File size: 13,509 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
285
286
287
288
289
290
291
"""J2 screen: zero-shot reading of KOHTD validation word crops with one stock-transformers model.

Native transformers classes only (trust_remote_code is never set), safetensors only, greedy, bf16, sdpa.
This script never reads labels and never opens train.tsv or test.tsv: it reads crop_file from screen_set_v1.tsv only.
Writes after every batch and resumes from preds.jsonl.

usage: run_screen.py SHORT MODELS_DIR PROMPTS_JSON SCREEN_SET_TSV IMG_DIR OUT_ROOT
         [--batch-size 16] [--max-new-tokens 48] [--scales 1,2,3] [--limit N] [--device cuda|cpu]
         [--threads N] [--check-batch-equal]
"""
import argparse
import copy
import json
import os
import sys
import time
from datetime import datetime, timezone

os.environ.setdefault("HF_HUB_OFFLINE", "1")
for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
    os.environ.pop(k, None)

ap = argparse.ArgumentParser()
ap.add_argument("short")
ap.add_argument("models_dir")
ap.add_argument("prompts_json")
ap.add_argument("screen_set")
ap.add_argument("img_dir")
ap.add_argument("out_root")
ap.add_argument("--batch-size", type=int, default=16)
ap.add_argument("--max-new-tokens", type=int, default=48)
ap.add_argument("--scales", default="1,2,3")
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--device", default="cuda")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--check-batch-equal", action="store_true")
args = ap.parse_args()

assert "screen_set_v1.tsv" in args.screen_set
import torch
import transformers
from PIL import Image

if args.threads:
    torch.set_num_threads(args.threads)
dev = args.device
use_cuda = dev == "cuda"
assert (not use_cuda) or torch.cuda.is_available(), "cuda requested but not available"

CARD_CLASS = {"lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", "lightonocr_3_1b": "LightOnOcrForConditionalGeneration"}
CARD_PROC = {"lightonocr_3_1b": "LightOnOcrProcessor"}
TWO_STEP = {"granite_docling_258m"}   # card: apply_chat_template(text) then processor(text, images)

P = json.load(open(args.prompts_json, encoding="utf-8"))[args.short]
prompt = P["prompt"]
model_path = os.path.join(args.models_dir, args.short)
assert not any(f.endswith(".py") for f in os.listdir(model_path)), "a .py file in the model folder"

crops = []
with open(args.screen_set, encoding="utf-8", newline="") as f:
    hdr = f.readline().rstrip("\n").split("\t")
    assert hdr == ["crop_file", "form_id", "label"]
    for line in f:
        crops.append(line.rstrip("\n").split("\t")[0])
if args.limit:
    crops = crops[: args.limit]
print(f"[{args.short}] crops {len(crops)} device {dev} batch {args.batch_size} scales {args.scales}", flush=True)

t_load = time.time()
cls = None
if args.short in CARD_CLASS:
    cls = getattr(transformers, CARD_CLASS[args.short], None)
if cls is None:
    cls = transformers.AutoModelForImageTextToText
pcls = getattr(transformers, CARD_PROC.get(args.short, ""), None) or transformers.AutoProcessor
processor = pcls.from_pretrained(model_path, trust_remote_code=False)
model = cls.from_pretrained(model_path, dtype=torch.bfloat16, trust_remote_code=False, use_safetensors=True,
                            attn_implementation="sdpa")
model = model.to(dev).eval()
load_seconds = time.time() - t_load
tok = getattr(processor, "tokenizer", processor)
tok.padding_side = "left"
if getattr(tok, "pad_token_id", None) is None:
    tok.pad_token = tok.eos_token

seen_p, n_params = set(), 0
for p in model.parameters():
    if id(p) not in seen_p:
        seen_p.add(id(p))
        n_params += p.numel()

gc = copy.deepcopy(model.generation_config)
gc.max_new_tokens = args.max_new_tokens
gc.do_sample = False
gc.num_beams = 1
gc.repetition_penalty = 1.0
gc.no_repeat_ngram_size = 0
gc.temperature = None
gc.top_p = None
gc.top_k = None
if gc.pad_token_id is None:
    gc.pad_token_id = tok.pad_token_id
eos_ids = set()
for e in (gc.eos_token_id, getattr(tok, "eos_token_id", None)):
    if isinstance(e, (list, tuple)):
        eos_ids.update(e)
    elif e is not None:
        eos_ids.add(e)
# stop on the generation config's end ids AND the tokenizer's end token (the chat turn end, e.g. <|im_end|>), as
# the serving stacks of the cards do; without this OvisOCR2 ran on after its turn end in the smoke test
gc.eos_token_id = sorted(eos_ids)
stop_ids_used = sorted(eos_ids)
if gc.pad_token_id is not None:
    eos_ids.add(gc.pad_token_id)

