# SPDX-License-Identifier: Apache-2.0 """Device check of the ttnn vision encoder vs the official fp32 goldens (stage PCCs), eager then traced + timing. bin/devrun -t 900 --reset-on-timeout -- python -u bundles/glm-ocr/code/tt_glmocr/tests/dev_vision.py \ --cases line_en,para_en [--buckets 256,1280] [--trace] [--reps 5] [--wdtype bf16] [--fidelity HiFi4] """ 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_glmocr import frontend as FE # noqa: E402 from tt_glmocr.reference import model as R # noqa: E402 from tt_glmocr.tests._paths import ASSETS, MODEL # 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("--cases", default="line_en,para_en") ap.add_argument("--buckets", default="") ap.add_argument("--trace", action="store_true") ap.add_argument("--stages", action="store_true") ap.add_argument("--reps", type=int, default=5) ap.add_argument("--wdtype", default="bf16") ap.add_argument("--merger-dtype", default="bf16") ap.add_argument("--fidelity", default="HiFi4") ap.add_argument("--chunk", type=int, default=256) ap.add_argument("--tag", default="") ap.add_argument("--res-bf16", action="store_true") ap.add_argument("--sdpa-fid", default="HiFi4") ap.add_argument("--kchunk", type=int, default=0) ap.add_argument("--exp-approx", action="store_true") ap.add_argument("--rope-mm", action="store_true") ap.add_argument("--approx-min", type=int, default=4096) ap.add_argument("--time-buckets", default="", help="extra buckets timed (traced) with full random images") args = ap.parse_args() import ttnn from tt_glmocr.ttaw.device import open_device, close_device from tt_glmocr.tt.ttnn_vision import TtnnVision, default_buckets entries = {e["name"]: e for e in json.load(open(os.path.join(ASSETS, "images.json")))} cases = [] for n in args.cases.split(","): img = FE.preprocess(os.path.join(ASSETS, entries[n]["file"])) cases.append((n, img)) if args.buckets: buckets = [int(b) for b in args.buckets.split(",")] else: allb = default_buckets() buckets = sorted({next(b for b in allb if b >= img.n_patches) for _, img in cases}) tb = [int(b) for b in args.time_buckets.split(",") if b] buckets = sorted(set(buckets) | set(tb)) t0 = time.time() W = R.Weights(MODEL, torch.bfloat16) print(f"weights {time.time() - t0:.1f}s; buckets {buckets}", flush=True) dev = open_device(0, dispatch="eth", trace_region_size=256 << 20) out = {"buckets": buckets, "wdtype": args.wdtype, "fidelity": args.fidelity, "cases": {}} try: t0 = time.time() V = TtnnVision(dev, W, buckets, wdtype=args.wdtype, fidelity=args.fidelity, merger_dtype=args.merger_dtype, sdpa_chunk=args.chunk, res_fp32=not args.res_bf16, sdpa_fidelity=args.sdpa_fid, sdpa_kchunk=args.kchunk, exp_approx=args.exp_approx, rope_op=not args.rope_mm, exp_approx_min=args.approx_min) print(f"upload {time.time() - t0:.1f}s", flush=True) for n, img in cases: st = torch.load(os.path.join(ASSETS, "golden", n, "stages_fp32.pt"), weights_only=True) stages = {} if args.stages else None t0 = time.time() y, ntok, Nb = V.run(img.patches, img.grid_h, img.grid_w, stages=stages) emb = ttnn.to_torch(y).float().reshape(-1, 1536)[:ntok] t1 = time.time() r = {"n_patches": img.n_patches, "Nb": Nb, "eager_s": round(t1 - t0, 2), "pcc_emb": round(pcc(emb, st["v_merger"]), 6), "maxabs_emb": round(float((emb - st["v_merger"]).abs().max()), 4)} if stages: for k, t in stages.items(): a = ttnn.to_torch(t).float() a = a.reshape(-1, a.shape[-1]) g = st[k] r["pcc_" + k] = round(pcc(a[:g.shape[0]], g), 6) out["cases"][n] = r print(n, json.dumps(r), flush=True) if args.trace: V.capture(buckets) for n, img in cases: st = torch.load(os.path.join(ASSETS, "golden", n, "stages_fp32.pt"), weights_only=True) ts = [] for _ in range(args.reps): t0 = time.perf_counter() y, ntok, Nb = V.run(img.patches, img.grid_h, img.grid_w) ttnn.synchronize_device(dev) ts.append(time.perf_counter() - t0) emb = ttnn.to_torch(y).float().reshape(-1, 1536)[:ntok] r = out["cases"][n] r["trace_pcc_emb"] = round(pcc(emb, st["v_merger"]), 6) r["trace_ms"] = round(1000 * min(ts), 2) r["trace_ms_med"] = round(1000 * sorted(ts)[len(ts) // 2], 2) print(n, "traced", json.dumps(r), flush=True) for Nb in tb: # full bucket: a random image of Nb patches (grid 2 x Nb/2 rows of merge blocks) gw = 64 if Nb % 128 == 0 else 2 gh = Nb // gw pt = (torch.rand(Nb, 588) * 2 - 1).numpy() ts = [] for _ in range(args.reps): t0 = time.perf_counter() V.run(pt, gh, gw, Nb=Nb) ttnn.synchronize_device(dev) ts.append(time.perf_counter() - t0) out.setdefault("time_buckets", {})[Nb] = round(1000 * min(ts), 2) print(f"bucket {Nb} patches ({Nb // 4} tokens) full: {1000 * min(ts):.2f} ms traced", flush=True) V.release() finally: close_device(dev) os.makedirs(os.path.join(ASSETS, "runs"), exist_ok=True) json.dump(out, open(os.path.join(ASSETS, "runs", f"vision{args.tag}.json"), "w"), indent=1) if __name__ == "__main__": main()