File size: 8,303 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
3258269
 
24aaa76
3258269
 
 
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3258269
24aaa76
 
 
 
 
3258269
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
import argparse
import csv
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
import om_text as T

import torch
import transformers
from PIL import Image

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

ap = argparse.ArgumentParser()
ap.add_argument("--model-dir", required=True)
ap.add_argument("--name", required=True)
ap.add_argument("--sets", default="gen_val,school_val")
ap.add_argument("--data-root", default=C.DATA + "/data/processed/r6_onemodel")
ap.add_argument("--out-root", default=C.DATA + "/outputs/r6_onemodel/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)


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


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


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)
os.makedirs(out_dir, exist_ok=True)


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 == "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


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"))
meta = {"design": T.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": {"greedy": True, "num_beams": 1, "repetition_penalty": 1.0, "stop_ids": stops},
        "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()}
sets = [s for s in a.sets.split(",") if s]
want_ids = set(x for x in a.ids.split(",") if x)

if (dev == "cuda" and a.batch1_probe 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":
            continue
        for r in load_set(s)[:a.batch1_probe]:
            im = load_img(r)
            t1 = time.time()
            x = C.generate_pages(model, proc, tok, [im], max_new, tmpl_kw, gc, stop_set, dev)[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()
            try:
                recs = C.generate_pages(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev)
            except Exception as ex:
                say("batch failed %s; one at a time" % repr(ex)[:150])
                recs = []
                for im in imgs:
                    try:
                        recs += C.generate_pages(model, proc, tok, [im], max_new, tmpl_kw, gc, stop_set, dev)
                    except Exception as ex2:
                        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"]))})
                fo.write(json.dumps(x, ensure_ascii=False) + "\n")
            fo.flush()
            say("%s %d/%d batch %.1fs max n_new %d" % (s, b + len(bb), len(pend), dt, max(x["n_new"] 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()}
    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)