File size: 4,263 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Device: the whole pipeline (views -> traced vision -> prefill -> decode) on test images WITHOUT goldens: prints the
text, the token count and the timings, and writes them to ``<RUNS>/run_<tag>.json`` (a later gate compares them with
the official outputs). One device process; run it under ``bin/devrun``.

    bin/devrun -t 900 --reset-on-timeout -- python -u common/dsocr/tt_dsocr/tests/dev_run.py \\
        --variant schift-ocr-1-beta --images ko_notice,ko_table --dec ttnn --tag schift_first
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from tt_dsocr import config as C  # noqa: E402
from tt_dsocr import frontend as FE  # noqa: E402
from tt_dsocr.tests._paths import ASSETS, MODELS, RUNS  # noqa: E402


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--variant", default="schift-ocr-1-beta")
    ap.add_argument("--images", required=True, help="names in images.json / images_ko.json, comma-separated")
    ap.add_argument("--mode", default="gundam")
    ap.add_argument("--prompt", default="")
    ap.add_argument("--dec", default="ttnn")
    ap.add_argument("--max-new", type=int, default=2000)
    ap.add_argument("--tag", default="run")
    ap.add_argument("--no-trace", action="store_true")
    args = ap.parse_args()
    from tt_dsocr.tt.model import DeviceConfig, DsocrDevice, NGram, Sampling
    from tt_dsocr.ttaw.device import close_device, open_device

    v = C.VARIANTS[args.variant]
    V = FE.VARIANTS[args.variant]
    imgs = {}
    for f in ("images.json", "images_ko.json"):
        if os.path.isfile(os.path.join(ASSETS, f)):
            imgs.update({e["name"]: e for e in json.load(open(os.path.join(ASSETS, f)))})
    tok = FE.Tokenizer(MODELS[args.variant])
    prompt = args.prompt or next(iter(C.TASK_PROMPTS[args.variant].values()))
    preps = [(n, FE.prepare(V, tok, os.path.join(ASSETS, imgs[n]["file"]), prompt, args.mode))
             for n in args.images.split(",")]
    pb = tuple(sorted({-(-len(p.ids) // 128) * 128 for _, p in preps}))
    tiles = max([2] + [p.n_tiles for _, p in preps])
    kv = (max(pb) + v.window + 31) // 32 * 32 if v.window else 8192
    cfg = DeviceConfig(variant=args.variant, modes=(args.mode,), max_context=kv, window=v.window,
                       max_positions=v.context_cap if v.window else 0, engine_dec=args.dec,
                       trace=not args.no_trace, max_crops=tiles, prefill_buckets=pb)
    kw = {"worker_l1_size": 1461248 - (64 << 10)} if args.dec == "mk" else {}
    log = lambda s: print(s, flush=True)  # noqa: E731
    dev = open_device(0, dispatch="eth", trace_region_size=1024 << 20, l1_small_size=1 << 15, **kw)
    res = {"args": vars(args), "cases": {}}
    try:
        t0 = time.time()
        m = DsocrDevice(dev, MODELS[args.variant], cfg, log=log)
        log(f"[run] engines ready in {time.time() - t0:.0f} s (buckets {pb}, kv {kv}, window {v.window})")
        for name, prep in preps:
            t1 = time.time()
            out = list(m.generate(prep, args.max_new, Sampling(), NGram(0)))
            dt = time.time() - t1
            text = tok.decode(out)
            tm = dict(getattr(m, "_t", {}) or {})
            r = {"tokens": len(out), "out_ids": out, "text": text, "eos": bool(out) and out[-1] == FE.EOS_ID,
                 "page_s": dt, "prompt_tokens": len(prep.ids), "tiles": prep.n_tiles,
                 **{k: tm[k] for k in ("vision_ms", "prefill_ms", "ttft_ms") if k in tm}}
            r["tokens_per_s"] = (len(out) - 1) / max(1e-9, dt - tm.get("ttft_ms", 0) / 1e3) if len(out) > 1 else 0
            res["cases"][name] = r
            log(f"[{name}] {len(out)} tokens (eos {r['eos']}), {prep.n_tiles} tiles, prompt {len(prep.ids)}, "
                f"TTFT {tm.get('ttft_ms', 0):.0f} ms, page {dt:.2f} s, {r['tokens_per_s']:.1f} tok/s\n{text[:1500]}\n---")
    finally:
        close_device(dev)
        if RUNS:
            os.makedirs(RUNS, exist_ok=True)
            json.dump(res, open(os.path.join(RUNS, f"run_{args.tag}.json"), "w"), indent=1, ensure_ascii=False)


if __name__ == "__main__":
    main()