"""CPU-only tests of the logic where a silent bug would corrupt results: token alignment, rewards, scoring, benchmark sampling, score parsing, significance tests, data selection and prompt choice. python -m pytest tests -q """ import argparse import json import random import pytest from common import experiment, mdpbench, photo_aug, rewards, score, select_data from common.data_prep import LINE_PROMPT, PAGE_PROMPT, choose_prompt from common.selfplay import lcs_unmatched # ---------------------------------------------------------------- self-play alignment def test_lcs_identical_sequences_have_no_unmatched(): assert lcs_unmatched([1, 2, 3], [1, 2, 3]) == ([], []) def test_lcs_substitution_marks_both_sides(): assert lcs_unmatched([1, 2, 3, 4, 5], [1, 2, 9, 4, 5]) == ([2], [2]) def test_lcs_deletion_and_insertion(): assert lcs_unmatched([1, 2, 3], [1, 3]) == ([1], []) assert lcs_unmatched([1, 3], [1, 2, 3]) == ([], [1]) def test_lcs_empty_sides(): assert lcs_unmatched([], [5, 6]) == ([], [0, 1]) assert lcs_unmatched([5], []) == ([0], []) def test_lcs_matched_plus_unmatched_covers_everything(): rng = random.Random(0) for _ in range(50): a = [rng.randrange(6) for _ in range(rng.randrange(0, 30))] b = [rng.randrange(6) for _ in range(rng.randrange(0, 30))] ua, ub = lcs_unmatched(a, b) kept_a = [x for i, x in enumerate(a) if i not in set(ua)] kept_b = [x for i, x in enumerate(b) if i not in set(ub)] assert kept_a == kept_b # what remains is one common subsequence # ---------------------------------------------------------------- rewards def test_reward_perfect_output_is_one(): text = "
ab
$x^2$" assert rewards.reward(text, text)[0] == pytest.approx(1.0) assert rewards.reward(text, text, mode="product")[0] == pytest.approx(1.0) def test_unclosed_tag_and_odd_dollars_fail_closure(): assert rewards.r_closure("bold") == 0.0 assert rewards.r_closure("a $x$ and $y") == 0.0 assert rewards.r_closure("

ok