img_tok_id = getattr(model.config, "image_token_id", None)
if img_tok_id is None:
    img_tok_id = getattr(processor, "image_token_id", None)
if img_tok_id is None and getattr(processor, "image_token", None):
    img_tok_id = tok.convert_tokens_to_ids(processor.image_token)

images_kwargs = copy.deepcopy(P.get("images_kwargs"))
if images_kwargs and images_kwargs.get("size", {}).get("shortest_edge") == "MIN_PIXELS_FROM_PROCESSOR":
    # card: processor.image_processor.min_pixels; the native processor keeps it as size["shortest_edge"]
    _ip = processor.image_processor
    _mp = getattr(_ip, "min_pixels", None)
    if _mp is None:
        _sz = _ip.size
        _mp = _sz["shortest_edge"] if isinstance(_sz, dict) else getattr(_sz, "shortest_edge")
    images_kwargs["size"]["shortest_edge"] = int(_mp)
tmpl_kwargs = {"enable_thinking": False} if P.get("enable_thinking_false") else {}

if use_cuda:
    torch.cuda.synchronize()
    mem_after_load = torch.cuda.memory_allocated()
    torch.cuda.reset_peak_memory_stats()
else:
    mem_after_load = 0
job_id = os.environ.get("SLURM_JOB_ID", "")
revision = None
try:
    lt = json.load(open(os.path.join(os.path.dirname(os.path.abspath(args.out_root)), "j11_stage1_kohtd", "loadtest", args.short + ".json")))
    revision = lt.get("revision")
except Exception:  # noqa: BLE001
    pass


def load_image(crop_file, scale):
    im = Image.open(os.path.join(args.img_dir, crop_file)).convert("RGB")
    if scale != 1:
        im = im.resize((im.width * scale, im.height * scale), Image.Resampling.LANCZOS)
    return im


def build_inputs(imgs):
    content_text = [{"type": "text", "text": prompt}] if prompt else []
    if args.short in TWO_STEP:
        convs = [[{"role": "user", "content": [{"type": "image"}] + content_text}] for _ in imgs]
        texts = [processor.apply_chat_template(c, add_generation_prompt=True) for c in convs]
        inputs = processor(text=texts, images=[[im] for im in imgs], return_tensors="pt", padding=True)
    else:
        convs = [[{"role": "user", "content": [{"type": "image", "image": im}] + content_text}] for im in imgs]
        kw = dict(tmpl_kwargs)
        if images_kwargs:
            kw["images_kwargs"] = images_kwargs
        inputs = processor.apply_chat_template(convs, add_generation_prompt=True, tokenize=True, return_dict=True,
                                               return_tensors="pt", padding=True, **kw)
    return inputs


def generate_batch(imgs):
    t0 = time.time()
    inputs = build_inputs(imgs)
    am = inputs["attention_mask"]
    assert bool(am[:, -1].all()), "padding is not on the left"
    inputs = inputs.to(dev, dtype=torch.bfloat16)
    t1 = time.time()
    if use_cuda:
        torch.cuda.synchronize()
        t1 = time.time()
    with torch.inference_mode():
        out = model.generate(**inputs, generation_config=gc)
    if use_cuda:
        torch.cuda.synchronize()
    t2 = time.time()
    in_len = inputs["input_ids"].shape[1]
    new = out[:, in_len:]
    try:
        texts = processor.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)
    except Exception:  # noqa: BLE001
        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_eos = len(row), False
        for j, t in enumerate(row):
            if t in eos_ids:
                n_new, hit_eos = j + 1, True
                break
        n_img = int((inputs["input_ids"][r] == img_tok_id).sum()) if img_tok_id is not None else -1
        recs.append({"raw": texts[r], "n_new": n_new, "hit_cap": (not hit_eos) and n_new >= args.max_new_tokens,
                     "n_img_tokens": n_img, "in_len": int(am[r].sum())})
    return recs, t1 - t0, t2 - t1


