File size: 12,813 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
"""ONEMODEL pilot (design ONEMODEL-pilot-1): whole-page reading in spotting mode of one checkpoint on validation page sets.
LOOPGUARD-1 copy (scripts/r5_loopguard): adds --arm A0|A1|A2, --observe (A0 with the guard in observe-only mode), the held-out
sets gen_test and school_test (readable only under the unseal token, for role A0 or the arm the token selected), the per-page
fields new_ids, guard_events, raw_unprocessed, and the meta 'decoding' block of the arm. Default --out-root is
DATA/outputs/r6_loopguard/page_preds (nothing under outputs/r6_onemodel is written). No batch-1 probe for guard arms.
With --arm A0 and no --observe the decoding path is the unchanged om_common.generate_pages.

Sets: gen_val (300 generated val pages), school_val (150 School Notebooks val pages) from the build records (images
pre-resized to <= 1,605,632 px); clutter_spot (the 500 synth_clutter_val images, resized with the same page rule; descriptive);
gen_test (300), school_test (150) from DATA/data/processed/r6_loopguard/records (held out, sealed).
Prompt 'Spotting:', page processor size, greedy, one beam, no repetition penalty, stop on the generation stop ids (+ the
trained answer end), left padding, batch --batch, max_new_tokens from build_report.json (frozen before training).
Writes one JSON line per page as soon as its batch is read (resumable): <out-root>/<name>/<set>.jsonl with the raw output
(special tokens kept), n_new, hit_cap, n_visual, seconds; then <set>.done.json. Exit 99 when --max-seconds is reached.

usage: om_eval_pages.py --model-dir DIR --name NAME --arm A0|A1|A2 [--observe] --sets gen_val,school_val [--device cuda]
"""
import argparse
import csv
import hashlib
import json
import os
import sys
import time
from datetime import datetime, timezone

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import om_common as C  # noqa: E402
import om_text as T  # noqa: E402

import torch  # noqa: E402
import transformers  # noqa: E402
from PIL import Image  # noqa: E402

vc = C.vc
csv.field_size_limit(10 ** 9)
CLUTTER = C.DATA + "/data/processed/r5/frozen_eval_v1/synth_clutter_val.tsv"
ONEMODEL_OUT = C.DATA + "/outputs/r6_onemodel"

ap = argparse.ArgumentParser()
ap.add_argument("--model-dir", required=True)
ap.add_argument("--name", required=True)
ap.add_argument("--arm", choices=["A0", "A1", "A2"], default="A0")
ap.add_argument("--observe", action="store_true", help="A0 with the A2 guard in observe-only mode (records fires, changes nothing)")
ap.add_argument("--sealed-token", default=T.OFFICIAL_UNSEAL)
ap.add_argument("--sets", default="gen_val,school_val")
ap.add_argument("--data-root", default=C.DATA + "/data/processed/r6_onemodel")
ap.add_argument("--heldout-root", default=C.DATA + "/data/processed/r6_loopguard")
ap.add_argument("--out-root", default=C.DATA + "/outputs/r6_loopguard/page_preds")
ap.add_argument("--batch", type=int, default=8)
ap.add_argument("--max-new", type=int, default=0, help="default: build_report.json max_new_tokens.value")
ap.add_argument("--device", default="cuda")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--max-seconds", type=float, default=0.0)
ap.add_argument("--limit", type=int, default=0, help="smoke: first N pages of each set")
ap.add_argument("--ids", default="", help="smoke: only these page ids (comma list)")
ap.add_argument("--batch1-probe", type=int, default=4)
a = ap.parse_args()
T0 = time.time()
dev = a.device
if a.threads:
    torch.set_num_threads(a.threads)
if a.observe and a.arm != "A0":
    raise SystemExit("--observe is only defined for arm A0")
if os.path.realpath(a.out_root).startswith(os.path.realpath(ONEMODEL_OUT)):
    raise SystemExit("REFUSED: LOOPGUARD outputs never go under %s" % ONEMODEL_OUT)
GUARD_ON = a.arm == "A2" or a.observe
ROLE = a.arm                                   # role checked against the unseal token for held-out sets
GEN_OVERRIDES = {"no_repeat_ngram_size": 20} if a.arm == "A1" else None
GUARD = None
if GUARD_ON:
    import om_guard as G
    GUARD = {"k": G.K_REP, "p_max": G.P_MAX, "t_line": G.T_LINE, "observe_only": bool(a.observe)}
    assert G.NGRAM == 20


