File size: 8,703 Bytes
5c33f00 | 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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | # 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=<golden outputs> EMBGEMMA_GOLDEN_SRC=<research/embgemma/golden> [EMBGEMMA_WEIGHTS_DIR=<snapshot>] \
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()
|