File size: 11,895 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
"""summary.tsv: one row per (arm, checkpoint) with the main validation figures, built from the score JSONs and each
checkpoint's meta.json. Empty cells mean the figure does not exist yet (the set was not scored or has no such crops)."""
import glob
import json
import os

from . import ioutil, metautil


def _is_num(x):
    return isinstance(x, (int, float)) and not isinstance(x, bool)


def total_samples(meta):
    """Training samples of a checkpoint counted from the start of training. A continued run (a leader checkpoint, which continues from the short checkpoint) writes in meta.json
    samples_seen = the samples of that call only (minicpm_ocr_1_0 leader: 1,160,592) and samples_total = all samples including the earlier phase (1,310,592 = P_lead): this
    returns samples_total when it is a number that is not below samples_seen, else samples_seen (line arms and short runs write the cumulative figure in samples_seen). A meta whose
    train_flag says 'short of P' keeps samples_seen, because its samples_total may be the planned figure, not the reached one. None when neither exists."""
    if not isinstance(meta, dict):
        return None
    s, t = meta.get("samples_seen"), meta.get("samples_total")
    if _is_num(t) and (not _is_num(s) or t >= s) and "short of p" not in str(meta.get("train_flag") or "").lower():
        return t
    return s if _is_num(s) else None


COLUMNS = [
    ("arm", "arm name"), ("checkpoint", "checkpoint name"),
    ("samples_seen", "training samples seen in total, from the start of training: meta.json samples_total when it exists (a continued run such as a leader checkpoint counts the samples of its "
                     "earlier phase too, = P_lead when complete), else samples_seen; see samples_this_call"),
    ("learning_rate", "learning rate (meta.json)"), ("train_flag", "flag from training, for example short of P (meta.json)"),
    ("V1_complete", "1 if every V1 crop has a prediction"), ("V1_n", "V1 crops scored"),
    ("V1_cer_greedy", "V1 CER, plain output (decision figure)"), ("V1_cer_greedy_lo", "95% interval low"),
    ("V1_cer_greedy_hi", "95% interval high"),
    ("V1_cer_postproc", "V1 CER after the frozen post-processing script"), ("V1_cer_j2strip", "V1 CER with J2 wrapper stripping"),
    ("V1_cer_repaired_refs", "V1 CER against look-alike-repaired references"),
    ("V1_wer_greedy", "V1 WER, plain"), ("V1_exact_greedy", "V1 share of crops read perfectly"),
    ("HR1_clutter_val", "HR1: share of clutter-only validation crops with output"),
    ("HR2_V1", "HR2: inserted characters per reference character on V1"), ("HR3_V1", "HR3 on V1"), ("HR4_V1", "HR4 on V1"),
    ("HR2_typed_val", "HR2 on the typed validation lines"), ("HR3_typed_val", "HR3 on the typed validation lines"),
    ("HR4_typed_val", "HR4 on the typed validation lines"),
    ("kohtd_val_cer_greedy", "CER on all KOHTD validation crops"),
    ("typed_macro_cer", "macro CER over languages on the typed synthetic validation lines"),
    ("hand_synth_macro_cer", "macro CER over languages on the synthetic handwriting validation lines"),
    ("unseen_font_cer", "CER on synthetic handwriting lines in held-out fonts"),
    ("seen_font_cer", "CER on synthetic handwriting lines in training fonts"),
    ("hkr_val_cer", "CER on HKR validation words (the s2000 subset when the full set was not scored)"),
    ("chd_val_cer", "CER on CHD validation words (s2000 subset when the full set was not scored)"),
    ("school_val_cer", "CER on school notebook validation words (s2000 subset when the full set was not scored)"),
    ("print_real_macro_cer", "macro CER over languages on the real printed validation lines"),
    ("curve_v1_cer", "CER on the fixed learning-curve set (all text crops)"),
    ("postproc_changed_V1", "V1 outputs changed by the post-processing script (clarification G4)"),
    ("hit_cap_V1", "share of V1 outputs that stopped at the token cap"),
    ("peak_mem_reserved_gib", "peak GPU memory, torch max_memory_reserved (gate G figure, meta.json); see peak_mem_basis"),
    ("peak_mem_allocated_gib", "peak GPU memory, max_memory_allocated (meta.json)"),
    ("peak_mem_basis", "batch 1, or the evaluation batch (an upper bound for batch 1)"),
    ("images_per_second", "images per second (meta.json); see speed_basis"),
    ("speed_basis", "how the speed was measured: VLM batch 16 on V1, or line arms' evaluation batch, which are not comparable"),
    ("scored_utc", "time of the newest score file of this row"), ("n_score_files", "number of score files of this row"),
    ("seed", "1, or 2 for a second-seed row: the arm folder <arm>_s2 (maker-code VLM arms, line arms A1_s2 and A2_s2), or a checkpoint <ckpt>_seed2 / <ckpt>_s2 of the arm; voted for 'vote'"),
    ("seed_of_arm", "for a second-seed row, the arm it is the second seed of (the base arm); empty otherwise"),
    ("samples_this_call", "meta.json samples_seen as written: the samples of the training call that made this checkpoint (for a leader checkpoint, without its short phase)"),
]
SET_ALIASES = {"V1": ("V1", "kohtd_screen_v1"), "kohtd_val": ("kohtd_val",), "synth_typed_val": ("synth_typed_val",),
               "synth_hand_val": ("synth_hand_val",), "synth_clutter_val": ("synth_clutter_val",),
               "hkr_val": ("hkr_val", "hkr_val_s2000"), "chd_val": ("chd_val", "chd_val_s2000"),
               "school_val": ("school_val", "school_val_s2000"), "print_real_val": ("print_real_val",), "curve_v1": ("curve_v1",)}