def utc():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def say(*x):
    print("[om_eval %s %s %s]" % (a.name, a.arm + ("+observe" if a.observe else ""), utc()), *x, flush=True)


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for blk in iter(lambda: f.read(1 << 20), b""):
            h.update(blk)
    return h.hexdigest()


rep = json.load(open(os.path.join(a.data_root, "build_report.json"), encoding="utf-8"))
max_new = a.max_new or int(rep["max_new_tokens"]["value"])
out_dir = os.path.join(a.out_root, a.name)


def load_set(name):
    if name in ("gen_val", "school_val"):
        p = os.path.join(a.data_root, "records", name + ".jsonl")
        T.guard_not_test(p)
        rows = []
        with open(p, encoding="utf-8") as f:
            for line in f:
                r = json.loads(line)
                assert r["split"] == "val", r["id"]
                rows.append({"id": r["id"], "image": r["image"], "resize": False})
        return rows
    if name in T.HELDOUT_SETS:
        p = os.path.join(a.heldout_root, "records", name + ".jsonl")
        rows = []
        with T.open_sealed(p, a.sealed_token, ROLE) as f:
            for line in f:
                r = json.loads(line)
                assert r["split"] == "test", r["id"]
                rows.append({"id": r["id"], "image": r["image"], "resize": False})
        return rows
    if name == "clutter_spot":
        T.guard_not_test(CLUTTER)
        with open(CLUTTER, encoding="utf-8", newline="") as f:
            rows = [r for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)]
        assert all(r["split"] == "val" for r in rows)
        return [{"id": r["id"], "image": r["image"], "resize": True} for r in rows]
    raise SystemExit("unknown set " + name)


def load_img(r):
    im = Image.open(r["image"]).convert("RGB")
    if r["resize"]:
        w, h = T.spot_size(im.size[0], im.size[1])
        im = im.resize((w, h), Image.LANCZOS)
    else:
        w, h = T.fit_size(im.size[0], im.size[1])
        assert (w, h) == im.size, "record image %s is not at the page size rule" % r["image"]
    return im


sets = [s for s in a.sets.split(",") if s]
for s in sets:                                    # refuse held-out sets before the model is loaded or anything is written
    if s in T.HELDOUT_SETS:
        T.check_unsealed(a.sealed_token, ROLE)
os.makedirs(out_dir, exist_ok=True)

t_load = time.time()
proc, tok, model = C.load(a.model_dir, info=False)
tok.padding_side = "left"
model = model.to(dev).eval()
exp = {}
if os.path.exists(os.path.join(a.model_dir, "r5_export.json")):
    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))
gc, stops, stop_set = vc.gen_setup(model, tok, exp.get("answer_suffix_ids"))
decoding = {"greedy": True, "num_beams": 1, "repetition_penalty": 1.0, "stop_ids": stops,
            "arm": a.arm, "observe_only_guard": bool(a.observe), "no_repeat_ngram_size": (GEN_OVERRIDES or {}).get("no_repeat_ngram_size", 0),
            "guard": GUARD, "lg_design": T.LG_DESIGN_ID,
            "om_guard_sha256": sha256_file(os.path.join(HERE, "om_guard.py")) if GUARD_ON else None,
            "om_common_sha256": sha256_file(os.path.join(HERE, "om_common.py"))}
meta = {"design": T.DESIGN_ID, "lg_design": T.LG_DESIGN_ID, "name": a.name, "model_dir": os.path.realpath(a.model_dir), "export_meta": exp,
        "prompt": T.SPOT_PROMPT, "page_processor_kwargs": C.PAGE_PROC_KW, "max_new_tokens": max_new, "batch": a.batch,
        "decoding": decoding,
        "device": dev, "gpu": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu", "transformers": transformers.__version__,
        "torch": torch.__version__, "load_seconds": round(time.time() - t_load, 1), "started_utc": utc()}
want_ids = set(x for x in a.ids.split(",") if x)


def gen(imgs):
    return C.generate_pages(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, gen_overrides=GEN_OVERRIDES, guard=GUARD)


