File size: 6,661 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
"""VLMB validation predictions with one adapter and one checkpoint (greedy; 48 new tokens for words, 192 for lines).

Never reads a locked (test) set: every manifest is checked against evalsets.json when --evalsets is given, and any
manifest path containing "test" is refused.

usage: vlmb_predict.py --short S --model-dir D --ckpt CKPT_DIR|none --manifest M.tsv --name EVALSET --out OUT_DIR
         [--limit N] [--batch-size 16] [--device cuda] [--speed] [--model-id ID --revision REV]
"""
import argparse
import importlib
import json
import os
import sys
import time
from datetime import datetime, timezone

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

ap = argparse.ArgumentParser()
ap.add_argument("--short", required=True)
ap.add_argument("--model-dir", required=True)
ap.add_argument("--ckpt", required=True)
ap.add_argument("--manifest", required=True)
ap.add_argument("--name", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--batch-size", type=int, default=16)
ap.add_argument("--device", default="cuda")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--speed", action="store_true", help="also measure peak memory at batch 1 and images/s at batch 16")
ap.add_argument("--model-id", default="")
ap.add_argument("--revision", default="")
ap.add_argument("--precision", default="amp_bf16")
ap.add_argument("--meta-extra", default="{}")
args = ap.parse_args()
assert "test" not in os.path.basename(args.manifest).lower(), "refusing a test manifest"

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import torch  # noqa: E402
from PIL import Image  # noqa: E402

if args.threads:
    torch.set_num_threads(args.threads)
dev = torch.device(args.device)
use_cuda = dev.type == "cuda"
os.makedirs(args.out, exist_ok=True)

rows = []
with open(args.manifest, encoding="utf-8", newline="") as f:
    hdr = f.readline().rstrip("\n").split("\t")
    ci = {h: i for i, h in enumerate(hdr)}
    for line in f:
        p = line.rstrip("\n").split("\t")
        rows.append((p[ci["id"]], p[ci["image"]], p[ci["text"]], p[ci["unit"]] if "unit" in ci else "word",
                     p[ci["split"]] if "split" in ci else ""))
assert all(r[4] != "test" for r in rows), "manifest holds test rows"
if args.limit:
    rows = rows[: args.limit]

t0 = time.time()
ad = importlib.import_module("adapters.ad_" + args.short).Adapter(args.model_dir, dev, args.precision)
ck_info = {"checkpoint": "base (no fine-tune)"}
if args.ckpt != "none":
    sd = torch.load(os.path.join(args.ckpt, "model.pt"), map_location="cpu", weights_only=True)
    missing, unexpected = ad.model.load_state_dict(sd, strict=False)
    assert not missing and not unexpected, (missing[:5], unexpected[:5])
    del sd
    st = json.load(open(os.path.join(args.ckpt, "state.json")))
    ck_info = {"checkpoint": args.ckpt, "samples_seen": st["samples_seen"], "step": st["step"]}
ad.prepare_eval()
load_s = time.time() - t0

pred_path = os.path.join(args.out, args.name + ".tsv")
done = {}
if os.path.exists(pred_path):
    with open(pred_path, encoding="utf-8") as f:
        f.readline()
        for line in f:
            p = line.rstrip("\n").split("\t")
            done[p[0]] = p
todo = [r for r in rows if r[0] not in done]


def clean(s):
    return s.replace("\t", " ").replace("\r", " ").replace("\n", " \\n ")


new_file = not os.path.exists(pred_path)
t_gen, n_gen = 0.0, 0
with open(pred_path, "a", encoding="utf-8") as fo:
    if new_file:
        fo.write("id\tref\thyp\n")
    for unit in ("word", "line", "page"):
        part = [r for r in todo if (r[3] or "word") == unit]
        mnt = 48 if unit == "word" else 192 if unit == "line" else 1024
        for b in range(0, len(part), args.batch_size):
            batch = part[b: b + args.batch_size]
            ims = [Image.open(r[1]).convert("RGB") for r in batch]
            tg = time.time()
            try:
                hyps = ad.generate(ims, mnt)
            except Exception as e:  # noqa: BLE001
                print("batch failed, one at a time:", repr(e)[:300], flush=True)
                hyps = []
                for im in ims:
                    try:
                        hyps.append(ad.generate([im], mnt)[0])
                    except Exception as e2:  # noqa: BLE001
                        print("item failed:", repr(e2)[:300], flush=True)
                        hyps.append("")
            if use_cuda:
                torch.cuda.synchronize()
            t_gen += time.time() - tg
            n_gen += len(batch)
            for r, h in zip(batch, hyps):
                fo.write(f"{r[0]}\t{clean(r[2])}\t{clean(h)}\n")
            fo.flush()

speed = {}
if args.speed and rows:
    ims = [Image.open(r[1]).convert("RGB") for r in rows[:16]]
    unit = rows[0][3] or "word"
    mnt = 48 if unit == "word" else 192
    if use_cuda:
        torch.cuda.empty_cache()
        torch.cuda.reset_peak_memory_stats()
    ad.generate(ims[:1], mnt)
    if use_cuda:
        torch.cuda.synchronize()
        speed["peak_gpu_mem_batch1_bytes"] = torch.cuda.max_memory_allocated()
    ad.generate(ims, mnt)  # warm
    if use_cuda:
        torch.cuda.synchronize()
    ts = time.time()
    for _ in range(2):
        ad.generate(ims, mnt)
    if use_cuda:
        torch.cuda.synchronize()
    speed["images_per_second_batch16"] = round(2 * len(ims) / (time.time() - ts), 2)
    speed["speed_unit"] = unit

meta = {"model_id": args.model_id, "revision": args.revision, "arm": args.short, **ck_info,
        "evalset": args.name, "manifest": args.manifest, "rows": len(rows),
        "decoding": {"greedy": True, "max_new_tokens": {"word": 48, "line": 192}},
        "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", "load_seconds": round(load_s, 1),
        "generate_seconds_this_session": round(t_gen, 1), "generated_this_session": n_gen,
        "torch": torch.__version__, "transformers": __import__("transformers").__version__,
        "job": os.environ.get("SLURM_JOB_ID", ""), "adapter_notes": getattr(ad, "NOTES", ""),
        "updated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), **speed,
        **json.loads(args.meta_extra)}
json.dump(meta, open(os.path.join(args.out, "meta.json" if args.name == "_" else f"meta_{args.name}.json"), "w"),
          indent=1, ensure_ascii=False)
print(json.dumps({k: v for k, v in meta.items() if k != "adapter_notes"}, ensure_ascii=False), flush=True)