def _find_meta_value(meta, test):
    """First numeric value in meta (nested dicts searched) whose key satisfies test(key)."""
    if isinstance(meta, dict):
        for k, v in meta.items():
            if isinstance(v, (int, float)) and not isinstance(v, bool) and test(str(k).lower()):
                return v
        for v in meta.values():
            if isinstance(v, dict):
                r = _find_meta_value(v, test)
                if r is not None:
                    return r
    return None


def _g(score, profile, group, metric, field="value"):
    try:
        return score["profiles"][profile]["groups"][group]["metrics"][metric][field]
    except (KeyError, TypeError):
        return None


def _macro(score, which="macro_language_cer", field="value"):
    try:
        return score["profiles"]["plain"]["macro"][which][field]
    except (KeyError, TypeError):
        return None


def _fmt(v):
    if v is None:
        return ""
    if isinstance(v, float):
        return "%.6g" % v
    return str(v)


def build_rows(scores_dir, preds_dir):
    """Returns list of row dicts, one per (arm, checkpoint), from validation (unlocked) score files only."""
    rows = {}
    for p in sorted(glob.glob(os.path.join(scores_dir, "*", "*", "*.json"))):
        try:
            sc = json.load(open(p, encoding="utf-8"))
        except ValueError:
            continue
        if sc.get("locked") or sc.get("status") != "scored":
            continue
        key = (sc["arm"], sc["checkpoint"])
        r = rows.setdefault(key, {"arm": sc["arm"], "checkpoint": sc["checkpoint"], "n_score_files": 0, "_sets": {}, "scored_utc": ""})
        r["n_score_files"] += 1
        r["scored_utc"] = max(r["scored_utc"], sc.get("scored_utc", ""))
        for nm in ioutil.score_names(sc) | {sc.get("registry_name") or sc["evalset"]}:        # a file called 'V1 (screen).tsv' answers to V1
            r["_sets"][nm] = sc
    out = []
    arm_names = {a for a, _ in rows}
    for (arm, ck), r in sorted(rows.items()):
        sets = r.pop("_sets")
        # second-seed rows are marked, not hidden: the arm folder <arm>_s2 is the second seed of <arm> (naming conventions 2 and 3 of the seed-2 runs), c_seed2 / c_s2 of VLMA arms
        if arm.endswith("_s2") and arm[:-3] in arm_names:
            r["seed"], r["seed_of_arm"] = "2", arm[:-3]
        elif ck.endswith(("_seed2", "_s2")) or "_seed2_" in ck:
            r["seed"], r["seed_of_arm"] = "2", arm
        else:
            r["seed"], r["seed_of_arm"] = ("voted" if ck == "vote" else "1"), ""

        def S(alias):
            for nm in SET_ALIASES[alias]:
                if nm in sets:
                    return sets[nm]
            return None
        meta = {}
        mp = os.path.join(preds_dir, arm, ck, "meta.json")
        if os.path.exists(mp):
            try:
                meta = json.load(open(mp, encoding="utf-8"))
            except ValueError:
                meta = {}
        r["samples_seen"] = total_samples(meta)
        r["samples_this_call"] = meta.get("samples_seen")
        r["learning_rate"] = metautil.learning_rate(meta)
        r["train_flag"] = meta.get("train_flag")
        v1 = S("V1")
        if v1:
            r["V1_complete"] = 1 if v1["coverage"]["complete"] else 0
            r["V1_n"] = v1["coverage"]["scored_rows"]
            r["V1_cer_greedy"] = _g(v1, "plain", "all", "cer")
            r["V1_cer_greedy_lo"] = _g(v1, "plain", "all", "cer", "lo")
            r["V1_cer_greedy_hi"] = _g(v1, "plain", "all", "cer", "hi")
            r["V1_cer_postproc"] = _g(v1, "pp", "all", "cer")
            r["V1_cer_j2strip"] = _g(v1, "j2strip", "all", "cer")
            rr = v1["profiles"].get("repaired_refs", {})
            r["V1_cer_repaired_refs"] = _g(v1, "repaired_refs", "all", "cer") if "groups" in rr else r["V1_cer_greedy"]
            r["V1_wer_greedy"] = _g(v1, "plain", "all", "wer")
            r["V1_exact_greedy"] = _g(v1, "plain", "all", "exact_match")
            r["HR2_V1"] = _g(v1, "plain", "all", "ins_rate")
            r["HR3_V1"] = _g(v1, "plain", "all", "hr3")
            r["HR4_V1"] = _g(v1, "plain", "all", "hr4")
            r["postproc_changed_V1"] = v1.get("postproc", {}).get("outputs_changed_by_postproc_total")
            r["hit_cap_V1"] = _g(v1, "plain", "all", "hit_cap_rate")
        kv = S("kohtd_val")
        if kv:
            r["kohtd_val_cer_greedy"] = _g(kv, "plain", "all", "cer")
        cl = S("synth_clutter_val")
        if cl:
            r["HR1_clutter_val"] = _g(cl, "plain", "all", "hr1")
        ty = S("synth_typed_val")
        if ty:
            r["typed_macro_cer"] = _macro(ty)
            r["HR2_typed_val"] = _g(ty, "plain", "all", "ins_rate")
            r["HR3_typed_val"] = _g(ty, "plain", "all", "hr3")
            r["HR4_typed_val"] = _g(ty, "plain", "all", "hr4")
        hs = S("synth_hand_val")
        if hs:
            r["hand_synth_macro_cer"] = _macro(hs)
            r["unseen_font_cer"] = _g(hs, "plain", "fontgroup:unseen", "cer")
            r["seen_font_cer"] = _g(hs, "plain", "fontgroup:seen", "cer")
        for a, col in (("hkr_val", "hkr_val_cer"), ("chd_val", "chd_val_cer"), ("school_val", "school_val_cer"), ("curve_v1", "curve_v1_cer")):
            s_ = S(a)
            if s_:
                r[col] = _g(s_, "plain", "all", "cer")
        pr = S("print_real_val")
        if pr:
            r["print_real_macro_cer"] = _macro(pr)
        mm = metautil.memory(meta)
        r["peak_mem_reserved_gib"], r["peak_mem_allocated_gib"], r["peak_mem_basis"] = mm["reserved_gib"], mm["allocated_gib"], mm["basis"]
        sp = metautil.speed(meta)
        r["images_per_second"], r["speed_basis"] = sp["images_per_second"], sp["basis"]
        out.append(r)
    return out


def write_summary(scores_dir, preds_dir, out_tsv):
    rows = build_rows(scores_dir, preds_dir)
    os.makedirs(os.path.dirname(os.path.abspath(out_tsv)), exist_ok=True)
    tmp = out_tsv + ".tmp"
    with open(tmp, "w", encoding="utf-8", newline="") as f:
        f.write("\t".join(c for c, _ in COLUMNS) + "\n")
        for r in rows:
            f.write("\t".join(_fmt(r.get(c)) for c, _ in COLUMNS) + "\n")
    os.replace(tmp, out_tsv)
    with open(os.path.join(os.path.dirname(os.path.abspath(out_tsv)), "summary_columns.json"), "w", encoding="utf-8") as f:
        json.dump([{"column": c, "meaning": m} for c, m in COLUMNS], f, indent=1)
    return rows