Nekochu's picture
LookAnything LA-2B one-pass heads as 8-bit ONNX for WebGPU
6e303cd verified
Raw History Blame Contribute Delete
3.67 kB
"""Run the exported parts on ORT CPU for the reference photos and compare with the PyTorch reference.
usage: verify_look.py MODEL_DIR [IMAGE_NAME ...] (MODEL_DIR holds vis_a/vis_a.onnx ... heads/heads.onnx)"""
import gc
import glob
import json
import os
import sys
import time
import numpy as np
import onnxruntime as ort
SP = os.environ.get("LOOK_DIR", ".") # holds src/ (the code repo), ckpt/LA-2B (the checkpoint), ref/ (reference outputs)
sys.path.insert(0, f"{SP}/work")
import tables as T # noqa: E402
root = sys.argv[1]
only = set(sys.argv[2:])
ref = json.load(open(f"{SP}/ref/results.json"))
data = {os.path.basename(f)[:-4]: np.load(f) for f in sorted(glob.glob(f"{SP}/ref/*.npz")) if not only or os.path.basename(f)[:-4] in only}
IMG_ID = 151655
so = ort.SessionOptions(); so.log_severity_level = 3; so.intra_op_num_threads = 4
sess = lambda p: ort.InferenceSession(f"{root}/{p}/{p}.onnx", so, providers=["CPUExecutionProvider"])
st = {}
for k, z in data.items():
ids = z["input_ids"][0]; first = int(np.where(ids == IMG_ID)[0][0]); n = int((ids == IMG_ID).sum())
gh, gw = int(z["grid"][0, 1]), int(z["grid"][0, 2]); S = z["inputs_embeds"].shape[1]; P = int(z["prompt_len"])
idx, wt, vc, vs = T.vision_tables(gh, gw)
pos = T.positions(first, gh // 2, gw // 2, S - first - n); tc, ts = T.text_tables(pos)
st[k] = dict(first=first, n=n, gh=gh, gw=gw, S=S, P=P, idx=idx, wt=wt, vc=vc, vs=vs, tc=tc, ts=ts, mask=T.mask(P, total=S))
t0 = time.time()
s = sess("vis_a")
for k, z in data.items():
d = st[k]; d["x"], d["d0"], d["d1"] = s.run(None, {"patches": z["pixel_values"], "pos_idx": d["idx"], "pos_w": d["wt"], "cos": d["vc"], "sin": d["vs"]})
s = sess("vis_b")
for k in data:
d = st[k]; d["img"], d["d2"] = s.run(None, {"x": d["x"], "cos": d["vc"], "sin": d["vs"]})
print(f"vision {time.time()-t0:.0f}s", flush=True)
for k, z in data.items():
d = st[k]; h = z["inputs_embeds"].copy(); h[0, d["first"]:d["first"] + d["n"]] = d["img"]
ds = np.zeros((3, d["S"], 2048), np.float32)
for i, t in enumerate((d["d0"], d["d1"], d["d2"])): ds[i, d["first"]:d["first"] + d["n"]] = t
d["h"], d["ds"] = h, ds
for p in ("lm_1", "lm_2", "lm_3", "lm_4"):
s = sess(p)
for k in data:
d = st[k]; feed = {"hidden": d["h"], "cos": d["tc"], "sin": d["ts"], "mask": d["mask"]}
if p == "lm_1": feed["ds"] = d["ds"]
d["h"] = s.run(None, feed)[0]
print(f"{p} {time.time()-t0:.0f}s", flush=True)
del s; gc.collect()
s = sess("heads")
rows = []
for k, z in data.items():
d = st[k]; q = d["h"][:, d["P"]:d["P"] + 27]
vis = np.ascontiguousarray(d["h"][:, d["first"]:d["first"] + d["n"]].reshape(1, d["gh"] // 2, d["gw"] // 2, 2048))
point, box, hm, hmask = s.run(None, {"gaze": np.ascontiguousarray(q[:, 18:27]), "head": np.ascontiguousarray(q[:, 9:18]), "vis": vis})
r = ref[k]
am = np.unravel_index(hm[0, 0].argmax(), hm[0, 0].shape)
pd = np.abs(point[0] - np.array(r["point"])).max(); bd = np.abs(box[0] - np.array(r["box"])).max()
hd = float(np.abs(hm[0, 0] - z["heatmap"]).max()); hrel = hd / float(np.abs(z["heatmap"]).max())
hid = float(np.abs(d["h"][0] - z["hidden"][0]).max())
rows.append((k, pd, bd, hrel))
print(f"{k:14s} point {np.round(point[0], 3).tolist()} ref {np.round(r['point'], 3).tolist()} (d {pd:.4f}) | box d {bd:.4f} | heatmap argmax {am[1]/64:.3f},{am[0]/64:.3f} "
f"ref {r['heatmap_argmax'][0]:.3f},{r['heatmap_argmax'][1]:.3f} rel err {hrel:.3f} | hidden max diff {hid:.3f}", flush=True)
print("worst point diff %.4f, box %.4f, heatmap rel %.3f" % (max(r[1] for r in rows), max(r[2] for r in rows), max(r[3] for r in rows)))