File size: 6,581 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
"""Test pass 2, amendment 6 (26 Nov, owner-requested, descriptive): M1 (PaddleOCR-VL 1.6 R5 leader) on az_localdoc_test with LATIN-ONLY
decoding. Identical to the test pass 2 run (eval_vlm_test.py: vlm_common prompt builder and training instruction, greedy, num_beams 1, stop
ids incl. the trained answer-end token, max_new_tokens 48/192 by unit, batch 16, left padding, bf16 on CPU, manifest order) except for one
logits processor that sets to -inf every vocabulary token whose decoded text contains a Cyrillic character (Unicode Script_Extensions
Cyrillic, r5eval.textnorm.char_script_set) and every byte-fallback token <0xD0>..<0xD4> (UTF-8 lead bytes of U+0400-U+052F; the lead
bytes of ə ğ ı ö ü ş ç are 0xC3-0xC9 and stay allowed). Latin letters, Azerbaijani letters, digits, punctuation and special tokens stay.
generate_batch is copied from vlm_common.py with the processor added (conf comes from the processed scores, as before).
Writes <preds-root>/paddleocr_vl_1_6/leader_latin_only/az_localdoc_test.{tsv,raw.jsonl} + meta.json. No score is computed here.

usage: tp2_az_latin.py --model-dir DIR --preds-root DIR --gate-file F [--limit-ids FILE] [--threads 32]
"""
import argparse
import json
import os
import sys
import time

ap = argparse.ArgumentParser()
ap.add_argument("--model-dir", required=True)
ap.add_argument("--preds-root", required=True)
ap.add_argument("--gate-file", required=True)
ap.add_argument("--threads", type=int, default=32)
ap.add_argument("--vlma", default="/path/to/TURKIC_OCR_CODE/scripts/r5_vlma")
a = ap.parse_args()
if not os.path.exists(a.gate_file):
    print("REFUSED: gate file missing", flush=True)
    sys.exit(3)
sys.path.insert(0, a.vlma)
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
import torch  # noqa: E402
import transformers  # noqa: E402
from PIL import Image  # noqa: E402

import postproc as pp  # noqa: E402
import vlm_common as vc  # noqa: E402
from r5eval import textnorm  # noqa: E402

torch.set_num_threads(a.threads)
SHORT = "paddleocr_vl_1_6"
MAN = "/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/az_localdoc_test.tsv"
t0 = time.time()
rows = vc.read_manifest(MAN)
assert all(r["split"] == "test" for r in rows) and len(rows) == 442
proc, tok = vc.load_processor(SHORT, a.model_dir)
tok.padding_side = "left"
exp = json.load(open(os.path.join(a.model_dir, "r5_export.json")))
tmpl_kw = exp.get("chat_template_kwargs", vc.template_kwargs(proc, tok))
model = vc.load_model(SHORT, a.model_dir, torch.bfloat16).eval()
gc, stops, stop_set = vc.gen_setup(model, tok, exp.get("answer_suffix_ids"))
dev = torch.device("cpu")

# ---- the mask
V = model.get_output_embeddings().weight.shape[0]
mask = torch.zeros(V, dtype=torch.bool)
BYTE_CYR = {"<0x%02X>" % b for b in range(0xD0, 0xD5)}
n_text = n_byte = 0
for i in range(V):
    try:
        s = tok.decode([i], skip_special_tokens=False, clean_up_tokenization_spaces=False)
    except Exception:  # noqa: BLE001
        s = ""
    piece = tok.convert_ids_to_tokens(i) if i < len(tok) else None
    if any("Cyrillic" in (textnorm.char_script_set(c) or ()) and "Latin" not in (textnorm.char_script_set(c) or ()) for c in s):
        mask[i] = True
        n_text += 1
    elif piece in BYTE_CYR:
        mask[i] = True
        n_byte += 1
assert not any(mask[s] for s in stops), "a stop token would be masked"
print("mask: vocab %d, masked %d (text %d, byte-fallback %d)" % (V, int(mask.sum()), n_text, n_byte), flush=True)


class LatinOnly(transformers.LogitsProcessor):
    def __call__(self, input_ids, scores):
        scores[:, mask[: scores.shape[1]].to(scores.device)] = float("-inf")
        return scores


LP = transformers.LogitsProcessorList([LatinOnly()])


def generate_batch(imgs, max_new):
    import copy
    inputs = vc.prompt_batch(SHORT, proc, imgs, tmpl_kw)
    assert bool(inputs["attention_mask"][:, -1].all()), "padding is not on the left"
    inputs = inputs.to(dev, dtype=torch.bfloat16)
    g = copy.deepcopy(gc)
    g.max_new_tokens = max_new
    with torch.inference_mode():
        out = model.generate(**inputs, generation_config=g, logits_processor=LP, output_scores=True, return_dict_in_generate=True)
        new = out.sequences[:, inputs["input_ids"].shape[1]:]
        lp = torch.stack([torch.log_softmax(s.float(), dim=-1).gather(1, new[:, t:t + 1]).squeeze(1)
                          for t, s in enumerate(out.scores[: new.shape[1]])], dim=1).cpu()
    texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)
    recs = []
    for r in range(new.shape[0]):
        row = new[r].tolist()
        n_new, hit = len(row), False
        for j, t in enumerate(row):
            if t in stop_set:
                n_new, hit = j + 1, True
                break
        v = lp[r, :n_new]
        recs.append({"raw": texts[r], "n_new": n_new, "hit_cap": (not hit) and n_new >= max_new,
                     "conf": round(float(v.mean()), 6) if n_new else None, "conf_min": round(float(v.min()), 6) if n_new else None})
    return recs


out_dir = os.path.join(a.preds_root, SHORT, "leader_latin_only")
os.makedirs(out_dir, exist_ok=True)
done = {}
with open(os.path.join(out_dir, "az_localdoc_test.raw.jsonl"), "w", encoding="utf-8") as fp:
    for b in range(0, len(rows), 16):
        bb = rows[b:b + 16]
        recs = generate_batch([vc.pad_min_grid(SHORT, proc, Image.open(r["image"]).convert("RGB"))[0] for r in bb], vc.MAXNEW[bb[0]["unit"]])
        for r, x in zip(bb, recs):
            x["id"] = r["id"]
            fp.write(json.dumps(x, ensure_ascii=False) + "\n")
            done[r["id"]] = x
        fp.flush()
        print("rows", b + len(bb), "%.0f s" % (time.time() - t0), flush=True)
tmp = os.path.join(out_dir, "az_localdoc_test.tsv.tmp")
vc.write_pred_tsv(tmp, rows, done, pp.plain_ref, pp.plain_output)
os.replace(tmp, os.path.join(out_dir, "az_localdoc_test.tsv"))
json.dump({"conf_definition": vc.CONF_DEF, "test_pass": {"script": "tp2_az_latin.py", "decoding": {"greedy": True, "num_beams": 1,
           "max_new_tokens": vc.MAXNEW, "batch": 16, "stop_ids": stops, "instruction": vc.INSTR,
           "logits_processor": "Latin-only: %d of %d tokens masked (text %d, byte-fallback %d)" % (int(mask.sum()), V, n_text, n_byte)},
           "device": "cpu bf16", "threads": a.threads, "rows": len(rows), "seconds": round(time.time() - t0, 1),
           "hit_cap_rows": sum(1 for x in done.values() if x["hit_cap"])}},
          open(os.path.join(out_dir, "meta.json"), "w"), indent=1)
print("done", len(rows), "rows", round(time.time() - t0, 1), "s", flush=True)