$x$") == 1.0 def test_ragged_table_fails_table_check(): ragged = "
ab
c
" spanned = '
a
cd
' assert rewards.r_table(ragged) == 0.0 assert rewards.r_table(spanned) == 1.0 assert rewards.r_table("no tables here") == 1.0 def test_product_reward_floors_format_failures_but_zeroes_loops(): total, parts = rewards.reward("hello world", "hello world", mode="product") assert parts["closure"] == 0.0 and total == pytest.approx(0.2) loop = "the same sentence again and again. " * 20 assert rewards.reward(loop, loop, mode="product")[0] == 0.0 def test_better_text_gets_higher_reward(): gt = "The quick brown fox jumps over the lazy dog" assert rewards.reward(gt, gt)[0] > rewards.reward("The quick brown fax jumps", gt)[0] > rewards.reward("", gt)[0] # ---------------------------------------------------------------- CER def test_cer_normalisation(): assert score.cer(score.norm("**Hello** world"), score.norm("Hello world")) == 0.0 assert score.norm("١٢٣") == "123" # any script's decimal digits -> 0-9 assert score.norm("Café") != score.norm("Cafe") # strict keeps marks assert score.norm("Café", fold=True) == score.norm("cafe", fold=True) def test_loop_detection(): assert score.has_loop("abcdefghij klmnopqrst uvwxyz 0123 " * 10) assert not score.has_loop("A normal paragraph with no repeated chunk of any meaningful length at all.") # ---------------------------------------------------------------- MDPBench helpers def test_page_id_helpers(): assert mdpbench.lang_of("zh-CHT_magazine_40_outdoor_light") == "zh-cht" assert mdpbench.doc_of("ar_book_9_indoor_light_oblique_wrinkle") == "ar_book_9" assert mdpbench.doc_of("ar_book_9") == "ar_book_9" assert mdpbench.is_digital_id("ar_book_9") and not mdpbench.is_digital_id("ar_book_9_indoor") def test_parse_per_lang(): assert mdpbench.parse_per_lang("ar=all,en=40,default=8") == ({"ar": None, "en": 40}, 8) assert mdpbench.parse_per_lang("default=all") == ({}, None) def test_parse_official_score_output(): out = "\n[Latin]\n DE: 80.1\n EN: 90.5\n Avg: 85.3\n\n[Non-Latin]\n AR: 70.0\n ZH-T: N/A\n Avg: 70.0\n\n" \ "[Overall]\n All : 81.0\n Digit.: 90.0\n Photo.: 78.0\n" s = mdpbench.parse_scores(out) assert s["AR"] == 70.0 and s["EN"] == 90.5 and s["ZH-T"] is None assert s["Latin_Avg"] == 85.3 and s["Non-Latin_Avg"] == 70.0 assert s["Overall_All"] == 81.0 and s["Overall_Digit"] == 90.0 and s["Overall_Photo"] == 78.0 def _fake_bench(tmp_path, monkeypatch, langs=("ar", "en"), docs=6): pages = [] for lang in langs: for d in range(docs): for suffix in ("", "_indoor_a", "_indoor_b", "_outdoor_c"): pages.append({"page_info": {"image_path": f"{lang}_book_{d}{suffix}.jpg"}, "layout_dets": []}) monkeypatch.setattr(mdpbench, "BENCH_DIR", tmp_path) monkeypatch.setattr(mdpbench, "download_images", lambda names: tmp_path / "img") (tmp_path / "MDPBench_public.json").write_text(json.dumps(pages), encoding="utf-8") def _subset(name, per_lang, exclude=None): mdpbench.cmd_subset(argparse.Namespace(name=name, per_lang=per_lang, seed=0, exclude=exclude)) gt = json.loads((mdpbench.BENCH_DIR / "subsets" / name / "gt.json").read_text(encoding="utf-8")) return [p["page_info"]["image_path"][:-4] for p in gt] def test_subsets_draw_whole_documents_and_dev_test_are_disjoint(tmp_path, monkeypatch): _fake_bench(tmp_path, monkeypatch) dev = _subset("dev", "ar=8,default=4") assert len(dev) == 12 # 2 Arabic documents + 1 English, 4 pages each by_doc = {} for p in dev: by_doc.setdefault(mdpbench.doc_of(p), []).append(p) assert all(len(v) == 4 and sum(mdpbench.is_digital_id(x) for x in v) == 1 for v in by_doc.values()) test = _subset("test", "default=all", exclude=["dev"]) assert not {mdpbench.doc_of(p) for p in dev} & {mdpbench.doc_of(p) for p in test} assert len(dev) + len(test) == 48 # together they cover the benchmark assert _subset("dev2", "ar=8,default=4") == dev # same seed -> same pages # ---------------------------------------------------------------- significance def test_paired_bootstrap_detects_a_real_gain_and_not_noise(): rng = random.Random(1) base = {f"ar_book_{d}{s}": rng.uniform(0.5, 0.8) for d in range(30) for s in ("", "_a", "_b", "_c")} better = {k: v + 0.05 for k, v in base.items()} noise = {k: v + rng.uniform(-0.05, 0.05) for k, v in base.items()} mean, lo, hi, n = experiment.paired_bootstrap(base, better, lambda p: True) assert n == 120 and mean == pytest.approx(5.0) and lo > 0 mean, lo, hi, _ = experiment.paired_bootstrap(base, noise, lambda p: True) assert lo < 0 < hi assert experiment.paired_bootstrap(base, better, lambda p: False) is None def test_paired_bootstrap_ignores_pages_missing_on_either_side(): base = {"ar_book_1": 0.5, "ar_book_2": None, "ar_book_3": 0.5} new = {"ar_book_1": 0.6, "ar_book_2": 0.9} assert experiment.paired_bootstrap(base, new, lambda p: True)[3] == 1 def test_run_tag_names(): assert experiment.tag_of({"name": "sft"}, 1.0) == "sft" assert experiment.tag_of({"name": "sft"}, 0.7) == "sft@0.7" assert experiment.page_lang("ZH-T") == "zh-cht" and experiment.page_lang("AR") == "ar" # ---------------------------------------------------------------- data selection and prompts def test_sieve_drops_broken_labels(): rows = [{"id": "a", "text": "fine"}, {"id": "b", "text": ""}, {"id": "c", "text": "open"}, {"id": "d", "text": "
12
3
"}] assert [r["id"] for r in select_data.sieve(rows)] == ["a"] def test_balance_caps_each_source(): rows = [{"id": i, "source": "big", "level": "page"} for i in range(50)] + \ [{"id": 100 + i, "source": "small", "level": "page"} for i in range(3)] out = select_data.balance(rows, per_source=10, seed=0) assert sum(r["source"] == "big" for r in out) == 10 and sum(r["source"] == "small" for r in out) == 3 def test_model_prompt_replaces_only_the_page_prompt(): assert choose_prompt({"level": "page"}, "DOC") == "DOC" assert choose_prompt({"level": "line"}, "DOC") == LINE_PROMPT assert choose_prompt({"level": "page"}) == PAGE_PROMPT assert choose_prompt({"level": "line"}, line_prompt="L") == "L" def test_perspective_coefficients_map_corners(): src = [(0, 0), (100, 0), (100, 200), (0, 200)] dst = [(10, 12), (115, 8), (108, 215), (5, 205)] c = photo_aug._perspective_coeffs(src, dst) for (u, v), (x, y) in zip(src, dst): # PIL maps output (x, y) back to input (u, v) d = c[6] * x + c[7] * y + 1 assert (c[0] * x + c[1] * y + c[2]) / d == pytest.approx(u, abs=1e-6) assert (c[3] * x + c[4] * y + c[5]) / d == pytest.approx(v, abs=1e-6) # ---------------------------------------------------------------- element credit (common/credit.py) from common import credit # noqa: E402 def test_line_spans_cover_text_and_keep_newlines(): assert credit.line_spans("ab\ncd") == [(0, 3), (3, 5)] assert credit.line_spans("ab\n") == [(0, 3)] assert credit.line_spans("") == [(0, 0)] def test_element_scores_blame_only_the_wrong_line(): _, s = credit.element_scores("hello\nwXrld\nagain", "hello\nworld\nagain") assert s[0] == 1.0 and s[2] == 1.0 and 0 < s[1] < 1 def test_token_scores_follow_line_of_each_token(): vocab = {1: "ab", 2: "\n", 3: "cX", 4: ""} # 4 = end token, adds no text decode = lambda ids: "".join(vocab[i] for i in ids) # noqa: E731 ts = credit.token_scores(decode, [1, 2, 3, 4], "ab\ncd") assert ts[0] == ts[1] == 1.0 and ts[2] == ts[3] == 0.5 def test_group_token_advantages_flat_group_is_zero(): assert credit.group_token_advantages([[0.5, 0.5], [0.5]]) == [[0.0, 0.0], [0.0]] adv = credit.group_token_advantages([[1.0, 1.0], [0.0, 0.0]]) assert adv[0][0] > 0 > adv[1][0] and abs(sum(adv[0] + adv[1])) < 1e-6 # ---------------------------------------------------------------- distillation math (common/vlm_utils.py) torch = pytest.importorskip("torch") def test_topk_tail_is_a_distribution_and_jsd_bounds(): from common.vlm_utils import jsd, topk_tail g = torch.Generator().manual_seed(0) p = torch.log_softmax(torch.randn(5, 50, generator=g), -1) q = torch.log_softmax(torch.randn(5, 50, generator=g), -1) idx = p.topk(8, -1).indices pt, qt = topk_tail(p, idx), topk_tail(q, idx) assert torch.allclose(pt.exp().sum(-1), torch.ones(5), atol=1e-5) assert torch.allclose(jsd(pt, pt), torch.zeros(5), atol=1e-6) d = jsd(pt, qt) assert (d > 0).all() and (d <= torch.log(torch.tensor(2.0)) + 1e-6).all() def test_blink_target_cancels_shared_language_prior(): from common.self_distill import distill_loss head = torch.nn.Linear(4, 6, bias=False) torch.manual_seed(0) h = torch.randn(3, 4) # teacher with eyes open == eyes closed: the image adds nothing, so target = teacher, any beta a = distill_loss(head, h.clone().requires_grad_(), h, h, beta=3.4, k=6, alpha=0.5) assert float(a) == pytest.approx(0.0, abs=1e-6) b = distill_loss(head, h.clone().requires_grad_(), h, h + 1.0, beta=3.4, k=6, alpha=0.5) b.backward() assert float(b) > 0 def test_nora_init_gives_unit_columns(): peft = pytest.importorskip("peft") from common.vlm_utils import nora_init net = torch.nn.Sequential(torch.nn.Linear(8, 8)) model = peft.get_peft_model(net, peft.LoraConfig(r=4, lora_alpha=4, target_modules=["0"])) assert nora_init(model) == 1 w = model.base_model.model[0].lora_A["default"].weight assert torch.allclose(w.norm(dim=0), torch.ones(8), atol=1e-5) def test_grpd_gate_signs(): A = torch.tensor([1.0, 1.0, -1.0, -1.0]) t = torch.tensor([-1.0, -3.0, -1.0, -3.0]) # teacher log-probs s = torch.tensor([-2.0, -2.0, -2.0, -2.0]) # student log-probs from common.grpo import grpd_reward R = grpd_reward(A, t, s) assert R.tolist() == [1.0, 0.0, 0.0, -1.0] # good reading: reinforce where teacher surer; bad: push down # ---------------------------------------------------------------- synthetic page conversion (common/synth_convert.py) from common import synth_convert as sc # noqa: E402 def _cell(r, c, x, text, rs=1, cs=1, header=False): return {"row": r, "col": c, "rowspan": rs, "colspan": cs, "header": header, "text": text, "bbox": [x, 0, 10, 10]} def test_table_cells_come_out_left_to_right_for_rtl_tables(): # right-to-left table: logical column 0 is the rightmost one (largest x) el = {"type": "table", "cells": [_cell(0, 0, 300, "A", header=True), _cell(0, 1, 100, "B", header=True), _cell(1, 0, 300, "1"), _cell(1, 1, 100, "2", rs=2)]} assert sc._cells_html(el) == ('' '
BA
21
') def test_page_ids_are_unique_across_shards(): ann = {"page_information": {"id": "000002"}} a = sc.page_id("academic_papers", "x/train-00001-of-00008.parquet", ann, 0) b = sc.page_id("academic_papers", "x/train-00002-of-00008.parquet", ann, 0) assert a != b and a.endswith("_00001_000002") def test_page_markdown_styles_and_skips_watermarks(): ann = {"page_information": {"image_width": 1000, "image_height": 1000}, "element_bboxes": [{"type": "heading", "level": 2, "text": "Title\n"}, {"type": "watermark", "text": "X"}, {"type": "paragraph", "text": "Body."}, {"type": "list", "ordered": True, "text": "1) a\n2) b"}, {"type": "formula", "latex": "a+b"}, {"type": "figure", "bbox": [100, 200, 300, 100]}]} assert sc.page_markdown(ann) == ('## Title\n\nBody.\n\n1. a\n2. b\n\n$$\na+b\n$$\n\n' '') def test_page_gt_matches_benchmark_schema(): ann = {"page_information": {}, "element_bboxes": [ {"type": "header", "lang": ["ar"], "text": "h", "bbox": [0, 0, 1, 1]}, {"type": "paragraph", "lang": ["ar"], "text": "p", "bbox": [0, 0, 1, 1]}, {"type": "caption", "lang": ["ar"], "text": "c", "bbox": [0, 0, 1, 1], "target": 3}, {"type": "table", "lang": ["ar"], "cells": [_cell(0, 0, 0, "t")], "bbox": [0, 0, 1, 1]}]} g = sc.page_gt(ann, "ar_x.png") assert g["extra"] == {"relation": []} and g["page_info"]["image_path"] == "ar_x.png" cats = [(d["category_type"], d["order"]) for d in g["layout_dets"]] assert cats == [("header", None), ("text_block", 0), ("table_caption", 1), ("table", 2)] # ---------------------------------------------------------------- focused SFT (common/vlm_sft.py) def test_focused_loss_trains_only_wrong_tokens_and_anchors_the_rest(): from common.vlm_sft import focused_loss V = 5 logits = torch.full((1, 4, V), -5.0) logits[0, 0, 1] = 5.0 # predicts token 1 at step 0 (target 1: right) logits[0, 1, 3] = 5.0 # predicts token 3 at step 1 (target 2: wrong) labels = torch.tensor([[-100, 1, 2, -100]]) model = logits.clone().requires_grad_() loss, share = focused_loss(model, logits, labels, threshold=0.5, kl_weight=1.0) assert share == 0.5 # one of the two target tokens is wrong expected = -torch.log_softmax(logits[0, 1], -1)[2] # CE on the wrong token; KL is 0 when model == reference assert torch.allclose(loss, expected, atol=1e-5) loss.backward() assert torch.allclose(model.grad[0, 0], torch.zeros(V), atol=1e-6) # the right token gets no push at the start assert model.grad[0, 1, 2] < 0 # the wrong token is pulled up def test_focused_loss_kl_pulls_back_a_drifted_model(): from common.vlm_sft import focused_loss ref = torch.zeros(1, 3, 4) ref[0, 0, 1] = 6.0 drift = ref.clone() drift[0, 0, 2] = 6.0 # drifted: puts mass on token 2 too labels = torch.tensor([[-100, 1, -100]]) loss, share = focused_loss(drift.requires_grad_(), ref, labels, 0.5, 1.0) assert share == 0.0 and loss > 0.1 def test_token_loss_reports_learning_and_forgetting_signals(): from common.vlm_sft import summarize, token_loss ref = torch.full((1, 4, 5), -5.0) ref[0, 0, 1] = 5.0 # start model right on step 0 (target 1) ref[0, 1, 3] = 5.0 # start model wrong on step 1 (target 2) model = ref.clone() model[0, 0, 1], model[0, 0, 4] = -5.0, 5.0 # model now wrong where start was right: forgetting model[0, 1, 3], model[0, 1, 2] = -5.0, 5.0 # model now right where start was wrong: learning labels = torch.tensor([[-100, 1, 2, -100]]) _, st = token_loss(model, ref, labels, 0.5, 1.0) assert st["fixed"] == 1.0 and st["broken"] == 1.0 and st["ref_acc"] == 0.5 and st["acc"] == 0.5 plain_loss, plain = token_loss(model, None, labels) assert plain["focus_share"] == 1.0 and plain["kl"] == 0.0 and plain_loss > 0 line = summarize([{**st, "loss": 1.0, "language": "ar", "sec": 1.0}], 3) assert "fixed 100.0%" in line and "broken 100.00%" in line and "ar" in line def test_repetition_unlikelihood_penalises_repeating_the_previous_token(): from common.vlm_sft import repetition_unlikelihood labels = torch.tensor([[-100, 1, 2, 3, -100]]) # targets 1, 2, 3 at steps 0..2 loops = torch.full((1, 5, 6), -5.0) loops[0, 1, 1] = 5.0 # at step 1 (target 2) the model wants to repeat 1 clean = torch.full((1, 5, 6), -5.0) clean[0, 1, 2] = 5.0 l_loop, m_loop = repetition_unlikelihood(loops.requires_grad_(), labels, window=2) l_clean, m_clean = repetition_unlikelihood(clean, labels, window=2) assert l_loop > 10 * l_clean and m_loop > m_clean l_loop.backward() assert loops.grad[0, 1, 1] > 0 # pushes the repeated token down # ---------------------------------------------------------------- failure mining (common/failure_mining.py) def test_failure_mining_classifies_arabic_errors_and_ids(): from common import failure_mining as fm gt = "\u0631\u064e\u0628\u0650\u064a\u0628\u064e\u0629\u064c \u062b\u064e\u0639\u0652\u0644\u064e\u0628\u064c " * 5 marks_only = fm.strip_marks(gt) # every diacritic lost, letters right assert "diacritics" in fm.arabic_flags(marks_only, gt) dotted = gt.replace("\u062b", "\u0646").replace("\u0628\u0650\u064a", "\u064a\u0650\u0628") # dot confusions assert "dots" in fm.arabic_flags(fm.strip_marks(dotted), fm.strip_marks(gt)) assert fm.arabic_flags(gt, gt) == [] assert fm.describe_id("ar_book_11") == ("ar", "book", "digital") assert fm.describe_id("ar_book_11_indoor_light_down_crease")[2] == "photo:indoor_light_down_crease" assert fm.describe_id("ar_synth_ar_numeric_tables_00008_000003")[1:] == ("ar_numeric_tables", "synthetic") page = {"layout_dets": [{"order": 1, "text": "b"}, {"order": None, "text": "header"}, {"order": 0, "text": "a"}]} assert fm.page_text(page) == "a\n\nb" # ---------------------------------------------------------------- loop guard (common/loop_guard.py) class _Tok: name_or_path = "fake" vocab = ["a", "b", "c", "\u064e", "\u0650", "", "x"] # 3, 4: diacritic marks; 5: markup def __len__(self): return len(self.vocab) def decode(self, ids): return "".join(self.vocab[i] for i in ids) def test_loop_guard_caps_marks_and_blocks_repeats_but_not_markup(): from common.loop_guard import LoopGuard g = LoopGuard(_Tok(), prompt_len=1, ngram=3, window=10, max_marks=2) s = g(torch.tensor([[6, 0, 3, 4]]), torch.zeros(1, 7)) # two marks in a row -> marks blocked assert s[0, 3] == -float("inf") and s[0, 4] == -float("inf") and s[0, 0] == 0 g = LoopGuard(_Tok(), prompt_len=1, ngram=3, window=10) s = g(torch.tensor([[6, 0, 1, 2, 0, 1]]), torch.zeros(1, 7)) # "a b" seen before, followed by "c" assert s[0, 2] == -float("inf") and s[0, 0] == 0 and g.hits["ngram"] == 1 g = LoopGuard(_Tok(), prompt_len=1, ngram=3, window=10) s = g(torch.tensor([[6, 5, 5, 5, 5]]), torch.zeros(1, 7)) # repeated stays allowed assert s[0, 5] == 0 def test_trim_repeated_tail_cuts_cycles_only_on_long_outputs(): from common.loop_guard import trim_repeated_tail body = "".join(f"line {i} with distinct content\n" for i in range(400)) # ~11k chars, no loop unit = "Yanqiao10.00\nYan+1.1\n" looped = body + unit * 40 + unit[:17] # cycle cut mid-way out, cut = trim_repeated_tail(looped) assert out.startswith(body) and out.count("Yanqiao") == 1 and cut > 30 * len(unit) assert trim_repeated_tail(body) == (body, 0) # no loop: untouched assert trim_repeated_tail(unit * 40)[1] == 0 # short output: untouched def test_script_share_routes_by_letters(): from common.vlm_infer import script_share assert script_share("
123
", "arabic") == 0.0 assert script_share("مرحبا بالعالم", "arabic") == 1.0 mixed = script_share("Hello مرحبا", "arabic") assert 0.4 < mixed < 0.6 assert script_share("文档 text", "han") == 2 / 6