File size: 4,636 Bytes
b8b3105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Device check of the ttnn DeepEncoder (SAM + CLIP + projector) against the official fp32 goldens (per view).

    bin/devrun -t 900 -- python -u common/dsocr/tt_dsocr/tests/dev_vision.py --cases formula_quad__tiny [--trace]

Per case and view (global; tiles): PCC of the SAM neck output, the CLIP output (patch rows) and the projected
features vs the golden; eager / traced ms. Results -> assets/dsocr/runs/vis_<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.reference import model as R  # 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 main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--variant", default="deepseek-ocr")
    ap.add_argument("--cases", default="formula_quad__tiny")
    ap.add_argument("--trace", action="store_true")
    ap.add_argument("--wdtype", default="bf16")
    ap.add_argument("--fidelity", default="HiFi4")
    ap.add_argument("--stages", action="store_true", help="also compare every SAM block (host reference)")
    ap.add_argument("--tag", default="")
    ap.add_argument("--clip-fp32", action="store_true", help="CLIP attention as fp32 matmuls + softmax")
    args = ap.parse_args()
    import ttnn
    from tt_dsocr.ttaw.device import open_device, close_device
    from tt_dsocr.tt.ttnn_vision import TtnnDeepEncoder

    gdir = GOLDEN[args.variant]
    jobs = []  # (case, view tag, px, golden sam, golden clip, golden proj)
    for c in args.cases.split(","):
        gt = torch.load(os.path.join(gdir, c, "tensors.pt"), weights_only=True)
        views = []
        if gt["images_crop"] is not None:
            views.append(("tiles", gt["images_crop"]))
        views.append(("global", gt["images_ori"]))
        for j, (tag, px) in enumerate(views):
            jobs.append((c, tag, px, gt["sam"][j], gt["vis"][j], gt["proj"][j]))
    keys = sorted({(int(px.shape[-1]), int(px.shape[0])) for _, _, px, _, _, _ in jobs})
    W = R.Weights(MODELS[args.variant])
    log = lambda s: print(s, flush=True)  # noqa: E731
    dev = open_device(0, dispatch="eth", trace_region_size=512 << 20, l1_small_size=1 << 15)
    res = {"args": vars(args), "cases": []}
    try:
        t0 = time.time()
        enc = TtnnDeepEncoder(dev, W, keys, wdtype=args.wdtype, fidelity=args.fidelity, log=log,
                              variant=args.variant, clip_attn_fp32=args.clip_fp32)
        log(f"[dev_vision] encoder up in {time.time() - t0:.0f} s, views {keys}")
        for c, tag, px, gsam, gclip, gproj in jobs:
            stages = {}
            t0 = time.time()
            out = enc.run(px, stages=stages)
            ttnn.synchronize_device(dev)
            te = time.time() - t0
            B, S = px.shape[0], px.shape[-1]
            v = enc.views[(S, B)].v
            cs = enc.c_out
            sam = ttnn.to_torch(stages["sam_out"]).float().reshape(B, v.gs, v.gs, cs).permute(0, 3, 1, 2)
            if enc.v2:
                pc = float("nan")
            else:
                clip = ttnn.to_torch(stages["clip_out"]).float().reshape(B, v.Sc, 1024)[:, :v.n]
                pc = pcc(clip, gclip[:, 1:])
            r = {"case": c, "view": tag, "S": S, "B": B, "eager_s": te, "pcc_sam": pcc(sam, gsam),
                 "pcc_clip": pc, "pcc_proj": pcc(out, gproj)}
            if args.trace:
                key = (S, B)
                if key not in enc.traces:
                    enc.capture([key])
                ts = []
                for _ in range(3):
                    t0 = time.time()
                    enc.run(px)
                    ttnn.synchronize_device(dev)
                    ts.append(time.time() - t0)
                r["traced_ms"] = 1e3 * min(ts)
                out2 = enc.run(px)
                r["pcc_proj_traced"] = pcc(out2, gproj)
            log(f"[{c} {tag} {S}x{B}] PCC sam {r['pcc_sam']:.5f} clip {r['pcc_clip']:.5f} proj {r['pcc_proj']:.5f}; "
                f"eager {te:.2f} s" + (f", traced {r['traced_ms']:.1f} ms" if args.trace else ""))
            res["cases"].append(r)
    finally:
        os.makedirs(RUNS, exist_ok=True)
        json.dump(res, open(os.path.join(RUNS, f"vis_{args.tag or 'run'}.json"), "w"), indent=1)
        close_device(dev)


if __name__ == "__main__":
    main()