if (dev == "cuda" and a.batch1_probe and a.arm == "A0" and not a.observe and not os.path.exists(os.path.join(out_dir, "batch1_probe.json"))
        and not (a.max_seconds and a.max_seconds < 1800)):      # the probe is skipped when less than 30 min of budget is left
    probe = []
    torch.cuda.synchronize()
    torch.cuda.empty_cache()
    torch.cuda.reset_peak_memory_stats()
    for s in sets:
        if s == "clutter_spot" or s in T.HELDOUT_SETS:
            continue
        for r in load_set(s)[:a.batch1_probe]:
            im = load_img(r)
            t1 = time.time()
            x = gen([im])[0]
            torch.cuda.synchronize()
            probe.append({"set": s, "id": r["id"], "seconds": round(time.time() - t1, 3), "n_new": x["n_new"], "hit_cap": x["hit_cap"]})
    json.dump({"pages": probe, "peak_mem_reserved_batch1_GiB": round(torch.cuda.max_memory_reserved() / 2 ** 30, 3),
               "peak_mem_allocated_batch1_GiB": round(torch.cuda.max_memory_allocated() / 2 ** 30, 3), "utc": utc()},
              open(os.path.join(out_dir, "batch1_probe.json"), "w"), indent=1)
    say("batch-1 probe done", json.dumps(probe)[:300])

status = 0
for s in sets:
    rows = load_set(s)
    if want_ids:
        rows = [r for r in rows if r["id"] in want_ids]
    if a.limit:
        rows = rows[:a.limit]
    path = os.path.join(out_dir, s + ".jsonl")
    done = set()
    if os.path.exists(path):
        with open(path, encoding="utf-8") as f:
            for line in f:
                try:
                    done.add(json.loads(line)["id"])
                except ValueError:
                    pass
    pend = [r for r in rows if r["id"] not in done]
    say("%s: %d pages, %d done, max_new %d" % (s, len(rows), len(done), max_new))
    if dev == "cuda":
        torch.cuda.reset_peak_memory_stats()
    with open(path, "a", encoding="utf-8") as fo:
        for b in range(0, len(pend), a.batch):
            if a.max_seconds and time.time() - T0 > a.max_seconds:
                status = 99
                break
            bb = pend[b:b + a.batch]
            imgs = [load_img(r) for r in bb]
            t1 = time.time()
            single = False
            try:
                recs = gen(imgs)
            except Exception as ex:  # noqa: BLE001  (as eval_vlm.py: retry one image at a time, record what still fails)
                say("batch failed %s; one at a time (batch composition changes: byte identity with A0 not expected here)" % repr(ex)[:150])
                single = True
                recs = []
                for im in imgs:
                    try:
                        recs += gen([im])
                    except Exception as ex2:  # noqa: BLE001
                        recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]})
            dt = time.time() - t1
            for r, im, x in zip(bb, imgs, recs):
                x.update({"id": r["id"], "set": s, "img_w": im.size[0], "img_h": im.size[1], "batch_seconds": round(dt, 2),
                          "batch_size": len(bb), "n_instances": len(T.parse_output(x["raw"]))})
                if single:
                    x["batch_fallback_single"] = True
                fo.write(json.dumps(x, ensure_ascii=False) + "\n")
            fo.flush()
            say("%s %d/%d batch %.1fs max n_new %d fires %d" % (s, b + len(bb), len(pend), dt, max(x["n_new"] for x in recs),
                                                               sum(len(x.get("guard_events") or []) for x in recs)))
    if status == 99:
        say("time budget reached; exit 99")
        break
    ids_written = set()
    with open(path, encoding="utf-8") as f:
        for line in f:
            try:
                ids_written.add(json.loads(line)["id"])
            except (ValueError, KeyError):
                pass                      # a line torn by a hard kill: that page is simply read again on resume
    n_done = len(ids_written & {r["id"] for r in rows})
    info = {"set": s, "pages": len(rows), "written": n_done, "complete": n_done >= len(rows), "utc": utc(),
            "arm": a.arm, "observe": bool(a.observe)}
    if dev == "cuda":
        info["peak_mem_reserved_GiB_batch"] = round(torch.cuda.max_memory_reserved() / 2 ** 30, 3)
    json.dump(info, open(os.path.join(out_dir, s + ".done.json"), "w"), indent=1)
meta["finished_utc"] = utc()
meta["status"] = status
json.dump(meta, open(os.path.join(out_dir, "meta_%s_%s.json" % (os.environ.get("SLURM_JOB_ID") or "local", "+".join(sets))), "w"),
          indent=1, ensure_ascii=False)
sys.exit(status)