# SPDX-License-Identifier: Apache-2.0 """End-to-end device check of an engine (host preprocessing -> device encoders -> device text backbone -> host pooling / normalize) against the official fp32 goldens. ONE device process; exits non-zero at the first error. EMBGEMMA_GOLDEN= EMBGEMMA_GOLDEN_SRC= [EMBGEMMA_WEIGHTS_DIR=] \ bin/devrun -t 1200 --reset-on-timeout -- python -u code/tt_embgemma/tests/dev_e2e.py \ --parts text,retrieval,image,audio,video,mixed --out e2e.json """ from __future__ import annotations import argparse import json import os import sys import time HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(HERE, "..", ".."))) import numpy as np # noqa: E402 from tt_embgemma import model_spec as S # noqa: E402 from tt_embgemma import pipeline as P # noqa: E402 from tt_embgemma.tests.goldens import MODEL, cos, golden_available, golden_module, load, unit # noqa: E402 def golden_helpers(): """The research golden scripts (cases.py, gen_golden.py) from EMBGEMMA_GOLDEN_SRC.""" C, G = golden_module("cases"), golden_module("gen_golden") if C is None or G is None or not golden_available() or not MODEL: raise SystemExit("set EMBGEMMA_GOLDEN (golden outputs), EMBGEMMA_GOLDEN_SRC (research/embgemma/golden) and " "EMBGEMMA_WEIGHTS_DIR (or cache the pinned weights)") return C, G def items_for(part, C, G, tok): """-> list of (key, Item, Options, golden tag).""" out = [] if part in ("text", "retrieval"): tag = "text_fp32_hooks" if part == "text" else "retrieval_fp32" _, gm = load(tag) for c in gm["cases"]: pn = c["prompt_name"] out.append((c["key"], P.Item([("text", c["text"])], tok.prompts[pn] if pn else ""), P.Options(), tag)) elif part == "image": for key, path, mst, _cap in C.IMAGES: if mst > 280: continue out.append((key, P.Item([("image", G.load_image(path))]), P.Options(image_tokens=mst), "image_fp32_hooks")) elif part == "audio": g, gm = load("audio_fp32_hooks") for c in gm["cases"]: k = c["key"] out.append((k, P.Item([("audio", {"array": g[f"{k}.waveform"], "sampling_rate": 16000})]), P.Options(), "audio_fp32_hooks")) elif part == "video": g, gm = load("video_fp32_hooks") for c in gm["cases"]: k = c["key"] if k.startswith("cap_"): continue md = c["video_metadata"] out.append((k, P.Item([("video", {"frames": g[f"{k}.frames"], "fps": md["fps"], "duration": md["duration"]})]), P.Options(), "video_fp32_hooks")) elif part == "mixed": imgs = {k: p for k, p, m, _ in C.IMAGES} for key, text, ims, pn in C.MIXED: out.append((key, P.Item([("text", text)] + [("image", G.load_image(imgs[i])) for i in ims]), P.Options(), "mixed_fp32")) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--parts", default="text") ap.add_argument("--engine", default="ttnn") ap.add_argument("--trace", type=int, default=1) ap.add_argument("--max-seq", type=int, default=2048) ap.add_argument("--batch", type=int, default=0, help="also run each part as one batched call") ap.add_argument("--determinism", type=int, default=0, help="replays of the first case, bitwise compared") ap.add_argument("--out", default="e2e.json") ap.add_argument("--weights", default="bf16") ap.add_argument("--fidelity", default="HiFi4") ap.add_argument("--text-act", default="bf16") ap.add_argument("--text-buckets", default="32,64,128,256,512,1024,2048") ap.add_argument("--long-buckets", default="1024,2048") ap.add_argument("--vision-buckets", default="864,1440,2592") ap.add_argument("--audio-buckets", default="512,1024,2048,3072") args = ap.parse_args() parts = [p for p in args.parts.split(",") if p] C, G = golden_helpers() from tt_embgemma.device import close_device, describe_device, open_device from tt_embgemma.preprocess.text import Tokenizer from tt_embgemma.tt.engine import EngineConfig, TtnnEngine from tt_embgemma.weights import load_embed_table, load_state tok = Tokenizer(MODEL) table = P.EmbedTable(load_embed_table(MODEL)) comps = {"text"} mods = {"text"} for p in parts: if p in ("image", "video", "mixed"): comps.add("vision") mods.update({"image", "video"}) if p == "audio": comps.add("audio") mods.add("audio") W = load_state(MODEL, tuple(sorted(comps)), skip_embed=True) dev = open_device() res = {"args": vars(args), "device": describe_device(dev), "parts": {}} embs = {} eng = None try: ints = lambda v: tuple(int(x) for x in v.split(",") if x) # noqa: E731 cfg = EngineConfig(modalities=tuple(sorted(mods)), trace=bool(args.trace), weights=args.weights, fidelity=args.fidelity, text_act=args.text_act, text_buckets=ints(args.text_buckets), long_buckets=ints(args.long_buckets), vision_buckets=ints(args.vision_buckets), audio_buckets=ints(args.audio_buckets)) eng = TtnnEngine(dev, W, cfg) if args.trace: eng.warmup() print("engine", cfg.stats, flush=True) for part in parts: its = items_for(part, C, G, tok) pr = {} gold = {} for key, item, opt, tag in its: if tag not in gold: gold[tag] = load(tag)[0] g = gold[tag] t1 = time.time() emb, n, _t, preps = P.embed_items(eng, tok, table, [item], opt) dt = time.time() - t1 ids_ok = preps[0].seq.ids == g[f"{key}.ids"].tolist() embs[f"{part}:{key}"] = emb[0].copy() c = cos(emb[0], g[f"{key}.emb"]) pr[key] = {"n": n[0], "cos": c, "ids": ids_ok, "s": round(dt, 3)} print(part, key, n[0], f"cos {c:.6f}", "ids" if ids_ok else "IDS-DIFF", f"{dt * 1e3:.1f} ms", flush=True) if args.batch and len(its) > 1: same_opt = all(o == its[0][2] for _, _, o, _ in its) if same_opt: emb, n, _t, _p = P.embed_items(eng, tok, table, [it for _, it, _, _ in its], its[0][2]) cb = [cos(emb[j], gold[its[j][3]][f"{its[j][0]}.emb"]) for j in range(len(its))] # G4: the same input alone vs inside the packed batch (device vs device) alone = {} for j, (key, item, opt, tag) in enumerate(its): e1, _, _, _ = P.embed_items(eng, tok, table, [item], opt) alone[key] = cos(e1[0], emb[j]) res.setdefault("batch", {})[part] = {"min_cos_vs_golden": min(cb), "min_cos_batch_vs_alone": min(alone.values())} print(part, "BATCHED", len(its), f"min cos {min(cb):.6f}", f"batch-vs-alone min cos {min(alone.values()):.7f}", flush=True) if args.determinism and its: key, item, opt, tag = its[0] e0, _, _, _ = P.embed_items(eng, tok, table, [item], opt) same = 0 for _ in range(args.determinism): e1, _, _, _ = P.embed_items(eng, tok, table, [item], opt) same += int(np.array_equal(e0, e1)) res.setdefault("determinism", {})[part] = {"replays": args.determinism, "bitwise_equal": same} print(part, "DETERMINISM", f"{same}/{args.determinism} bitwise identical", flush=True) cs = [v["cos"] for v in pr.values()] res["parts"][part] = {"cases": pr, "min_cos": min(cs), "mean_1mcos": float(np.mean([1 - c for c in cs]))} print("PART", part, len(cs), f"min cos {min(cs):.6f}", f"mean 1-cos {np.mean([1 - c for c in cs]):.2e}", flush=True) res["engine"] = eng.describe() finally: if eng is not None: eng.close() close_device(dev) json.dump(res, open(args.out, "w"), indent=1) np.savez(args.out[:-5] + "_emb.npz", **{k.replace(":", "__"): v for k, v in embs.items()}) print("DONE", flush=True) if __name__ == "__main__": main()