turkic-ocr-code / tests_r5eval /test_verdict.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
58.3 kB
"""Tests of verdictlib (units and boundaries pinned), selection.py, and verdict.py on synthetic fake scores.
usage: python -I test_verdict.py [workdir]
Everything here is synthetic: no real prediction, manifest or score file is read."""
import json
import os
import random
import shutil
import subprocess
import sys
import tempfile
import traceback
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, "..", "src"))
import numpy as np # noqa: E402
import synth_world as sw # noqa: E402
from r5eval import selection, stats, verdictlib as vl # noqa: E402
SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py")
VERDICT = os.path.join(HERE, "..", "scripts", "r5eval", "verdict.py")
BUILD_KT = os.path.join(HERE, "..", "scripts", "r5eval", "build_ktrain.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
# ------------------------------------------------------------------ layer 1: units and boundaries ----------------------------
A1 = {"hr1": 0.01, "hr2": 0.01, "hr3": 0.02, "hr4_T1": 0.0, "hr4_T2": 0.0}
def res(x):
return vl.veto(x, A1)["components"]
@test
def t_veto_hr1_boundaries():
base = dict(A1)
assert res(dict(base, hr1=0.03))["HR1"]["result"] == "pass" # max(2 x 0.01, 0.01 + 0.02) = 0.03: equality passes
assert res(dict(base, hr1=0.0301))["HR1"]["result"] == "fail"
z = {"hr1": 0.0, "hr2": 0.01, "hr3": 0.02, "hr4_T1": 0, "hr4_T2": 0}
assert vl.veto(dict(z, hr1=0.02), z)["components"]["HR1"]["result"] == "pass" # A1 at 0: limit is +2 points
assert vl.veto(dict(z, hr1=0.0201), z)["components"]["HR1"]["result"] == "fail"
a4 = dict(z, hr1=0.04) # A1 at 4%: relative limit 8%, absolute cap 5% applies
assert vl.veto(dict(a4, hr1=0.05), a4)["components"]["HR1"]["result"] == "pass"
assert vl.veto(dict(a4, hr1=0.0501), a4)["components"]["HR1"]["result"] == "fail"
a6 = dict(z, hr1=0.06) # A1 above 5%: the cap is dropped for all arms
r = vl.veto(dict(a6, hr1=0.12), a6)["components"]["HR1"]
assert r["result"] == "pass" and r["cap_dropped_because_A1_exceeds_5_percent"] is True
assert vl.veto(dict(a6, hr1=0.13), a6)["components"]["HR1"]["result"] == "fail"
assert vl.veto(a6, a6)["components"]["HR1"]["result"] == "pass" # A1 against itself
@test
def t_veto_hr2_hr3_hr4_boundaries():
b = dict(A1)
assert res(dict(b, hr2=0.0149))["HR2"]["result"] == "pass" # above the absolute limit 0.013 but not above 1.5 x 0.01
assert res(dict(b, hr2=0.0151))["HR2"]["result"] == "fail" # above both
assert res(dict(b, hr2=0.0129))["HR2"]["result"] == "pass"
assert res(dict(b, hr3=0.025))["HR3"]["result"] == "pass" # A1 + 0.5 points, equality passes
assert res(dict(b, hr3=0.0251))["HR3"]["result"] == "fail"
assert res(dict(b, hr4_T1=0.001, hr4_T2=0.001))["HR4"]["result"] == "pass"
assert res(dict(b, hr4_T1=0.0011))["HR4"]["result"] == "fail"
assert res(dict(b, hr4_T1=0.0, hr4_T2=0.0011))["HR4"]["result"] == "fail" # on T2 alone
assert res(dict(b, hr4_T1=0.0, hr4_T2=None))["HR4"]["result"] == "not evaluable"
assert res(dict(b, hr4_T1=0.0021, hr4_T2=None))["HR4"]["result"] == "fail" # a figure above the limit decides even if the other is missing
assert vl.veto(dict(b, hr1=None), A1)["result"] == "not evaluable"
assert vl.veto(dict(b, hr1=None, hr3=0.5), A1)["result"] == "fail"
assert vl.veto(A1, A1)["result"] == "pass"
@test
def t_typed_noninferiority_units():
ref = {"kk": 0.02, "tr": 0.03, "az": 0.04}
aud = ["kk", "tr", "az"]
ok = vl.typed_noninferiority({"kk": 0.0230, "tr": 0.0330, "az": 0.0430}, ref, aud) # +0.003 in every language: macro at the limit
assert ok["result"] == vl.MET
assert vl.typed_noninferiority({"kk": 0.0231, "tr": 0.0331, "az": 0.0431}, ref, aud)["result"] == vl.NOT_MET # macro +0.0031
# one language +0.01 and the others lower: macro fine, language at its limit
assert vl.typed_noninferiority({"kk": 0.03, "tr": 0.02, "az": 0.03}, ref, aud)["result"] == vl.MET
r = vl.typed_noninferiority({"kk": 0.0301, "tr": 0.0, "az": 0.0}, ref, aud) # kk +1.01 points, macro far below
assert r["result"] == vl.NOT_MET and r["macro_ok"] is True and r["languages_ok"] is False
assert vl.typed_noninferiority({"kk": 0.02}, ref, aud)["result"] == vl.NOT_EVAL # a language is missing
assert vl.typed_noninferiority({"kk": 0.02}, ref, None)["result"] == vl.NOT_EVAL # no audited list
assert vl.typed_noninferiority({"kk": 0.02}, ref, [])["result"] == vl.NOT_EVAL
@test
def t_gate_g_units():
assert abs(vl.GATE_DECIMAL_GIB - 22.3517) < 1e-3 and vl.GATE_BINARY_GIB == 24.0
assert vl.gate_g(None, 22.3)["result"] == vl.MET
r = vl.gate_g(None, 22.4) # between the two readings of 24 GB
assert r["result"] == vl.NOT_MET and r["result_binary_reading"] == vl.MET
assert vl.gate_g(None, 24.1)["result_binary_reading"] == vl.NOT_MET
assert vl.gate_g(20.0, None)["result"] == vl.NOT_EVAL # reader only: whole pipeline not measured
assert vl.gate_g(20.0, None, reader_only_counts=True)["result"] == vl.MET
assert vl.gate_g(23.0, None)["result"] == vl.NOT_MET # the reader alone already exceeds the limit
assert vl.gate_g(None, None)["result"] == vl.NOT_EVAL
def fake_cmp_factory(table, sd=0.01, n=3000, seed=0):
"""table: (x, y, endpoint) -> d_rel. Builds a replicate array so that p-values and bounds exist."""
rng = np.random.default_rng(seed)
def fn(x, y, ep):
d = table.get((x, y, ep))
if d is None:
return None
reps = d + sd * rng.standard_normal(n)
return {"cer_x": 0.05 * (1 + d), "cer_y": 0.05, "d_rel": d, "d_abs": 0.05 * d, "B": n, "K": 100,
"d_rel_ci95": [float(np.percentile(reps, 2.5)), float(np.percentile(reps, 97.5))],
"p_better": float((1 + np.sum(reps >= 0)) / (n + 1)), "prob_improvement": float(np.mean(reps < 0)), "_rel_reps": reps}
return fn
def figs(table, present=("A1", "A2", "B1"), **over):
base_veto = {"hr1": 0.0, "hr2": 0.01, "hr3": 0.02, "hr4_T1": 0.0, "hr4_T2": 0.0}
F = {"present": set(present), "cmp_fn": fake_cmp_factory(table),
"veto": {r: dict(base_veto) for r in present},
"typed": {r: {"kk": 0.02, "tr": 0.03} for r in present}, "audited": ["kk", "tr"],
"gate": {r: {"reader_gib": 9.0, "pipeline_gib": 12.0} for r in present},
"cer": {r: {"P1": 0.05, "P2": 0.1} for r in present}, "val_cer": {r: 0.05 for r in present},
"params": {"B1": 1.0, "B2": 0.8}, "reader_only_counts": False}
F.update(over)
return F
def cl(out, cid):
return next(c for c in out["clauses"] if c["id"] == cid)
@test
def t_decide_b1_wins_on_every_evaluable_clause():
tab = {("B1", "A1", "P1"): -0.30, ("B1", "A1", "P2"): -0.25, ("A2", "A1", "P1"): 0.20, ("A2", "A1", "P2"): 0.20}
out = vl.decide(figs(tab))
assert cl(out, "4.a")["result"] == vl.MET and cl(out, "4.b")["result"] == vl.NOT_EVAL
assert cl(out, "4.c")["result"] == vl.MET and cl(out, "4.d")["result"] == vl.MET and cl(out, "4.e")["result"] == vl.MET
assert out["decision"]["section4"].startswith("met on every evaluable clause")
assert out["decision"]["ship"] == "B1" and out["decision"]["line_branch_choice"] == "A1"
assert cl(out, "3.1")["result"] == vl.NOT_MET # A2 is 20% worse than A1: it does not qualify
@test
def t_decide_margin_boundary_and_holm():
# d exactly at -M passes 4.a; slightly above fails
tab = {("B1", "A1", "P1"): -0.10, ("B1", "A1", "P2"): -0.10, ("A2", "A1", "P1"): 0.2, ("A2", "A1", "P2"): 0.2}
F = figs(tab)
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.001) # replicates tight around the point estimate so Holm rejects
out = vl.decide(F)
assert cl(out, "4.a")["result"] == vl.MET
tab[("B1", "A1", "P1")] = -0.0999
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.001)
assert cl(vl.decide(F), "4.a")["result"] == vl.NOT_MET
# a wide interval: point estimate beyond the margin, but Holm does not reject
tab = {("B1", "A1", "P1"): -0.15, ("B1", "A1", "P2"): -0.15, ("A2", "A1", "P1"): 0.2, ("A2", "A1", "P2"): 0.2}
F = figs(tab)
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.2)
out = vl.decide(F)
assert cl(out, "4.a")["result"] == vl.NOT_MET
assert out["decision"]["ship"] == "A1"
@test
def t_decide_a2_qualifies_when_clearly_better_and_clean():
tab = {("B1", "A1", "P1"): -0.02, ("B1", "A1", "P2"): -0.02, ("A2", "A1", "P1"): -0.30, ("A2", "A1", "P2"): -0.30}
F = figs(tab)
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.02)
out = vl.decide(F)
assert cl(out, "3.1")["result"] == vl.MET and out["decision"]["line_branch_choice"] == "A2"
# an audited language 1.5 points worse stops A2
F2 = figs(tab)
F2["cmp_fn"] = fake_cmp_factory(tab, sd=0.02)
F2["typed"]["A2"] = {"kk": 0.035, "tr": 0.03}
out = vl.decide(F2)
assert cl(out, "3.1.b")["result"] == vl.NOT_MET and out["decision"]["line_branch_choice"] == "A1"
@test
def t_decide_veto_failure_blocks_b1_and_missing_data_is_not_evaluable():
tab = {("B1", "A1", "P1"): -0.4, ("B1", "A1", "P2"): -0.4, ("A2", "A1", "P1"): 0.1, ("A2", "A1", "P2"): 0.1}
F = figs(tab)
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.01)
F["veto"]["B1"]["hr4_T1"] = 0.0011
out = vl.decide(F)
assert cl(out, "4.d")["result"] == vl.NOT_MET and out["decision"]["section4"] == vl.NOT_MET and out["decision"]["ship"] == "A1"
assert out["decision"]["b1_handwriting_teacher_under_5"] is False # fails the veto, so not a teacher
F = figs(tab)
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.01)
F["audited"] = None
out = vl.decide(F)
assert cl(out, "4.c")["result"] == vl.NOT_EVAL and out["decision"]["section4"] == vl.NOT_EVAL and out["decision"]["ship"] == "undetermined"
F = figs(tab)
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.01)
F["gate"]["B1"] = {"reader_gib": 9.0, "pipeline_gib": None}
out = vl.decide(F)
assert cl(out, "4.e")["result"] == vl.NOT_EVAL
F["reader_only_counts"] = True
assert cl(vl.decide(F), "4.e")["result"] == vl.MET
# futility
F = figs(tab)
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.01)
F["val_cer"]["B1"] = 0.0551
out = vl.decide(F)
assert cl(out, "6.1")["result"] == vl.NOT_MET and out["decision"]["section4"] == vl.NOT_MET
F["val_cer"]["B1"] = 0.055
assert cl(vl.decide(F), "6.1")["result"] == vl.MET
@test
def t_decide_teacher_clause_and_a3_a4():
tab = {("B1", "A1", "P1"): -0.05, ("B1", "A1", "P2"): -0.05, ("A2", "A1", "P1"): 0.1, ("A2", "A1", "P2"): 0.1,
("A4", "A1", "P1"): -0.3, ("A4", "A1", "P2"): -0.3}
F = figs(tab, present=("A1", "A2", "A4", "B1"))
F["cmp_fn"] = fake_cmp_factory(tab, sd=0.005)
out = vl.decide(F)
assert cl(out, "4.a")["result"] == vl.NOT_MET # beats A1 but not by 10%
assert out["decision"]["b1_handwriting_teacher_under_5"] is True # better on P1 with Holm bound below zero, passes the veto
assert cl(out, "3.5")["result"] == vl.MET and out["decision"]["line_branch_choice"] == "A4"
# with A4 chosen, 4.a' needs B1 against A4: absent comparison -> not evaluable
assert cl(out, "4.a'")["result"] == vl.NOT_EVAL
@test
def t_decide_without_a1_or_b1():
out = vl.decide(figs({}, present=("A2",)))
assert out["decision"]["ship"].startswith("undetermined")
tab = {("A2", "A1", "P1"): 0.1, ("A2", "A1", "P2"): 0.1}
out = vl.decide(figs(tab, present=("A1", "A2")))
assert cl(out, "4")["result"] == vl.NOT_EVAL and out["decision"]["ship"] == "undetermined"
@test
def t_selection_tie_rule_and_size_classes():
rows = [{"arm": "m1", "included": True, "v1_cer": 0.100, "images_per_second": 20.0, "size_class": "middle"},
{"arm": "m2", "included": True, "v1_cer": 0.104, "images_per_second": 50.0, "size_class": "small"},
{"arm": "m3", "included": True, "v1_cer": 0.1051, "images_per_second": 90.0, "size_class": "large"},
{"arm": "m4", "included": False, "v1_cer": None, "images_per_second": None, "size_class": "large"}]
ch, why = selection.pick(rows)
assert ch["arm"] == "m2" # m3 is 5.1% above the lowest, outside the tie pool; m2 is within 5% and faster than m1
assert selection.size_class(0.26) == "small" and selection.size_class(0.5) == "middle" and selection.size_class(1.5) == "middle"
assert selection.size_class(1.51) == "large" and selection.size_class(None) is None
rows[1]["images_per_second"] = None
ch, why = selection.pick(rows)
assert ch["arm"] == "m1" and "speed missing" in why
# ------------------------------------------------------------------ layer 2: synthetic scores through the real pipeline -----
W = {}
TR = ["çay", "ışık", "İstanbul", "gözlük", "şeker", "üzüm", "öğrenci", "ağaç", "Işıl", "kitap", "okul", "çiçek"]
AZ = ["ağıl", "əsas", "çörək", "gözəl", "məktəb", "şəhər", "Əli", "kitab", "dərs", "ölkə", "üzüm", "ildırım"]
def concat_manifests(path, parts):
lines = None
rows = []
for p in parts:
t = open(p, encoding="utf-8").read().rstrip("\n").split("\n")
lines = t[0]
rows += t[1:]
open(path, "w", encoding="utf-8").write(lines + "\n" + "\n".join(rows) + "\n")
def rows_of(path):
t = open(path, encoding="utf-8").read().rstrip("\n").split("\n")
hdr = t[0].split("\t")
return [dict(zip(hdr, l.split("\t"))) for l in t[1:]]
def build_world(root):
W["root"] = root
man = os.path.join(root, "manifests")
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")
# K_train: a train manifest that contains the first half of the Kazakh vocabulary
half = sw.VOCAB[:14]
sw.make_manifest(os.path.join(man, "train_real.tsv"), "tr", 10, 20, split="train", vocab=half, seed=5)
mix = os.path.join(root, "mix_v1.yaml")
open(mix, "w").write("mix:\n members:\n - {name: real, manifest: %s/train_real.tsv, share: 1.0}\n" % man)
subprocess.run([sys.executable, "-I", BUILD_KT, "--mix", mix, "--out", os.path.join(root, "p2"), "--extra-text"], check=True,
capture_output=True)
W["ktrain"] = os.path.join(root, "p2", "ktrain_manifest.json")
t1 = sw.make_manifest(os.path.join(man, "kohtd_test.tsv"), "t1", 60, 10, split="test", seed=11)
val = sw.make_manifest(os.path.join(man, "kohtd_val.tsv"), "vv", 30, 10, split="val", seed=12)
sw.make_manifest(os.path.join(man, "ty_kk.tsv"), "tkk", 10, 8, split="test", kind="typed_synth", unit="line", seed=13)
sw.make_manifest(os.path.join(man, "ty_tr.tsv"), "ttr", 10, 8, split="test", lang="tr", script="Latn", kind="typed_synth", unit="line",
vocab=TR, seed=14)
sw.make_manifest(os.path.join(man, "ty_az.tsv"), "taz", 10, 8, split="test", lang="az", script="Latn", kind="typed_synth", unit="line",
vocab=AZ, seed=15)
concat_manifests(os.path.join(man, "synth_typed_test.tsv"), [os.path.join(man, n) for n in ("ty_kk.tsv", "ty_tr.tsv", "ty_az.tsv")])
cl_rows = sw.make_manifest(os.path.join(man, "synth_clutter_test.tsv"), "ct", 10, 20, split="test", clutter=True, kind="clutter", unit="line")
ty = rows_of(os.path.join(man, "synth_typed_test.tsv"))
sw.write_registry(os.path.join(root, "evalsets.json"), [
{"name": "kohtd_test (P1)", "manifest": os.path.join(man, "kohtd_test.tsv"), "split": "test", "locked": True, "group_unit": "form"},
{"name": "kohtd_val", "manifest": os.path.join(man, "kohtd_val.tsv"), "split": "val", "locked": False},
{"name": "synth_typed_test", "manifest": os.path.join(man, "synth_typed_test.tsv"), "split": "test", "locked": True},
{"name": "synth_clutter_test", "manifest": os.path.join(man, "synth_clutter_test.tsv"), "split": "test", "locked": True}])
W["rows"] = {"t1": t1, "val": val, "ty": ty, "cl": cl_rows}
os.makedirs(os.path.dirname(W["gate"]), exist_ok=True)
open(W["gate"], "w").write("synthetic test pass\n")
# endpoints and selection
ep = {"confirmed": True, "B": 400, "seed": 20261121, "margin": 0.10,
"T1": {"evalsets": ["kohtd_test"], "P1_group": "all", "P2_group": "slice:P2"},
"T2": {"evalsets": ["synth_typed_test"], "audited_languages": ["kk", "tr", "az"]},
"clutter": {"evalsets": ["synth_clutter_test"]},
"validation": {"kohtd_val": ["kohtd_val"], "V1": ["V1"]}, "reader_only_counts_as_pipeline": True}
W["ep_path"] = os.path.join(root, "endpoints.json")
json.dump(ep, open(W["ep_path"], "w"))
def add_arm(arm, ck, rate, typed_rate, clutter_rate=0.0, loop_rate=0.0, seed=1, mem=9.5):
base = os.path.join(W["preds"], arm, ck)
sw.write_preds(os.path.join(base, "kohtd_test.tsv"), W["rows"]["t1"], rate, seed=seed, loop_rate=loop_rate)
sw.write_preds(os.path.join(base, "kohtd_val.tsv"), W["rows"]["val"], rate, seed=seed + 100)
sw.write_preds(os.path.join(base, "synth_typed_test.tsv"), W["rows"]["ty"], typed_rate, seed=77, with_conf=False)
sw.write_preds(os.path.join(base, "synth_clutter_test.tsv"), W["rows"]["cl"], 0.0, seed=seed + 5, clutter_rate=clutter_rate, with_conf=False)
sw.write_meta(os.path.join(base, "meta.json"), peak_mem_reserved_batch1_GiB=mem)
def run_score():
cmd = [sys.executable, "-I", SCORE, "--registry", os.path.join(W["root"], "evalsets.json"), "--preds", W["preds"], "--out", W["out"],
"--B", "200", "--settle", "0", "--ktrain", W["ktrain"], "--gate-file", W["gate"], "--test-pass", "--workers", "3"]
p = subprocess.run(cmd, capture_output=True, text=True)
assert p.returncode == 0, p.stdout[-1000:] + p.stderr[-2000:]
def write_selection(extra_roles):
roles = {"A1": {"arm": "A1", "checkpoint": "long"}, "B1": {"arm": "B1", "checkpoint": "short", "unique_params_b": 1.0}}
roles.update(extra_roles)
W["sel_path"] = os.path.join(W["root"], "selection.json")
json.dump({"roles": roles}, open(W["sel_path"], "w"))
def run_verdict(name, extra=()):
out = os.path.join(W["root"], name)
cmd = [sys.executable, "-I", VERDICT, "--scores", W["out"], "--selection", W["sel_path"], "--endpoints", W["ep_path"], "--out", out,
"--gate-file", W["gate"] + ".absent", "--synthetic"] + list(extra)
p = subprocess.run(cmd, capture_output=True, text=True)
assert p.returncode == 0, p.stdout[-800:] + p.stderr[-2000:]
return json.load(open(out, encoding="utf-8"))
@test
def t_world_and_scores_with_p2_slice():
root = sys.argv[1] if len(sys.argv) > 1 else tempfile.mkdtemp(prefix="r5eval_verdict_")
shutil.rmtree(root, ignore_errors=True)
os.makedirs(root)
build_world(root)
add_arm("A1", "long", 0.12, 0.02, seed=1)
add_arm("B1", "short", 0.03, 0.02, seed=2) # typed predictions are drawn with the same seed and rate: identical to A1's
run_score()
sc = json.load(open(os.path.join(W["out"], "B1", "short", "kohtd_test.json"), encoding="utf-8"))
assert sc["locked"] is True and sc["set_info"]["has_ktrain"] is True
sl = sc["set_info"]["slices"]
assert "slice:P2" in sl and "slice:P2b" in sl and "slice:P2_literal" in sl, sl
g = sc["profiles"]["plain"]["groups"]
assert g["slice:P2"]["n_items"] < g["all"]["n_items"] and g["slice:P2"]["n_items"] > 100
assert g["slice:P2b"]["n_items"] == g["slice:P2"]["n_items"] # no text outside the hand training labels in this world
assert "n2fold" in json.load(open(os.path.join(W["out"], "B1", "short", "synth_typed_test.json")))["profiles"]
# test labels changed by the look-alike repair would be listed here; this world has none
assert "cluster_ids" in sc["profiles"]["plain"]
@test
def t_verdict_b1_clearly_better():
write_selection({})
v = run_verdict("verdict_b1.json")
assert v["synthetic"] is True and v["locked_scores_read"] is True
c = {x["id"]: x for x in v["clauses"]}
assert c["4.a"]["result"] == vl.MET, c["4.a"]
assert c["4.b"]["result"] == vl.NOT_EVAL and c["4.c"]["result"] == vl.MET and c["4.d"]["result"] == vl.MET and c["4.e"]["result"] == vl.MET
assert v["decision"]["ship"] == "B1" and v["decision"]["section4"].startswith("met on every evaluable clause")
assert v["sensitivity_other_reading_of_references"]["clauses_that_flip"] == [] # the world has no mixed-script labels
hf = v["holm_family"]["B1_vs_A1_P1"]
assert hf["evaluable"] and hf["holm_reject"] and hf["d_rel"] < -0.5 and hf["holm_upper_bound"] < 0
assert v["holm_family"]["A2_vs_A1_P1"]["evaluable"] is False # no A2 in this world: p = 1.0 keeps the family size at 4
assert "A1" in v["descriptive"] and "B1" in v["descriptive"]
assert v["summary"][0].startswith("Line-branch choice: A1")
@test
def t_verdict_b1_worse_and_hallucinating():
add_arm("B1", "short", 0.20, 0.02, clutter_rate=0.3, loop_rate=0.05, seed=3)
run_score()
v = run_verdict("verdict_b1_bad.json")
c = {x["id"]: x for x in v["clauses"]}
assert c["4.a"]["result"] == vl.NOT_MET and c["4.d"]["result"] == vl.NOT_MET
comps = c["4.d"]["figures"]
assert comps["HR1"]["result"] == "fail" and comps["HR4"]["result"] == "fail"
assert v["decision"]["ship"] == "A1" and v["decision"]["section4"] == vl.NOT_MET
assert v["decision"]["b1_handwriting_teacher_under_5"] is False
@test
def t_verdict_refuses_locked_scores_without_gate_or_synthetic_flag():
out = os.path.join(W["root"], "verdict_closed.json")
cmd = [sys.executable, "-I", VERDICT, "--scores", W["out"], "--selection", W["sel_path"], "--endpoints", W["ep_path"], "--out", out,
"--gate-file", W["gate"] + ".absent"]
p = subprocess.run(cmd, capture_output=True, text=True)
assert p.returncode == 0
v = json.load(open(out, encoding="utf-8"))
assert v["locked_scores_read"] is False and v["decision"]["ship"].startswith("undetermined")
assert any("locked score file ignored" in n for n in v["notes"])
@test
def t_verdict_with_gate_file_present_reads_locked_scores():
out = os.path.join(W["root"], "verdict_open.json")
cmd = [sys.executable, "-I", VERDICT, "--scores", W["out"], "--selection", W["sel_path"], "--endpoints", W["ep_path"], "--out", out,
"--gate-file", W["gate"]]
p = subprocess.run(cmd, capture_output=True, text=True)
assert p.returncode == 0
v = json.load(open(out, encoding="utf-8"))
assert v["locked_scores_read"] is True and v["synthetic"] is False and v["test_pass_gate_file_exists"] is True
@test
def t_select_b1b2_cli_on_validation_scores():
# two VLM-like arms with V1 scores in a fresh scores folder
root = os.path.join(W["root"], "sel")
os.makedirs(root)
man = os.path.join(root, "manifests")
v1 = sw.make_manifest(os.path.join(man, "kohtd_screen_v1.tsv"), "v1", 20, 10, seed=21)
sw.write_registry(os.path.join(root, "reg.json"), [{"name": "V1", "manifest": os.path.join(man, "kohtd_screen_v1.tsv"), "split": "val", "locked": False}])
for arm, rate, ips, mem in (("big_vlm", 0.05, 30.0, 12.0), ("small_vlm", 0.052, 90.0, 3.0), ("worse_vlm", 0.2, 200.0, 2.0)):
sw.write_preds(os.path.join(root, "preds", arm, "short", "V1.tsv"), v1, rate, seed=hash(arm) % 1000)
sw.write_meta(os.path.join(root, "preds", arm, "short", "meta.json"), images_per_second_batch16_V1=ips)
r = subprocess.run([sys.executable, "-I", SCORE, "--registry", os.path.join(root, "reg.json"), "--preds", os.path.join(root, "preds"), "--out",
os.path.join(root, "scores"), "--B", "100", "--settle", "0", "--ktrain", os.path.join(root, "no_ktrain.json")], capture_output=True, text=True)
assert r.returncode == 0, r.stderr[-1500:]
info = {"big_vlm": {"unique_params_b": 2.0}, "small_vlm": {"unique_params_b": 0.3}, "worse_vlm": {"unique_params_b": 1.0}}
json.dump(info, open(os.path.join(root, "arms_info.json"), "w"))
sel_py = os.path.join(HERE, "..", "scripts", "r5eval", "select_b1b2.py")
r = subprocess.run([sys.executable, "-I", sel_py, "--scores", os.path.join(root, "scores"), "--out", os.path.join(root, "selection.json"),
"--arms-info", os.path.join(root, "arms_info.json"), "--allow-short-b1"], capture_output=True, text=True)
assert r.returncode == 0, r.stderr[-1500:]
s = json.load(open(os.path.join(root, "selection.json")))
assert s["provisional"] is True and any("PROVISIONAL" in w for w in s["warnings"])
# CERs of big_vlm and small_vlm differ by far less than 5% only if the random corruption lands that way; accept either, but the rule must hold
table = {t["arm"]: t for t in s["table"]}
lo = min(t["v1_cer"] for t in table.values() if t["included"])
pool = [a for a, t in table.items() if t["included"] and t["v1_cer"] <= 1.05 * lo]
if len(pool) > 1:
assert s["B1"] == max(pool, key=lambda a: table[a]["images_per_second"])
else:
assert s["B1"] == pool[0]
assert s["B2"] is not None and table[s["B2"]]["size_class"] != table[s["B1"]]["size_class"]
assert os.path.exists(os.path.join(root, "selection.json.sha256"))
# clarification H14: paired form-bootstrap intervals for every pair among the top six VLM arms (here three arms: three pairs)
pw = s["pairwise_top6_v1"]
assert len(pw["arms_in_order_of_V1_CER"]) == 3 and len(pw["pairs"]) == 3 and "descriptive" in pw["label"]
for p_ in pw["pairs"]:
assert p_["d_abs_ci95"][0] <= p_["d_abs"] <= p_["d_abs_ci95"][1] and p_["d_abs"] <= 0 # the first arm of a pair has the lower V1 CER
worst = [p_ for p_ in pw["pairs"] if p_["second"] == "worse_vlm"]
assert len(worst) == 2 and all(p_["interval_below_zero_first_is_better"] for p_ in worst) # 20% against about 5%: the interval excludes zero
assert all("_docs" not in t for t in s["table"]) and s["arms_not_ranked_at_this_pick"] == []
# ------------------------------------------------------------------ amendment 3.3: two seeds (D4), reference arms and SOTA block (D5)
@test
def t_two_seed_t_statistics_known_values():
from scipy import stats as sps
K = 50
den = np.full(K, 100.0)
x1, x2, y1, y2 = np.full(K, 10.0), np.full(K, 12.0), np.full(K, 20.0), np.full(K, 20.0) # every cluster identical: bootstrap variance 0
r = stats.paired_two_seed_t([x1, x2], [den, den], [y1, y2], [den, den], B=300)
assert r["kind"] == "two_seed_t" and r["df"] == 2 and r["n_seeds_x"] == 2
assert abs(r["d_rel"] - (0.11 / 0.20 - 1)) < 1e-12
rsd2 = (np.std([0.10, 0.12], ddof=1) / 0.11) ** 2
assert abs(r["var_bootstrap"]) < 1e-18 and abs(r["relative_seed_sd_squared_pooled"] - rsd2 / 2) < 1e-12 # pooled over (n-1) weights: (rsd_X^2 + 0) / 2
se = np.sqrt(rsd2 / 2 * (1 / 2 + 1 / 2))
assert abs(r["se"] - se) < 1e-12
t975 = sps.t.ppf(0.975, 2)
assert abs(r["t_quantile_97_5"] - 4.302653) < 1e-5
assert abs(r["d_rel_ci95"][0] - (r["d_rel"] - t975 * se)) < 1e-12 and abs(r["d_rel_ci95"][1] - (r["d_rel"] + t975 * se)) < 1e-12
assert abs(r["p_better"] - sps.t.cdf(r["d_rel"] / se, 2)) < 1e-12
# Holm-adjusted upper bound with the t quantile: rank 1 of 4 uses 1 - 0.05/4
assert abs(stats.holm_bound_t(r["d_rel"], se, 2, 1, 4) - (r["d_rel"] + sps.t.ppf(1 - 0.05 / 4, 2) * se)) < 1e-12
# one seed on one side: only the seed term of the arm that has two seeds enters, df = 1 (pooled over the arms that have repeats)
r1 = stats.paired_two_seed_t([x1, x2], [den, den], [y1], [den], B=300)
assert r1["df"] == 1 and abs(r1["relative_seed_sd_squared_pooled"] - rsd2) < 1e-12
# two seeds of both arms, no variation anywhere: d is 0 and SE is undefined (no variance): no interval is invented
r0 = stats.paired_two_seed_t([y1, y1], [den, den], [y1, y1], [den, den], B=300)
assert r0["se"] is None and r0["d_rel_ci95"] is None and r0["p_better"] is None
@test
def t_seed_pairs_clause_4b():
def F(cers):
return {"seed_cers_fn": lambda role, ep: cers.get((role, ep))}
ok = {("B1", "P1"): [0.03, 0.035], ("A1", "P1"): [0.12, 0.13], ("B1", "P2"): [0.05, 0.06], ("A1", "P2"): [0.2, 0.21]}
assert vl.seed_pairs(F(ok), "B1", "A1")[0] == vl.MET
bad = {**ok, ("B1", "P2"): [0.05, 0.205]} # B1 seed 2 (0.205) is worse than A1 seed 1 (0.2) on P2: one of four pairs fails
assert vl.seed_pairs(F(bad), "B1", "A1")[0] == vl.NOT_MET
one = {**ok, ("A1", "P1"): [0.12]}
assert vl.seed_pairs(F(one), "B1", "A1")[0] == vl.NOT_EVAL
assert vl.seed_pairs({}, "B1", "A1")[0] == vl.NOT_EVAL
tie = {**ok, ("B1", "P1"): [0.12, 0.03]} # equal CER is not 'better'
assert vl.seed_pairs(F(tie), "B1", "A1")[0] == vl.NOT_MET
CHECKLIST = {"items": [{"id": "C%02d" % i, "required": i <= 12, "check": ("check %d" % i) if i != 16 else "a State of the Art wording, a state-of-the-art hyphen form and a SOTA claim taken from an input file"}
for i in range(1, 17)]}
ATTEST = {"C06": {"holds": True, "note": "greedy, no LM for any arm"}, "C07": {"holds": True, "note": "dedupe.json"},
"C08": {"holds": True, "note": "training data disclosed"}, "C12": {"holds": True, "note": "KOHTD test labels agreed by two volunteers"}}
def add_checkpoint_preds(arm, ck, rate, seed, sets=("kohtd_test",), samples=150000):
"""Predictions of an arm checkpoint on kohtd_test only (the reference arms and the LM / short checkpoints need nothing else)."""
base = os.path.join(W["preds"], arm, ck)
sw.write_preds(os.path.join(base, "kohtd_test.tsv"), W["rows"]["t1"], rate, seed=seed, with_conf=False)
sw.write_meta(os.path.join(base, "meta.json"), peak_mem_reserved_batch1_GiB=1.0, samples_seen=samples)
def verdict_text_has_no_state_of_the_art(v):
import re
txt = json.dumps(v, ensure_ascii=False).lower()
return "state of the art" not in txt and "state-of-the-art" not in txt and re.search(r"\bsota\b", txt) is None
@test
def t_two_seed_reference_arms_and_published_comparison_h10_to_h14():
man = os.path.join(W["root"], "manifests")
rand_rows = sw.make_manifest(os.path.join(man, "kohtd_rand_test.tsv"), "rt", 20, 10, split="test", seed=31)
reg_p = os.path.join(W["root"], "evalsets.json")
reg = json.load(open(reg_p))
reg["sets"].append({"name": "kohtd_rand_test", "manifest": os.path.join(man, "kohtd_rand_test.tsv"), "split": "test", "locked": True})
json.dump(reg, open(reg_p, "w"))
add_arm("A1", "long", 0.12, 0.02, seed=1)
add_arm("A1", "long_seed2", 0.13, 0.02, seed=21)
add_arm("B1", "short", 0.03, 0.02, seed=2)
add_arm("B1", "short_seed2", 0.035, 0.02, seed=22)
# P_short checkpoints of A1 (equal samples), the gated-LM checkpoints of A1 (better than greedy), reference arms (i), (ii), (iii), two more VLM arms for the ranking
add_checkpoint_preds("A1", "short", 0.14, 71)
add_checkpoint_preds("A1", "long_lm_gated", 0.02, 72)
add_checkpoint_preds("A1", "long_seed2_lm_gated", 0.022, 73)
for arm, rate, seed in (("R1", 0.20, 41), ("R2", 0.25, 42)):
add_checkpoint_preds(arm, "final", rate, seed)
add_checkpoint_preds("R1rand", "final", 0.04, 46, sets=()) # rate 0.04: CER about 4%: within the gate of 8.15%
add_checkpoint_preds("R2rand", "final", 0.125, 47, sets=()) # about 11%: above the gate of 5.74%
for arm in ("R1rand", "R2rand"): # these two are scored on the replication test, not on kohtd_test
os.remove(os.path.join(W["preds"], arm, "final", "kohtd_test.tsv"))
sw.write_preds(os.path.join(W["preds"], arm, "final", "kohtd_rand_test.tsv"), rand_rows, 0.04 if arm == "R1rand" else 0.125, seed=46, with_conf=False)
add_checkpoint_preds("R1iii", "final", 0.15, 81)
add_checkpoint_preds("R2iii", "final", 0.10, 82)
add_checkpoint_preds("V2", "short", 0.05, 91)
add_checkpoint_preds("V3", "short", 0.08, 92)
run_score()
roles = {"A1": {"arm": "A1", "checkpoint": "long", "seed2_checkpoint": "long_seed2"},
"B1": {"arm": "B1", "checkpoint": "short", "seed2_checkpoint": "short_seed2", "unique_params_b": 1.0},
"R1": {"arm": "R1", "checkpoint": "final", "unique_params_b": 0.01}, "R2": {"arm": "R2", "checkpoint": "final", "unique_params_b": 0.01},
"R1_rand": {"arm": "R1rand", "checkpoint": "final"}, "R2_rand": {"arm": "R2rand", "checkpoint": "final"},
"R1_iii": {"arm": "R1iii", "checkpoint": "final"}, "R2_iii": {"arm": "R2iii", "checkpoint": "final"}}
json.dump({"roles": roles, "table": [{"arm": "B1", "unique_params_b": 1.0}, {"arm": "V2", "unique_params_b": 0.9}, {"arm": "V3", "unique_params_b": 0.5},
{"arm": "A1", "included": False, "vlm_candidate": False, "reason": "not in the VLM allow-list"}, # has scores at short but is no VLM arm
{"arm": "V_no_scores", "included": False, "reason": "no checkpoint with scores"}]},
open(W["sel_path"], "w"))
ep = json.load(open(W["ep_path"]))
ep["T1_rand"] = {"evalsets": ["kohtd_rand_test"], "P1_group": "all"}
ep["reference_arms"] = {"R1": {"name": "HTR-Flor", "published": {"cer_percent": 6.52, "wer_percent": 24.52, "ser_percent": 26.98, "source": "arXiv 2110.04075v1 p.19 Table 4"}},
"R2": {"name": "SVTR-Tiny", "published": {"cer_percent": 4.59, "wer_percent": 20.00, "source": "Bimurat 2024 p.11 Table 3"}}}
json.dump(ep, open(W["ep_path"], "w"))
chk = os.path.join(W["root"], "checklist.json")
json.dump(CHECKLIST, open(chk, "w"))
att = os.path.join(W["root"], "attest.json")
json.dump(ATTEST, open(att, "w"))
v = run_verdict("verdict_seeds.json", ["--sota-checklist", chk])
hf = v["holm_family"]["B1_vs_A1_P1"]
assert hf["method"] == "two_seed_t" and hf["df"] == 2 and hf["evaluable"] and hf["holm_reject"], hf
assert hf["holm_upper_bound"] < 0
c = {x["id"]: x for x in v["clauses"]}
assert c["4.b"]["result"] == vl.MET, c["4.b"]
assert c["4.a"]["result"] == vl.MET and v["decision"]["ship"] == "B1"
assert v["decision"]["section4"].startswith("met on every clause") and "including 4b with two seeds" in v["decision"]["ship_text"] # no stale 'single seed' wording
assert c["6.2"]["figures"]["grey_zone_condition_met"] is False and v["decision"]["inconclusive_6_3"] is False
# ---- amendment 3.4 E4 and E5: the final checkpoints and their budgets are stated; B1 as a one-seed extra arm ----
fb = v["final_checkpoint_budgets"]
assert set(fb) == {"A1", "B1"} and fb["B1"]["seeds"] == 2 and fb["A1"]["seeds"] == 2 and fb["A1"]["checkpoint"] == "long" and fb["B1"]["checkpoint"] == "short"
assert v["summary"][1].startswith("Final checkpoints and budgets used (amendments 3.4 E4, E5; clarification J1)") and "B1 B1 at short" in v["summary"][1]
sel_all = json.load(open(W["sel_path"]))
one = json.loads(json.dumps(sel_all))
one["roles"]["B1"].pop("seed2_checkpoint")
json.dump(one, open(W["sel_path"], "w"))
try:
v_one = run_verdict("verdict_one_seed_b1.json", ["--sota-checklist", chk])
finally:
json.dump(sel_all, open(W["sel_path"], "w"))
c_one = {x["id"]: x for x in v_one["clauses"]}
assert c_one["4.b"]["result"] == vl.NOT_EVAL and v_one["final_checkpoint_budgets"]["B1"]["seeds"] == 1
assert v_one["decision"]["section4"].startswith("met on every evaluable clause") and "4.b not evaluable" in v_one["decision"]["section4"] # the single-seed wording
assert "not evaluable with one seed" in v_one["decision"]["ship_text"] and "single seed" in v_one["summary"][1]
# ---- H11 and H12: comparison with the two published methods we re-ran on our split ----
s = v["published_method_comparison"]
assert "sota" not in v # the old key name is gone: nothing in the file names a best-published-result claim (H11)
assert s["candidate"]["role"] == "B1" and s["condition_1"]["result"] == vl.MET
assert all(s["reference_comparisons"][r]["difference_points_ci95"][1] < 0 for r in ("R1", "R2"))
rc = s["replication_check"]
assert rc["R1"]["limit_percent"] == 8.15 and rc["R2"]["limit_percent"] == 5.74 # 1.25 x the published CER
assert rc["R1"]["reproduced"] is True and rc["R2"]["reproduced"] is False and rc["R2"]["wording"] == "our re-run did not reproduce the published figure"
assert s["reference_comparisons"]["R1"]["against"] == "the published method re-run on our split"
assert s["reference_comparisons"]["R2"]["against"] == "our re-run (it did not reproduce the published figure)"
assert s["claim_allowed"] is True
assert s["wording"].startswith("B1 (P1 CER") and "is better than our re-runs of the two methods on our split" in s["wording"]
assert "did not reproduce the published figure" in s["wording"] and "not against the published method" in s["wording"]
assert "better than the two published methods we re-ran" not in s["wording"] # that wording needs BOTH reference arms reproduced
st = {i["id"]: i["status"] for i in s["condition_2"]["items"]}
assert st["C01"] == "holds" and st["C02"] == "holds" and st["C05"] == "holds" and st["C10"] == "holds" and st["C06"] == "not evaluable"
assert s["replication_check"]["R1"]["differences_percent_points"]["cer_percent"] is not None
assert verdict_text_has_no_state_of_the_art(v)
assert v["wording_rule_H11"]["strings_rewritten_from_inputs"] >= 1 # the checklist text from the input file was rewritten
assert not any("R1" in x["id"] or "R2" in x["id"] for x in v["clauses"]) # the reference arms enter no clause of sections 3 to 5
assert v["summary"][-1].startswith("Against the two published methods we re-ran on our split")
# ---- H10: the line-branch choice (A1) with the gated character LM against B1, beside the binding greedy verdict ----
d = v["decoding_comparison_H10"]
assert d["binding_verdict_unchanged"] is True and d["line_branch_choice"] == "A1" and d["lm_gated_checkpoint"] == "long_lm_gated"
assert d["greedy"]["result"] == vl.MET and d["lm_gated"]["result"] == vl.NOT_MET # B1 (3%) beats greedy A1 (12%) but not A1 with the LM (2%)
assert d["depends_on_decoding"] is True and d["text"].startswith("the verdict depends on decoding")
assert d["lm_gated"]["figures"]["P1"]["d_rel"] > 0 # B1 is worse than the LM line branch
assert any("verdict depends on decoding" in x for x in v["summary"])
# ---- H13: same-data comparison at equal samples ----
h13 = v["same_data_comparison_H13"]
r1 = h13["reference_arms"]["R1_iii"]
assert r1["equal_samples_to_P_short"] is True and r1["samples_seen"] == 150000
b1 = r1["per_arm"]["B1"]
assert b1["vs_P_short"]["P1"]["ours_is_lower_interval_below_zero"] is True and b1["label_P_short"] == "same data (mix_v1) and equal samples"
assert b1["label_final"].startswith("different budgets") and b1["vs_final_checkpoint"]["P1"] is not None
assert "A1" in r1["per_arm"] and r1["best_P_short_arm_on_P1"] == "B1" and r1["best_arm_beats_it_on_P1"] is True
# ---- H14: descriptive ranking of the VLM arms on the test P_short scores ----
rk = v["vlm_ranking_P_short_descriptive_H14"]
ranked = [r["arm"] for r in rk["rows"] if r.get("rank_by_P1")]
assert ranked == ["B1", "V2", "V3"] and rk["rows"][0]["P1"]["lo"] <= rk["rows"][0]["P1"]["cer"] <= rk["rows"][0]["P1"]["hi"] and "descriptive" in rk["label"]
assert "A1" not in [r["arm"] for r in rk["rows"]] # a non-candidate row of the table is never ranked as a VLM
assert [r for r in rk["rows"] if r["arm"] == "V_no_scores"][0]["scored"] is False # a candidate without scores is listed, unranked
# ---- both reference arms reproduced: the full wording of H11 ----
sw.write_preds(os.path.join(W["preds"], "R2rand", "final", "kohtd_rand_test.tsv"), rand_rows, 0.02, seed=46, with_conf=False)
run_score()
v2 = run_verdict("verdict_both_reproduced.json", ["--sota-checklist", chk])
s2 = v2["published_method_comparison"]
assert s2["replication_check"]["R2"]["reproduced"] is True and s2["claim_allowed"] is True
assert s2["wording"].startswith("B1 (P1 CER") and "is better than the two published methods we re-ran on our split:" in s2["wording"] and "our re-run (it did not" not in s2["wording"]
assert verdict_text_has_no_state_of_the_art(v2)
# the checklist items that need attestations are listed but no longer gate the wording (H11); with attestations and the gate file they hold
out = os.path.join(W["root"], "verdict_attested.json")
p = subprocess.run([sys.executable, "-I", VERDICT, "--scores", W["out"], "--selection", W["sel_path"], "--endpoints", W["ep_path"], "--out", out,
"--gate-file", W["gate"], "--sota-checklist", chk, "--sota-attestations", att], capture_output=True, text=True)
assert p.returncode == 0, p.stderr[-1500:]
v3 = json.load(open(out, encoding="utf-8"))
st2 = {i["id"]: i["status"] for i in v3["published_method_comparison"]["condition_2"]["items"]}
assert st2["C09"] == "holds" and st2["C06"] == "holds", st2
assert v3["published_method_comparison"]["condition_2"]["result"] == vl.MET
@test
def t_j1_section3_at_p_long_section4_and_h10_at_the_furthest_checkpoint():
"""Clarification J1: section 3 reads the line arms at 'long' (two seeds); the line-branch choice enters section 4 and the H10 block at long2x (seed 1 only: G1)."""
chk = os.path.join(W["root"], "checklist.json")
add_arm("A1", "long2x", 0.045, 0.02, seed=61) # far better than A1 at 'long' (0.12): the two checkpoints can not be confused
add_checkpoint_preds("A1", "long2x_lm_gated", 0.025, 62)
sw.write_meta(os.path.join(W["preds"], "A1", "long2x", "meta.json"), peak_mem_reserved_batch1_GiB=9.5, samples_seen=3168768)
sw.write_meta(os.path.join(W["preds"], "A1", "long", "meta.json"), peak_mem_reserved_batch1_GiB=9.5, samples_seen=1584384)
run_score()
sel_all = json.load(open(W["sel_path"]))
base = run_verdict("verdict_j1_base.json", ["--sota-checklist", chk]) # selection without section-4 fields: both sections read 'long'
j = json.loads(json.dumps(sel_all))
j["roles"]["A1"].update({"section3_checkpoint": "long", "section4_checkpoint": "long2x", "section4_budget": {"samples_seen": 3168768, "label": "2 x P_long (3,168,768 samples)"}})
json.dump(j, open(W["sel_path"], "w"))
try:
v = run_verdict("verdict_j1.json", ["--sota-checklist", chk])
j["roles"]["A1"]["section4_checkpoint"] = "long3x" # a section-4 checkpoint without test scores: J1 could not be applied, and it says so
json.dump(j, open(W["sel_path"], "w"))
v_missing = run_verdict("verdict_j1_missing.json", ["--sota-checklist", chk])
finally:
json.dump(sel_all, open(W["sel_path"], "w"))
hb, h4 = base["holm_family"]["B1_vs_A1_P1"], v["holm_family"]["B1_vs_A1_P1"]
assert hb["reference_role"] == "A1" and h4["reference_role"] == "A1@s4"
assert v["holm_family"]["A2_vs_A1_P1"]["reference_role"] == "A1" # the section-3 tests keep reading A1 at P_long
assert h4["cer_a1"] < 0.7 * hb["cer_a1"] # section 4 compares B1 with A1 at long2x, not with A1 at long
assert v["decision"]["section4_reference_roles"]["A1"] == "A1@s4" and base["decision"]["section4_reference_roles"]["A1"] == "A1"
assert v["decision"]["line_branch_choice"] == "A1"
c = {x["id"]: x for x in v["clauses"]}
assert c["4.b"]["result"] == vl.NOT_EVAL and "single seed" in v["decision"]["section4"] # A1 has one seed at long2x: clause 4b waived as written (G1, G2)
assert v["descriptive"]["A1"]["checkpoint"] == "long" and v["descriptive"]["A1@s4"]["checkpoint"] == "long2x"
h10 = v["decoding_comparison_H10"]
assert h10["line_branch_choice_checkpoint"] == "long2x" and h10["lm_gated_checkpoint"] == "long2x_lm_gated" # the H10 block reads the furthest checkpoint
assert base["decoding_comparison_H10"]["lm_gated_checkpoint"] == "long_lm_gated"
j1 = v["line_branch_section4_J1"]
assert j1["section4_uses_a_further_checkpoint"] is True and j1["choice"] == "A1"
assert j1["section3_checkpoint_P_long"]["checkpoint"] == "long" and j1["section3_checkpoint_P_long"]["seeds"] == 2
assert j1["section4_checkpoint_furthest"]["checkpoint"] == "long2x" and j1["section4_checkpoint_furthest"]["seeds"] == 1
assert j1["section4_checkpoint_furthest"]["P1_cer"]["value"] < 0.7 * j1["section3_checkpoint_P_long"]["P1_cer"]["value"] # the P_long figure is shown beside it
fb = v["final_checkpoint_budgets"]["A1"]
assert fb["checkpoint"] == "long" and fb["seeds"] == 2 and fb["section4_checkpoint"] == "long2x" and fb["section4_seeds"] == 1 and fb["section4_budget"].startswith("2 x P_long")
assert "section 4 and the H10 block at long2x" in v["summary"][1]
assert base["line_branch_section4_J1"]["section4_uses_a_further_checkpoint"] is False
mj = v_missing["decision"]["section4_reference_roles"]
assert mj["A1"] == "A1" and any("long3x" in n and "could not be applied" in n for n in v_missing["notes"]) # nothing is substituted silently
@test
def t_g2_reference_roles_written_by_select_make_the_comparison_blocks_evaluable():
"""AUDIT check 8, gap G2: selection.json must carry R1, R2, R1_rand, R2_rand, R1_iii, R2_iii (REF's folders ours, rand, mix) or the D5, H11 to H13 blocks are not evaluable."""
man = os.path.join(W["root"], "manifests")
rand_rows = sw.make_manifest(os.path.join(man, "kohtd_rand_test.tsv"), "rt", 20, 10, split="test", seed=31)
for arm, ck, rate, seed in (("R1", "ours", 0.20, 141), ("R2", "ours", 0.25, 142), ("R1", "mix", 0.15, 143), ("R2", "mix", 0.10, 144)):
add_checkpoint_preds(arm, ck, rate, seed)
for arm, rate in (("R1", 0.04), ("R2", 0.125)): # variant (ii): scored on the replication test only
add_checkpoint_preds(arm, "rand", rate, 145, sets=())
os.remove(os.path.join(W["preds"], arm, "rand", "kohtd_test.tsv"))
sw.write_preds(os.path.join(W["preds"], arm, "rand", "kohtd_rand_test.tsv"), rand_rows, rate, seed=146, with_conf=False)
add_checkpoint_preds("R1", "ours_paperdec", 0.01, 147) # HTR-Flor's own beam decoder: descriptive, never a role
for arm, ck in (("R1", "ours"), ("R1", "rand"), ("R1", "mix")):
sw.write_meta(os.path.join(W["preds"], arm, ck, "meta.json"), samples_seen=150016, parameters=843582)
for arm, ck in (("R2", "ours"), ("R2", "rand"), ("R2", "mix")):
sw.write_meta(os.path.join(W["preds"], arm, ck, "meta.json"), samples_seen=150016, parameters=13878426, parameters_ctc_branch_used_at_test_time=2232812)
run_score()
refs, warns = selection.reference_roles(W["out"], W["preds"])
assert warns == [] and set(refs) == {"R1", "R2", "R1_rand", "R2_rand", "R1_iii", "R2_iii"}
assert [(refs[r]["arm"], refs[r]["checkpoint"], refs[r]["reference_variant"]) for r in ("R1", "R2", "R1_rand", "R2_rand", "R1_iii", "R2_iii")] == [
("R1", "ours", "i"), ("R2", "ours", "i"), ("R1", "rand", "ii"), ("R2", "rand", "ii"), ("R1", "mix", "iii"), ("R2", "mix", "iii")]
assert refs["R1"]["unique_params_b"] == 843582 / 1e9 and refs["R2"]["unique_params_b"] == 2232812 / 1e9 and refs["R1_iii"]["samples_seen"] == 150016 # R2: the test-time branch
assert not any(v_["checkpoint"].endswith("paperdec") for v_ in refs.values())
sel_all = json.load(open(W["sel_path"]))
base = {k: v_ for k, v_ in sel_all["roles"].items() if k in ("A1", "B1")}
ep = json.load(open(W["ep_path"]))
ep["T1_rand"] = {"evalsets": ["kohtd_rand_test"], "P1_group": "all"}
json.dump(ep, open(W["ep_path"], "w"))
chk = os.path.join(W["root"], "checklist.json")
try:
json.dump({"roles": base, "table": []}, open(W["sel_path"], "w")) # what select_b1b2.py wrote before the fix: no reference roles
v0 = run_verdict("verdict_g2_without.json", ["--sota-checklist", chk])
json.dump({"roles": dict(base, **refs), "table": []}, open(W["sel_path"], "w")) # what it writes now
v1 = run_verdict("verdict_g2_with.json", ["--sota-checklist", chk])
finally:
json.dump(sel_all, open(W["sel_path"], "w"))
rc0, rc1 = v0["published_method_comparison"]["replication_check"], v1["published_method_comparison"]["replication_check"]
assert rc0["R1"]["reproduced"] is None and rc0["R1"]["re_run_cer_percent"] is None and rc0["R2"]["reproduced"] is None # without the roles: not evaluable
assert rc1["R1"]["reproduced"] is True and rc1["R2"]["reproduced"] is False and rc1["R1"]["re_run_cer_percent"] is not None # with them: the H12 gate is evaluated
assert v1["published_method_comparison"]["reference_comparisons"]["R1"]["against"] == "the published method re-run on our split"
h13 = v1["same_data_comparison_H13"]["reference_arms"]
assert set(h13) == {"R1_iii", "R2_iii"} and h13["R1_iii"]["samples_seen"] == 150016 and "reference_arms" not in v0["same_data_comparison_H13"]
@test
def t_limit_and_wording_for_one_reference_arm_not_beaten():
from r5eval import verdictgather as vg
assert vg.Gather._limit({"cer_percent": 6.52}) == 8.15 and vg.Gather._limit({"cer_percent": 4.59}) == 5.74 and vg.Gather._limit(None) is None
# B1 reads kohtd_test exactly as R1 does (same rows damaged, same rate and seed): it does not beat R1 although it beats R2
add_arm("B1", "short", 0.19, 0.02, seed=60)
add_arm("B1", "short_seed2", 0.19, 0.02, seed=61)
for arm, ck in (("B1", "short"), ("B1", "short_seed2"), ("A1", "long"), ("A1", "long_seed2")): # A1 is then the arm that ships (B1 does not beat it)
sw.write_preds(os.path.join(W["preds"], arm, ck, "kohtd_test.tsv"), W["rows"]["t1"], 0.20, seed=41, with_conf=False)
run_score()
v = run_verdict("verdict_sota2.json", ["--sota-checklist", os.path.join(W["root"], "checklist.json")])
s = v["published_method_comparison"]
assert s["claim_allowed"] is False and s["condition_1"]["result"] == vl.NOT_MET # beating R2 alone is not enough: BOTH are required
assert s["condition_1"]["per_reference"]["R2"] == vl.MET and s["condition_1"]["per_reference"]["R1"] == vl.NOT_MET
assert s["wording"].startswith("A1 is not shown to be better than the two published methods we re-ran on our split")
assert any("HTR-Flor" in f for f in s["failed_conditions"])
assert verdict_text_has_no_state_of_the_art(v)
d = v["decoding_comparison_H10"]
assert d["depends_on_decoding"] is not True # with B1 equal to A1 neither decoding gives B1 the margin: no dependence
@test
def t_prediction_files_named_by_registry_name_with_parentheses_are_found():
"""VLMA's eval_vlm.py names a file by the registry name, for example 'kohtd_test (P1).tsv'. verdict.py must find its score file by what it
scored, not by the file name."""
for ck in ("long", "long_seed2"):
base = os.path.join(W["preds"], "A1", ck)
os.rename(os.path.join(base, "kohtd_test.tsv"), os.path.join(base, "kohtd_test (P1).tsv"))
os.remove(os.path.join(W["out"], "A1", ck, "kohtd_test.json"))
run_score()
assert os.path.exists(os.path.join(W["out"], "A1", "long", "kohtd_test (P1).json"))
v = run_verdict("verdict_parens.json", ["--sota-checklist", os.path.join(W["root"], "checklist.json")])
h = v["holm_family"]["B1_vs_A1_P1"]
# in this state B1 and A1 read kohtd_test exactly like R1 (identical outputs), so d is 0 and no variance exists; the point is that A1 was FOUND
assert h["method"] == "two_seed_t" and h["cer_a1"] is not None and h["d_rel"] == 0.0
assert "A1" in v["descriptive"] and v["descriptive"]["A1"]["complete_T1"] is True and v["descriptive"]["A1"]["seeds_scored_on_T1"] == [1, 2]
assert v["published_method_comparison"]["condition_1"]["result"] in (vl.MET, vl.NOT_MET) # the comparison ran: A1 was found
@test
def t_select_b1b2_excludes_reference_arms_and_uses_the_allow_list():
root = os.path.join(W["root"], "sel2")
os.makedirs(root)
man = os.path.join(root, "manifests")
v1 = sw.make_manifest(os.path.join(man, "kohtd_screen_v1.tsv"), "v1", 20, 10, seed=21)
sw.write_registry(os.path.join(root, "reg.json"), [{"name": "V1 (screen)", "manifest": os.path.join(man, "kohtd_screen_v1.tsv"), "split": "val", "locked": False}])
for arm, rate, ips in (("vlm_a", 0.10, 30.0), ("R1", 0.01, 500.0), ("R2rand", 0.01, 500.0), ("unlisted", 0.02, 50.0), ("vlm_b", 0.30, 90.0)):
sw.write_preds(os.path.join(root, "preds", arm, "short", "V1 (screen).tsv"), v1, rate, seed=7 + len(arm))
sw.write_meta(os.path.join(root, "preds", arm, "short", "meta.json"), images_per_second_batch16_V1=ips)
r = subprocess.run([sys.executable, "-I", SCORE, "--registry", os.path.join(root, "reg.json"), "--preds", os.path.join(root, "preds"), "--out",
os.path.join(root, "scores"), "--B", "100", "--settle", "0", "--ktrain", os.path.join(root, "no_ktrain.json")], capture_output=True, text=True)
assert r.returncode == 0, r.stderr[-1500:]
from r5eval import selection
info = {"vlm_a": {"unique_params_b": 1.0}, "vlm_b": {"unique_params_b": 0.3}, "unlisted": {"unique_params_b": 0.2}}
s = selection.select(os.path.join(root, "scores"), info, vlm_allow={"vlm_a", "vlm_b"}, strict_final=False)
arms = {t["arm"] for t in s["table"] if t["included"]}
assert arms == {"vlm_a", "vlm_b"} and s["B1"] == "vlm_a" and s["B2"] == "vlm_b" # R1 (lowest CER), R2rand and the unlisted arm never compete
assert "R1" not in {t["arm"] for t in s["table"]} and "R2rand" not in {t["arm"] for t in s["table"]}
s = selection.select(os.path.join(root, "scores"), info, strict_final=False) # no allow-list: reference arms are still excluded by name
assert "R1" not in {t["arm"] for t in s["table"]} and "R2rand" not in {t["arm"] for t in s["table"]} and s["B1"] == "unlisted"
s = selection.select(os.path.join(root, "scores"), {"unlisted": {"role": "reference"}}, strict_final=False)
assert "unlisted" not in {t["arm"] for t in s["table"]}
# an arm that is neither a line arm, a reference arm nor in the allow-list is LISTED as excluded (never silently dropped)
s = selection.select(os.path.join(root, "scores"), info, vlm_allow={"vlm_a", "vlm_b"}, strict_final=False)
rows = {t["arm"]: t for t in s["table"]}
assert "unlisted" in rows and rows["unlisted"]["included"] is False and "allow-list" in rows["unlisted"]["reason"]
# the CLI fills the parameter counts from the models table, so that B2 (another size class than B1) can be chosen without arms_info
with open(os.path.join(root, "models.tsv"), "w") as f:
f.write("short\tsize_class\tparams_unique_design\nvlm_a\tmiddle\t1000000000\nvlm_b\tsmall\t300000000\n")
sel_py = os.path.join(HERE, "..", "scripts", "r5eval", "select_b1b2.py")
r = subprocess.run([sys.executable, "-I", sel_py, "--scores", os.path.join(root, "scores"), "--out", os.path.join(root, "sel_cli.json"), "--models-tsv",
os.path.join(root, "models.tsv"), "--vlm-arms", "unlisted", "--allow-short-b1"], capture_output=True, text=True)
assert r.returncode == 0, r.stderr[-1500:]
sj = json.load(open(os.path.join(root, "sel_cli.json")))
assert sj["B1"] == "unlisted" or sj["B1"] == "vlm_a"
ps = {t["arm"]: t["unique_params_b"] for t in sj["table"]}
assert ps["vlm_a"] == 1.0 and ps["vlm_b"] == 0.3 and sj["roles"]["B1"]["short_checkpoint"] == "short"
@test
def t_meta_readers_for_vlma_and_linedet_files():
from r5eval import metautil
vlma = {"peak_mem_reserved_batch1_GiB": 9.5, "peak_mem_batch1_GiB": 8.0, "images_per_second_batch16_V1": 55.0, "learning_rate": 2e-5,
"conf_definition": "conf = mean natural-log probability of the generated tokens ..."}
m = metautil.memory(vlma)
assert m["reserved_gib"] == 9.5 and m["allocated_gib"] == 8.0 and m["basis"] == "batch 1"
assert metautil.speed(vlma)["images_per_second"] == 55.0 and metautil.conf_kind(vlma)[0] == "logprob"
line = {"peak_gpu_memory_gib_eval_batch_reserved": 3.2, "peak_gpu_memory_gib_eval_batch_allocated": 2.9, "learning_rate_peak": 1e-3,
"peak_gpu_memory_batch1_gib": "see OUT/timing.json (measured separately at batch 1)",
"images_per_second": "per set in summary.lines_per_second_eval", "summary": {"V1": {"lines_per_second_eval": 812.0}},
"confidence": "conf = mean over emitted characters of the frame maximum probability; conf_min = minimum of the same; hit_cap = 0 (CTC has no length cap)"}
m = metautil.memory(line)
assert m["reserved_gib"] == 3.2 and "evaluation batch" in m["basis"]
assert metautil.speed(line)["images_per_second"] == 812.0 and "not the same as the VLM" in metautil.speed(line)["basis"]
assert metautil.learning_rate(line) == 1e-3
assert metautil.conf_kind(line)[0] == "probability" # 'frame maximum probability' is a probability, not a log-probability
assert metautil.memory({})["reserved_gib"] is None
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)