def run_scale(scale, out_dir, bs, list_crops):
    os.makedirs(out_dir, exist_ok=True)
    pred_path = os.path.join(out_dir, "preds.jsonl")
    time_path = os.path.join(out_dir, "timing.jsonl")
    done = set()
    if os.path.exists(pred_path):
        for line in open(pred_path, encoding="utf-8"):
            try:
                done.add(json.loads(line)["crop_file"])
            except Exception:  # noqa: BLE001
                pass
    todo = [c for c in list_crops if c not in done]
    print(f"[{args.short}] scale {scale}x: done {len(done)}, to do {len(todo)}", flush=True)
    meta_path = os.path.join(out_dir, "meta.json")
    prev = json.load(open(meta_path)) if os.path.exists(meta_path) else {}
    peak = prev.get("peak_gpu_mem_allocated_bytes", 0)
    sessions = prev.get("job_ids", [])
    if job_id and job_id not in sessions:
        sessions.append(job_id)
    errors = prev.get("errors", 0)
    with open(pred_path, "a", encoding="utf-8") as fp, open(time_path, "a", encoding="utf-8") as ft:
        for b in range(0, len(todo), bs):
            batch = todo[b: b + bs]
            t_img = 0.0
            try:
                ti = time.time()
                imgs = [load_image(c, scale) for c in batch]
                t_img = time.time() - ti
                recs, t_pre, t_gen = generate_batch(imgs)
            except Exception as e:  # noqa: BLE001
                print(f"[{args.short}] batch failed ({repr(e)[:200]}); one crop at a time", flush=True)
                if use_cuda:
                    torch.cuda.empty_cache()
                recs, t_pre, t_gen = [], 0.0, 0.0
                for c in batch:
                    try:
                        r1, a, g = generate_batch([load_image(c, scale)])
                        recs.append(r1[0])
                        t_pre += a
                        t_gen += g
                    except Exception as e2:  # noqa: BLE001
                        errors += 1
                        recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_img_tokens": -1, "in_len": -1,
                                     "error": repr(e2)[:300]})
            for c, r in zip(batch, recs):
                r.update({"crop_file": c, "scale": scale, "batch_size": bs})
                fp.write(json.dumps(r, ensure_ascii=False) + "\n")
            fp.flush()
            os.fsync(fp.fileno())
            pk = torch.cuda.max_memory_allocated() if use_cuda else 0
            peak = max(peak, pk)
            ft.write(json.dumps({"n": len(batch), "t_img": round(t_img, 4), "t_pre": round(t_pre, 4), "t_gen": round(t_gen, 4),
                                 "new_tokens": sum(r["n_new"] for r in recs), "job_id": job_id,
                                 "batch_first_crop": batch[0]}) + "\n")
            ft.flush()
    meta = {
        "short": args.short, "repo_revision": revision, "scale": scale, "prompt": prompt, "prompt_note": P["note"],
        "transformers": transformers.__version__, "torch": torch.__version__, "device": dev,
        "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", "dtype": "bfloat16",
        "attn_implementation": getattr(model.config, "_attn_implementation", None), "batch_size": bs,
        "max_new_tokens": args.max_new_tokens, "model_class": type(model).__module__ + "." + type(model).__name__,
        "processor_class": type(processor).__module__ + "." + type(processor).__name__,
        "params_unique": n_params, "generation_config_used": {k: v for k, v in gc.to_dict().items() if v is not None},
        "stop_token_ids": stop_ids_used, "images_kwargs": images_kwargs, "chat_template_kwargs": tmpl_kwargs, "two_step_processor": args.short in TWO_STEP,
        "load_seconds": round(load_seconds, 1), "mem_after_load_bytes": mem_after_load,
        "peak_gpu_mem_allocated_bytes": peak, "peak_note": "H100, not the RTX 5090; torch.cuda.max_memory_allocated after weights were loaded and the peak counter reset" if use_cuda else "cpu run: no GPU memory figure",
        "job_ids": sessions, "errors": errors, "updated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "screen_set": os.path.basename(args.screen_set), "crops_in_list": len(list_crops),
    }
    json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False)
    return meta


model_dir_out = os.path.join(args.out_root, args.short)
for s in [int(x) for x in args.scales.split(",")]:
    meta = run_scale(s, os.path.join(model_dir_out, f"s{s}"), args.batch_size, crops)
    print(f"[{args.short}] scale {s}x finished; peak GPU mem {meta['peak_gpu_mem_allocated_bytes']/2**30:.2f} GiB", flush=True)

if args.check_batch_equal:
    a = [json.loads(l)["raw"] for l in open(os.path.join(model_dir_out, "s1", "preds.jsonl"), encoding="utf-8")]
    run_scale(1, os.path.join(model_dir_out, "s1_batch1_check"), 1, crops)
    b = [json.loads(l)["raw"] for l in open(os.path.join(model_dir_out, "s1_batch1_check", "preds.jsonl"), encoding="utf-8")]
    res = {"crops": len(a), "identical": sum(1 for x, y in zip(a, b) if x == y), "batch_N": a, "batch_1": b}
    json.dump(res, open(os.path.join(model_dir_out, "batch_equal_check.json"), "w"), indent=1, ensure_ascii=False)
    print(f"[{args.short}] batch-N vs batch-1 identical outputs: {res['identical']} of {res['crops']}", flush=True)