File size: 6,989 Bytes
c60a316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Device check of the Unlimited-OCR-2 DASH decoder (tt/ttnn_dash.py) on the golden image rows (no vision):
prefill logits vs the official fp32 golden, teacher-forced decode over the golden tokens (page guard on), then a
greedy loop compared with the golden output.

    bin/devrun -t 1200 -- python -u common/dsocr/tt_dsocr/tests/dev_uocr.py --cases formula_quad__gundam [--gen 0]
"""

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.reference import model as R  # noqa: E402
from tt_dsocr.reference import uocr2 as U  # noqa: E402
from tt_dsocr.tests._paths import 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 tvd(a, b):
    return float(0.5 * (a.float().softmax(-1) - b.float().softmax(-1)).abs().sum())


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("--cases", default="formula_quad__gundam")
    ap.add_argument("--max-context", type=int, default=4096)
    ap.add_argument("--tf-steps", type=int, default=0, help="0 = every golden step")
    ap.add_argument("--gen", type=int, default=-1, help="greedy tokens (-1 = golden length + 8, 0 = skip)")
    ap.add_argument("--tag", default="uocr")
    ap.add_argument("--sparse", action="store_true", help="decode MoE over the 6 gathered experts")
    ap.add_argument("--trace", action="store_true", help="warm up + trace the decode halves (24 traces)")
    args = ap.parse_args()
    import ttnn  # noqa: F401
    from tt_dsocr.ttaw.device import open_device, close_device
    from tt_dsocr.tt.model import PageGuard
    from tt_dsocr.tt.ttnn_dash import TtnnDashDecoder

    W = R.Weights(MODELS["unlimited-ocr-2"])
    emb = W.get(R.PFX + "embed_tokens.weight", cache=False)
    cases = []
    for c in args.cases.split(","):
        d = os.path.join(GOLDEN["unlimited-ocr-2"], c)
        meta = json.load(open(os.path.join(d, "meta.json")))
        ten = torch.load(os.path.join(d, "tensors.pt"), weights_only=True)
        st = torch.load(os.path.join(d, "steps.pt"), weights_only=True)
        ids = meta["input_ids"]
        rows = emb[torch.tensor(ids)].float()
        rows[ten["seq_mask"]] = ten["img_emb"].float()
        cases.append((c, meta, st, ids, rows))
    buckets = sorted({-(-len(x[3]) // 128) * 128 for x in cases})
    dev = open_device(0, dispatch="eth", trace_region_size=64 << 20)
    res = {"args": vars(args), "cases": {}}
    log = lambda s: print(s, flush=True)  # noqa: E731
    try:
        t0 = time.time()
        dec = TtnnDashDecoder(dev, W, buckets, args.max_context, sparse_decode=args.sparse)
        log(f"[uocr] decoder up in {time.time() - t0:.0f} s, buckets {buckets}, KV {dec.max_seq}")
        if args.trace:
            t0 = time.time()
            dec.warmup()
            dec.capture()
            log(f"[uocr] warmup + decode traces in {time.time() - t0:.0f} s")
        for c, meta, st, ids, rows in cases:
            r = {}
            L = len(ids)
            gen = meta["gen_ids"]
            t1 = time.time()
            dec.prefill(rows, L, ids=ids)
            lg = dec.logits_host()
            r["prefill_s_eager_first"] = time.time() - t1
            full = st["logits16"].float()
            r["prefill_pcc"] = pcc(lg, full[0])
            r["prefill_top1"] = int(lg.argmax()) == int(full[0].argmax())
            log(f"[{c}] L {L}: prefill logits PCC {r['prefill_pcc']:.5f} top-1 {r['prefill_top1']} "
                f"({r['prefill_s_eager_first']:.1f} s first run)")
            # teacher forcing over the golden tokens
            n_tf = len(gen) if args.tf_steps <= 0 else min(args.tf_steps, len(gen))
            guard = PageGuard(ids)
            agree, tv, pc = [], [], []
            t1 = time.time()
            for s in range(n_tf):
                if s:
                    dec.step(gen[s - 1], L + s - 1)
                    lg = dec.logits_host()
                g = guard(lg.clone(), gen[:s])
                agree.append(int(g.argmax()) == gen[s])
                if s < full.shape[0]:
                    tv.append(tvd(lg, full[s]))
                    pc.append(pcc(lg, full[s]))
            dt = time.time() - t1
            r.update(tf_steps=n_tf, tf_top1=sum(agree) / max(1, n_tf), tf_first_miss=next(
                (i for i, a in enumerate(agree) if not a), None), tvd16_mean=sum(tv) / max(1, len(tv)),
                tvd16_max=max(tv) if tv else 0.0, pcc16_min=min(pc) if pc else 0.0,
                step_ms=1e3 * dt / max(1, n_tf - 1))
            log(f"[{c}] TF {n_tf} steps: top-1 {r['tf_top1']:.4f} (first miss {r['tf_first_miss']}), TVD(16) mean "
                f"{r['tvd16_mean']:.5f} max {r['tvd16_max']:.5f}, logits PCC(16) min {r['pcc16_min']:.5f}; "
                f"{r['step_ms']:.1f} ms / step (eager)")
            # greedy
            n_gen = len(gen) + 8 if args.gen < 0 else args.gen
            if n_gen > 0:
                dec.prefill(rows, L, ids=ids)
                lg = dec.logits_host()
                guard = PageGuard(ids)
                out = []
                t1 = time.time()
                for s in range(n_gen):
                    if s:
                        dec.step(out[-1], L + s - 1)
                        lg = dec.logits_host()
                    t = int(guard(lg.clone(), out).argmax())
                    out.append(t)
                    if t == 1:
                        break
                dt = time.time() - t1
                same = 0
                while same < min(len(out), len(gen)) and out[same] == gen[same]:
                    same += 1
                r.update(gen_tokens=len(out), gen_identical=out == gen, gen_prefix=same,
                         gen_tok_s=(len(out) - 1) / dt if dt > 0 else 0.0)
                log(f"[{c}] greedy {len(out)} tokens: identical {out == gen} (first {same} of {len(gen)}); "
                    f"{r['gen_tok_s']:.1f} tok/s")
            res["cases"][c] = r
    finally:
        os.makedirs(RUNS, exist_ok=True)
        json.dump(res, open(os.path.join(RUNS, f"dev_{args.tag}.json"), "w"), indent=1, default=str)
        close_device(dev)


if __name__ == "__main__":
    main()