File size: 15,132 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""End-to-end test of score.py on a synthetic world. usage: python -I test_cli.py [workdir]
Checks: scoring and score-file content, hand-computed CER, post-processing counts from raw output, incremental behaviour, refusal of
locked sets (the manifest of the locked set does not exist, so any attempt to open it would be visible), the gate flag and file,
registry names with parentheses, ragged and incomplete prediction files, reference mismatch stop, summary.tsv."""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import traceback

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import synth_world as sw  # noqa: E402

SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py")
RESULTS = []


def test(fn):
    try:
        fn()
        RESULTS.append((fn.__name__, True))
        print("PASS", fn.__name__)
    except Exception:  # noqa: BLE001
        RESULTS.append((fn.__name__, False))
        print("FAIL", fn.__name__)
        print(traceback.format_exc())
    return fn


W = {}


def run(args, expect_rc=None):
    cmd = [sys.executable, "-I", SCORE, "--registry", W["reg"], "--preds", W["preds"], "--out", W["out"], "--B", "200",
           "--settle", "0", "--ktrain", os.path.join(W["root"], "no_ktrain.json"), "--gate-file", W["gate"]] + args
    p = subprocess.run(cmd, capture_output=True, text=True)
    if expect_rc is not None:
        assert p.returncode == expect_rc, (p.returncode, p.stdout[-800:], p.stderr[-1500:])
    return p


def load(rel):
    return json.load(open(os.path.join(W["out"], rel), encoding="utf-8"))


@test
def t_build_world():
    root = sys.argv[1] if len(sys.argv) > 1 else tempfile.mkdtemp(prefix="r5eval_cli_")
    shutil.rmtree(root, ignore_errors=True)
    os.makedirs(root)
    W["root"] = root
    W["preds"], W["out"] = os.path.join(root, "preds"), os.path.join(root, "scores")
    W["gate"] = os.path.join(root, "RULE", "test_pass_started.txt")
    W["reg"] = os.path.join(root, "evalsets.json")
    man = os.path.join(root, "manifests")
    v1 = sw.make_manifest(os.path.join(man, "kohtd_screen_v1.tsv"), "v1", 30, 10, seed=1)
    cl = sw.make_manifest(os.path.join(man, "synth_clutter_val.tsv"), "cl", 10, 10, clutter=True, kind="clutter", unit="line")
    sw.write_registry(W["reg"], [
        {"name": "V1", "manifest": os.path.join(man, "kohtd_screen_v1.tsv"), "split": "val", "locked": False, "group_unit": "form"},
        {"name": "synth_clutter_val", "manifest": os.path.join(man, "synth_clutter_val.tsv"), "split": "val", "locked": False},
        {"name": "kohtd_test (P1)", "manifest": os.path.join(man, "kohtd_test.tsv"), "split": "test", "locked": True},
    ])
    sw.write_preds(os.path.join(W["preds"], "A1", "short", "V1.tsv"), v1, 0.10, seed=2)
    sw.write_meta(os.path.join(W["preds"], "A1", "short", "meta.json"), conf_logprob=False, peak_mem_reserved_batch1_GiB=2.0)
    sw.write_preds(os.path.join(W["preds"], "B1", "short", "V1.tsv"), v1, 0.05, seed=3, raw_wrap_rate=0.2)
    sw.write_meta(os.path.join(W["preds"], "B1", "short", "meta.json"))
    sw.write_preds(os.path.join(W["preds"], "A1", "short", "synth_clutter_val.tsv"), cl, 0.0, clutter_rate=0.0, with_conf=False)
    sw.write_preds(os.path.join(W["preds"], "B1", "short", "synth_clutter_val.tsv"), cl, 0.0, clutter_rate=0.3, seed=5, with_conf=False)
    # a locked test set whose manifest does not exist: scoring must refuse it without touching the manifest
    open(os.path.join(W["preds"], "A1", "short", "kohtd_test.tsv"), "w").write("id\tref\thyp\nx\ta\ta\n")
    # a smoke directory and an unregistered file
    os.makedirs(os.path.join(W["preds"], "smoke_arm", "short"))
    open(os.path.join(W["preds"], "smoke_arm", "short", "V1.tsv"), "w").write("id\tref\thyp\n")
    open(os.path.join(W["preds"], "A1", "short", "unknown_set.tsv"), "w").write("id\tref\thyp\n")
    W["v1_rows"] = v1


@test
def t_first_run_scores_validation_and_refuses_locked():
    p = run(["--workers", "2"], expect_rc=0)
    log = load("run_log.json")
    assert len(log["scored"]) == 4, log
    assert [r["set"] for r in log["refused_locked"]] == ["kohtd_test"], log["refused_locked"]
    assert len(log["unmatched"]) == 1 and log["unmatched"][0].endswith("unknown_set.tsv")
    assert any("smoke_arm" in d for d in log["skipped_dirs"])
    assert not os.path.exists(os.path.join(W["out"], "A1", "short", "kohtd_test.json"))
    assert os.path.exists(os.path.join(W["out"], "summary.tsv"))


@test
def t_score_file_values_match_hand_computation():
    sc = load("A1/short/V1.json")
    assert sc["status"] == "scored" and sc["locked"] is False and sc["registry_name"] == "V1"
    assert sc["coverage"]["complete"] and sc["coverage"]["scored_rows"] == 300
    # recompute the pooled CER independently with the frozen J2 library
    sys.path.insert(0, os.path.join(HERE, "..", "src"))
    from r5eval import frozen
    d = n = 0
    for line in open(os.path.join(W["preds"], "A1", "short", "V1.tsv"), encoding="utf-8").read().split("\n")[1:]:
        if not line:
            continue
        p = line.split("\t")
        d += frozen.j2.align(frozen.j2.norm(p[1]), frozen.j2.norm(p[2]))[0]
        n += len(frozen.j2.norm(p[1]))
    m = sc["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"]
    assert abs(m["value"] - d / n) < 1e-12 and m["num"] == d and m["den"] == n
    assert m["lo"] <= m["value"] <= m["hi"] or abs(m["lo"] - m["value"]) < 0.05
    assert sc["profiles"]["plain"]["groups"]["all"]["n_clusters"] == 30
    assert "macro" in sc["profiles"]["plain"] and "distribution" in sc["profiles"]["plain"]
    assert "calibration" in sc["profiles"]["plain"] and sc["set_info"]["conf_kind"] == "probability"
    # special letters were counted for kk
    mm = sc["profiles"]["plain"]["groups"]["all"]["metrics"]
    assert any(k.startswith("sl|kk|қ|miss_rate") for k in mm)


@test
def t_raw_output_gives_postprocessing_counts_and_vlm_confidence_kind():
    sc = load("B1/short/V1.json")
    pp = sc["postproc"]
    assert pp["pp_source"] == "raw" and pp["rows_with_raw_output"] == 300
    assert pp["outputs_changed_by_wrapper_stripping"] > 0          # about 20% of 300 outputs were fenced in the raw file
    assert pp["outputs_changed_by_postproc_total"] >= pp["outputs_changed_by_wrapper_stripping"] - 1
    plain = sc["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"]["value"]
    j2s = sc["profiles"]["j2strip"]["groups"]["all"]["metrics"]["cer"]["value"]
    assert abs(plain - j2s) < 1e-12      # the TSV hyp is the stripped text; fences only exist in the raw file, so stripping raw gives the same CER
    assert sc["set_info"]["conf_kind"] == "logprob"
    a1 = load("A1/short/V1.json")
    assert a1["postproc"]["pp_source"] == "tsv" and a1["postproc"]["outputs_changed_by_wrapper_stripping"] == 0


@test
def t_clutter_hr1():
    a = load("A1/short/synth_clutter_val.json")["profiles"]["plain"]["groups"]["all"]["metrics"]
    b = load("B1/short/synth_clutter_val.json")["profiles"]["plain"]["groups"]["all"]["metrics"]
    assert a["hr1"]["value"] == 0.0 and a["hr1"]["den"] == 100
    assert 0.1 < b["hr1"]["value"] < 0.5 and b["hr1"]["num"] > 0
    assert "cer" not in a      # clutter crops never enter CER (convention C4)


@test
def t_incremental_second_run_scores_nothing_and_modified_file_is_rescored():
    p = run(["--workers", "1"], expect_rc=0)
    log = load("run_log.json")
    assert len(log["scored"]) == 0 and log["up_to_date"] == 4
    path = os.path.join(W["preds"], "A1", "short", "V1.tsv")
    txt = open(path, encoding="utf-8").read().replace("қазақ", "казак", 1) if "қазақ" in open(path, encoding="utf-8").read() else open(path, encoding="utf-8").read()
    open(path, "w", encoding="utf-8").write(txt + "")
    sw.write_preds(path, W["v1_rows"], 0.12, seed=9)
    run(["--workers", "1"], expect_rc=0)
    log = load("run_log.json")
    assert len(log["scored"]) == 1 and log["up_to_date"] == 3


@test
def t_test_pass_flag_alone_does_not_open_locked_sets():
    run(["--test-pass"], expect_rc=0)
    log = load("run_log.json")
    assert log["gate_open"] is False and len(log["refused_locked"]) == 1
    assert not os.path.exists(os.path.join(W["out"], "A1", "short", "kohtd_test.json"))


@test
def t_gate_file_alone_does_not_open_locked_sets():
    os.makedirs(os.path.dirname(W["gate"]), exist_ok=True)
    open(W["gate"], "w").write("test pass started (test)\n")
    run([], expect_rc=0)                      # no --test-pass flag
    log = load("run_log.json")
    assert log["gate_open"] is False and len(log["refused_locked"]) == 1
    os.remove(W["gate"])


@test
def t_gate_open_scores_locked_set():
    man = os.path.join(W["root"], "manifests", "kohtd_test.tsv")
    rows = sw.make_manifest(man, "t1", 20, 10, split="test", seed=4)
    sw.write_preds(os.path.join(W["preds"], "A1", "short", "kohtd_test.tsv"), rows, 0.1, seed=6)
    os.makedirs(os.path.dirname(W["gate"]), exist_ok=True)
    open(W["gate"], "w").write("test pass started (test)\n")
    run(["--test-pass"], expect_rc=0)
    sc = load("A1/short/kohtd_test.json")
    assert sc["locked"] is True and sc["status"] == "scored" and sc["registry_name"] == "kohtd_test (P1)"
    assert os.path.exists(os.path.join(W["out"], "A1", "short", "kohtd_test.json"))
    # validation summary never lists locked sets
    s = open(os.path.join(W["out"], "summary.tsv"), encoding="utf-8").read()
    assert "A1\tshort" in s and "B1\tshort" in s


@test
def t_summary_columns():
    lines = open(os.path.join(W["out"], "summary.tsv"), encoding="utf-8").read().strip().split("\n")
    hdr = lines[0].split("\t")
    assert hdr[:2] == ["arm", "checkpoint"] and "V1_cer_greedy" in hdr and "HR1_clutter_val" in hdr
    rows = {l.split("\t")[0]: dict(zip(hdr, l.split("\t"))) for l in lines[1:]}
    assert rows["B1"]["V1_n"] == "300" and rows["B1"]["V1_complete"] == "1"
    assert float(rows["B1"]["V1_cer_greedy"]) < float(rows["A1"]["V1_cer_greedy"])
    assert rows["B1"]["peak_mem_reserved_gib"] == "9.5" and rows["A1"]["peak_mem_reserved_gib"] == "2"
    assert rows["B1"]["images_per_second"] == "55"
    assert float(rows["B1"]["HR1_clutter_val"]) > 0 and float(rows["A1"]["HR1_clutter_val"]) == 0.0


@test
def t_incomplete_ragged_and_mismatching_files():
    # incomplete: only the first 100 rows predicted
    p = os.path.join(W["preds"], "A1", "partial", "V1.tsv")
    sw.write_preds(p, W["v1_rows"][:100], 0.1, seed=3)
    # ragged row appended
    open(p, "a", encoding="utf-8").write("badrow\tonly_two_fields\n")
    # reference mismatch: a changed reference stops scoring
    p2 = os.path.join(W["preds"], "A1", "mismatch", "V1.tsv")
    sw.write_preds(p2, W["v1_rows"], 0.1, seed=3, ref_override={W["v1_rows"][0]["id"]: "other text"})
    run([], expect_rc=0)
    inc = load("A1/partial/V1.json")
    assert inc["status"] == "scored" and inc["coverage"]["scored_rows"] == 100 and inc["coverage"]["missing_ids"] == 200
    assert inc["coverage"]["ragged_rows_skipped"] == 1 and inc["coverage"]["complete"] is False
    mm = load("A1/mismatch/V1.json")
    assert mm["status"] == "ref_mismatch" and mm["coverage"]["ref_mismatch_rows"] == 1


@test
def t_file_named_by_registry_name_with_parentheses_reaches_the_summary():
    reg = json.load(open(W["reg"]))
    reg["sets"].append({"name": "V1 (screen)", "manifest": os.path.join(W["root"], "manifests", "kohtd_screen_v1.tsv"), "split": "val", "locked": False})
    json.dump(reg, open(W["reg"], "w"))
    sw.write_preds(os.path.join(W["preds"], "PN", "short", "V1 (screen).tsv"), W["v1_rows"], 0.08, seed=12)
    run([], expect_rc=0)
    assert os.path.exists(os.path.join(W["out"], "PN", "short", "V1 (screen).json"))
    lines = open(os.path.join(W["out"], "summary.tsv"), encoding="utf-8").read().strip().split("\n")
    hdr = lines[0].split("\t")
    row = [dict(zip(hdr, l.split("\t"))) for l in lines[1:] if l.startswith("PN\t")][0]
    assert row["V1_n"] == "300" and float(row["V1_cer_greedy"]) > 0


@test
def t_parity_with_vlma_postproc_score_on_wrapped_and_apostrophe_outputs():
    """Our plain and post-processed CER and WER equal VLMA's postproc.score() (the figures its eval_vlm.py writes) on the same rows, when the TSV
    hyp is N0 of the raw output as in the real VLMA files. The CER of clutter rows differs by design (convention C4) and is not in this set."""
    import random
    sys.path.insert(0, os.path.join(HERE, "..", "src"))
    from r5eval import frozen
    pp = frozen.vlma_pp
    root = W["root"]
    man = os.path.join(root, "manifests")
    vocab = ["o'zbek", "oʻzbek", "ma’no", "gʻoya", "so‘z", "kitob", "maktab", "oq", "to`g`ri", "shahar"]
    rows = sw.make_manifest(os.path.join(man, "pp_check.tsv"), "pc", 25, 8, lang="uz_latn", script="Latn", vocab=vocab, seed=5)
    reg = json.load(open(W["reg"]))
    reg["sets"].append({"name": "pp_check", "manifest": os.path.join(man, "pp_check.tsv"), "split": "val", "locked": False})
    json.dump(reg, open(W["reg"], "w"))
    rnd = random.Random(11)
    raws, refs = [], []
    d = os.path.join(W["preds"], "VP", "short")
    os.makedirs(d, exist_ok=True)
    with open(os.path.join(d, "pp_check.tsv"), "w", encoding="utf-8", newline="") as f, open(os.path.join(d, "pp_check.raw.jsonl"), "w", encoding="utf-8") as g:
        f.write("id\tref\thyp\tconf\tconf_min\thit_cap\tn_tokens\n")
        for r in rows:
            t = r["text"]
            form = rnd.choice(["plain", "fence", "tags", "heading", "bold", "apos", "damaged", "empty", "latex", "entity"])
            raw = {"plain": t, "fence": "```text\n" + t + "\n```", "tags": "<text>" + t + "</text>", "heading": "## " + t, "bold": "**" + t + "**",
                   "apos": t.replace("o'", "oʻ").replace("’", "ʼ"), "damaged": t[1:] + "x", "empty": "", "latex": "$\\text{" + t + "}$", "entity": t + " &amp; x"}[form]
            hyp = pp.plain_output(raw)
            refs.append(pp.plain_ref(t))
            raws.append(raw)
            f.write("\t".join([r["id"], pp.plain_ref(t), hyp, "-0.1", "-0.2", "0", "3"]) + "\n")
            g.write(json.dumps({"id": r["id"], "raw": raw, "hit_cap": False}, ensure_ascii=False) + "\n")
    sw.write_meta(os.path.join(d, "meta.json"))
    run([])
    sc = load("VP/short/pp_check.json")
    theirs = pp.score([r["text"] for r in rows], raws)
    for prof, key in (("plain", "plain"), ("pp", "pp")):
        m = sc["profiles"][prof]["groups"]["all"]["metrics"]
        assert abs(m["cer"]["value"] - theirs[key]["cer"]) < 1e-12, (prof, m["cer"]["value"], theirs[key]["cer"])
        assert abs(m["wer"]["value"] - theirs[key]["wer"]) < 1e-12, (prof, m["wer"]["value"], theirs[key]["wer"])
        assert abs(m["exact_match"]["value"] - theirs[key]["exact"]) < 1e-12
    n_changed = sum(1 for x in raws if pp.pp_output(x) != pp.plain_output(x))
    assert sc["postproc"]["outputs_changed_by_postproc_total"] == n_changed and n_changed > 0 and sc["postproc"]["pp_source"] == "raw"


if __name__ == "__main__":
    bad = [r for r in RESULTS if not r[1]]
    print("tests: %d passed, %d failed" % (len(RESULTS) - len(bad), len(bad)))
    sys.exit(1 if bad else 0)