File size: 8,033 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
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
# SPDX-License-Identifier: Apache-2.0
"""End-to-end device run (frontend -> ttnn vision -> ttnn prefill -> decode engine) on the golden cases.

    bin/devrun -t 1500 -- python -u common/dsocr/tt_dsocr/tests/dev_e2e.py --cases formula_quad__tiny,table_sales__gundam \
        --dec ttnn|mk [--no-trace] [--max-new 2048]

Per case: image-embedding PCC vs golden, greedy tokens vs golden (identical / first mismatch / CER), TTFT, vision /
prefill ms, decode tokens/s, page latency. Results -> assets/dsocr/runs/e2e_<tag>.json.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time

import torch

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, GOLDEN, MODELS, RUNS  # noqa: E402


def pcc(a, b):
    a, b = a.double().flatten(), b.double().flatten()
    a, b = a - a.mean(), b - b.mean()
    return float((a @ b) / (a.norm() * b.norm() + 1e-30))


def cer(a: str, b: str) -> float:
    if not b:
        return float(len(a) > 0)
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i] + [0] * len(b)
        for j, cb in enumerate(b, 1):
            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))
        prev = cur
    return prev[-1] / len(b)


def _arm_faulthandler():
    """Dump the Python stacks on a fatal signal (SIGSEGV / SIGABRT / ...; devrun's timeout kill shows where a job was).
    No periodic watchdog: ``faulthandler.dump_traceback_later(repeat=True)`` segfaults Python 3.12 when it fires while
    the main thread switches generators (the verifier's report, 2026-12-02), so the former DSOCR_FAULT_S is gone; use
    pytest's ``-o faulthandler_timeout`` or ``python -u`` progress prints instead."""
    import faulthandler

    faulthandler.enable(file=sys.stderr)


def main():
    _arm_faulthandler()
    ap = argparse.ArgumentParser()
    ap.add_argument("--variant", default="deepseek-ocr")
    ap.add_argument("--cases", default="formula_quad__tiny")
    ap.add_argument("--dec", default="ttnn")
    ap.add_argument("--no-trace", action="store_true")
    ap.add_argument("--max-new", type=int, default=0)
    ap.add_argument("--recipe", default="bfp8")
    ap.add_argument("--max-context", type=int, default=4096)
    ap.add_argument("--tag", default="")
    ap.add_argument("--sparse", action="store_true", help="ttnn decode: MoE over the 6 gathered experts")
    ap.add_argument("--reps", type=int, default=2, help="requests per case (the last one is timed)")
    ap.add_argument("--tile-chunk", type=int, default=0, help="Gundam tiles per vision run (0 = the default)")
    args = ap.parse_args()
    import ttnn
    from tt_dsocr.ttaw.device import open_device, close_device
    from tt_dsocr.tt.model import DeviceConfig, DsocrDevice, NGram, Sampling

    gdir = GOLDEN[args.variant]
    V = FE.VARIANTS[args.variant]
    imgs = {}
    for f in ("images.json", "images_ko.json"):  # the shared set + the Korean pages (schift-ocr-1-beta)
        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])
    cases = []
    modes = set()
    max_tiles = 2
    uocr = args.variant == "unlimited-ocr-2"
    win = C.VARIANTS[args.variant].window       # schift-ocr-1-beta: the 128-token decode window
    few = uocr or win > 0                        # dev runs: prefill buckets / tiles of the cases only
    for c in args.cases.split(","):
        name, mode = c.split("__")
        meta = json.load(open(os.path.join(gdir, c, "meta.json")))
        gt = torch.load(os.path.join(gdir, c, "tensors.pt"), weights_only=True)
        files = [os.path.join(ASSETS, imgs[n]["file"]) for n in name.split("+")]
        if uocr:  # the golden prompt is the full one ("<PAGE><image>..." + instruction)
            prep = FE.prepare_pages(V, tok, files, meta["prompt"], mode)
        else:
            prep = FE.prepare(V, tok, files[0], meta["prompt_text"], mode)
        assert prep.ids == meta["input_ids"], f"{c}: prompt ids differ from the golden"
        pages = prep.extra.get("pages") or [{"tiles_px": prep.tiles_px}]
        max_tiles = max([max_tiles] + [0 if p["tiles_px"] is None else p["tiles_px"].shape[0] for p in pages])
        cases.append((c, meta, gt, prep))
        modes.add(mode)
    log = lambda s: print(s, flush=True)  # noqa: E731
    pb = tuple(sorted({-(-len(x[3].ids) // 128) * 128 for x in cases})) if few else ()
    kv = max(args.max_context, (max(pb) + win + 31) // 32 * 32) if win else args.max_context
    cfg = DeviceConfig(variant=args.variant, modes=tuple(sorted(modes)), max_context=kv, window=win,
                       max_positions=C.VARIANTS[args.variant].context_cap if win else 0,
                       engine_dec="ttnn" if uocr else args.dec, mk_recipe=args.recipe, trace=not args.no_trace,
                       sparse_decode=args.sparse, **({"tile_chunk": args.tile_chunk} if args.tile_chunk else {}),
                       max_crops=max(max_tiles, 2) if few else V.crop_max, prefill_buckets=pb)
    # the megakernel needs the larger kernel-config ring (64 KiB less worker L1); the ttnn engines keep the default
    # worker L1 (FAULTS.md #3: the only run of the ttnn engines with the reduced L1 hung)
    kw = {"worker_l1_size": 1461248 - (64 << 10)} if cfg.engine_dec == "mk" else {}
    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"[e2e] engines ready in {time.time() - t0:.0f} s")
        for c, meta, gt, prep in cases:
            r = {}
            if uocr:
                emb = m.prompt_rows(prep)[gt["seq_mask"]]
            else:
                emb = m.image_rows(prep)
            r["emb_pcc"] = pcc(emb, gt["img_emb"])
            gen = meta["gen_ids"]
            mx = args.max_new or (len(gen) + 16)
            ngram = NGram(0) if uocr else NGram(meta.get("ngram", 20))
            for rep in range(max(1, args.reps)):  # the last run is the timed one (warm traces / caches)
                out = list(m.generate(prep, mx, Sampling(), ngram))
                tm = m.timings()
                if args.dec == "mk" and not uocr:
                    ab = m.dec.tlk.aborts()
                    same = sum(1 for a, b in zip(out, gen) if a == b)
                    log(f"[soak] {c} rep {rep}: {len(out)} tokens, {same} equal to the golden prefix-wise, "
                        f"aborts {len(ab)} {ab[:3]}")
            text = tok.decode(out)
            if uocr:  # the Unlimited-OCR-2 golden text drops the EOS (the official infer's text)
                text = tok.decode([t for t in out if t != FE.EOS_ID])
            same = 0
            while same < min(len(out), len(gen)) and out[same] == gen[same]:
                same += 1
            r.update({k: v for k, v in tm.items() if k != "tokens"})
            r.update(text=text, out_ids=out)
            r.update(tokens=len(out), identical=out == gen, prefix_match=same, cer=cer(text, meta["text"]),
                     page_ms=tm["ttft_ms"] + tm.get("decode_ms", 0.0))
            log(f"[{c}] emb PCC {r['emb_pcc']:.5f}; {len(out)} tokens identical {out == gen} (first {same}), CER "
                f"{r['cer']:.4f}; vision {tm['vision_ms']:.0f} ms, prefill {tm['prefill_ms']:.0f} ms, TTFT "
                f"{tm['ttft_ms']:.0f} ms, decode {tm.get('tokens_per_s', 0):.1f} tok/s, page {r['page_ms']:.0f} ms")
            res["cases"][c] = r
    finally:
        os.makedirs(RUNS, exist_ok=True)
        json.dump(res, open(os.path.join(RUNS, f"e2e_{args.tag or 'run'}.json"), "w"), indent=1, default=str)
        close_device(dev)


if __name__ == "__main__":
    main()