File size: 6,238 Bytes
aa204f5 | 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 | # 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()
|