File size: 11,683 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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Smoke test of a running EmbeddingGemma 2 server (standard library only: runs with the host's python3).
python3 smoke_test.py --url http://127.0.0.1:20000 [--wait 1200] [--manifest <staged>/tt_kernel_manifest.json]
[--profile NAME] [--out smoke.json]
Checks (each failure is listed; exit 0 = PASS):
- readiness (/health), /info: ETH dispatch, 12x10 grid, the pinned configuration of the package (manifest serve env);
- /v1/embeddings on the shipped texts with their task prompts (samples/smoke_reference.json, official
sentence-transformers float32 outputs; one is 599 tokens = the sliding-window path): cosine >= MIN_COS_TEXT, unit
norm; base64 = float; MRL 256 = the re-normalized prefix of the 768-d vector;
- /embed on the shipped images (checker.png; transparent.png, RGBA composited onto white) and speech clip
(speech_16k.wav): cosine >= MIN_COS_MEDIA; audio vs its transcript is more similar than vs an unrelated text;
- batching: the texts inside one request vs alone, 8 concurrent requests: cosine >= MIN_COS_BATCH (G4: the official
bf16 batch-vs-alone drift 1.2e-4, x 2);
- refusals: dimensions 300, token-id input, unknown field, media in text-only fields.
"""
from __future__ import annotations
import argparse
import base64
import concurrent.futures
import json
import math
import struct
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import client as C # noqa: E402
MODEL = "embeddinggemma-2"
MIN_COS_TEXT = 0.9997
MIN_COS_MEDIA = 0.999
MIN_COS_BATCH = 0.99976 # G4: 1 - 2 x (1 - 0.99988), the official bf16 batch-vs-alone cosine
def _load_ttaw(name):
import importlib.util
p = HERE.parent / "ttaw" / "server" / f"{name}.py"
spec = importlib.util.spec_from_file_location(f"embgemma_ttaw_{name}", p)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def wait_ready(url: str, wait_s: float):
t0 = time.time()
last = None
while True:
try:
h = C.get_json(url + "/health")
last = h
if h.get("status") in ("ok", "error"):
return h
except Exception as e: # noqa: BLE001
last = {"status": f"unreachable: {e}"}
if time.time() - t0 > wait_s:
return last
time.sleep(5)
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://127.0.0.1:20000")
ap.add_argument("--wait", type=float, default=1200)
ap.add_argument("--manifest", default=None)
ap.add_argument("--profile", default=None)
ap.add_argument("--out", default=None)
a = ap.parse_args()
url = a.url.rstrip("/")
fails = []
metrics = {}
h = wait_ready(url, a.wait)
if h.get("status") != "ok":
print(f"SMOKE FAIL {MODEL}: not ready: {h}")
return 1
info = C.get_json(url + "/info")
dev = info.get("device", {})
if dev.get("dispatch") != "eth" or dev.get("grid") != "12x10":
fails.append(f"device {dev.get('dispatch')} {dev.get('grid')} (expected eth 12x10)")
cfg = info.get("config", {})
if a.manifest:
pins = _load_ttaw("smoke").pinned_config(a.manifest, a.profile)
env = pins.get("env", {})
for k, field, conv in (("EMBGEMMA_MAX_BATCH", "max_batch", int), ("EMBGEMMA_MAX_SEQ_LEN", "max_seq_len", int),
("EMBGEMMA_IMAGE_TOKENS_MAX", "image_tokens_max", int),
("EMBGEMMA_DISPATCH", "dispatch", str), ("EMBGEMMA_FIDELITY", "fidelity", str),
("EMBGEMMA_TEXT_ENGINE", "text_engine", str), ("EMBGEMMA_MAX_IMAGES", "max_images", int)):
if k in env and conv(env[k]) != cfg.get(field):
fails.append(f"/info config {field}={cfg.get(field)!r}, package pins {k}={env[k]!r}")
if "EMBGEMMA_MODALITIES" in env and env["EMBGEMMA_MODALITIES"].split(",") != cfg.get("modalities"):
fails.append(f"/info modalities {cfg.get('modalities')} != pinned {env['EMBGEMMA_MODALITIES']}")
rev = (pins.get("weights") or {}).get("revision")
wdir = str(info.get("model_info", {}).get("model_dir", ""))
if rev and rev not in wdir:
fails.append(f"weights dir {wdir!r} is not the pinned revision {rev}")
metrics["weights_dir"] = wdir
ref = json.loads((HERE.parent / "samples" / "smoke_reference.json").read_text())
mods = cfg.get("modalities", ["text", "image", "video", "audio"])
# ---- text: one request per prompt name (OpenAI route), compared with the official outputs
got = {}
t0 = time.perf_counter()
for t, want in zip(ref["texts"], ref["text_embeddings"]):
code, body = C.post(url + "/v1/embeddings", {"input": t["text"], "prompt_name": t["prompt_name"]}
if t["prompt_name"] else {"input": t["text"]})
if code != 200:
fails.append(f"/v1/embeddings {t['key']}: HTTP {code} {body}")
continue
e = body["data"][0]["embedding"]
got[t["key"]] = e
c = C.cosine(e, want)
metrics.setdefault("text_cos", {})[t["key"]] = round(c, 7)
if c < MIN_COS_TEXT:
fails.append(f"{t['key']}: cosine vs official {c:.6f} < {MIN_COS_TEXT}")
if body["usage"]["prompt_tokens"] != t["n_tokens"]:
fails.append(f"{t['key']}: usage {body['usage']} != {t['n_tokens']} tokens")
if abs(math.sqrt(sum(v * v for v in e)) - 1) > 1e-3:
fails.append(f"{t['key']}: not unit norm")
metrics["texts_ms"] = round(1e3 * (time.perf_counter() - t0), 1)
t = ref["texts"][0]
code, body = C.post(url + "/v1/embeddings", {"input": t["text"], "prompt_name": t["prompt_name"],
"dimensions": 256, "encoding_format": "base64"})
if code == 200 and t["key"] in got:
raw = base64.b64decode(body["data"][0]["embedding"])
v = struct.unpack(f"<{len(raw) // 4}f", raw)
full = got[t["key"]][:256]
n = math.sqrt(sum(x * x for x in full))
if len(v) != 256 or max(abs(x - y / n) for x, y in zip(v, full)) > 1e-5:
fails.append("MRL 256 (base64) is not the re-normalized prefix of the 768-d embedding")
else:
fails.append(f"MRL request HTTP {code}")
# ---- media
if "image" in mods:
img = base64.b64encode((HERE.parent / "samples" / ref["image"]["file"]).read_bytes()).decode()
t0 = time.perf_counter()
code, body = C.post(url + "/embed", {"inputs": [{"image": img}]})
metrics["image_ms"] = round(1e3 * (time.perf_counter() - t0), 1)
if code != 200:
fails.append(f"/embed image: HTTP {code} {body}")
else:
c = C.cosine(body["embeddings"][0], ref["image"]["embedding"])
metrics["image_cos"] = round(c, 7)
if c < MIN_COS_MEDIA or body["n_tokens"][0] != ref["image"]["n_tokens"]:
fails.append(f"image: cosine {c:.6f} (>= {MIN_COS_MEDIA}), tokens {body['n_tokens']} "
f"(want {ref['image']['n_tokens']})")
if "image" in mods and "image_transparent" in ref: # RGBA PNG: transparency composited onto white (official)
rt = ref["image_transparent"]
img = base64.b64encode((HERE.parent / "samples" / rt["file"]).read_bytes()).decode()
code, body = C.post(url + "/embed", {"inputs": [{"image": img}]})
if code != 200:
fails.append(f"/embed transparent image: HTTP {code} {body}")
else:
c = C.cosine(body["embeddings"][0], rt["embedding"])
metrics["image_transparent_cos"] = round(c, 7)
if c < MIN_COS_MEDIA or body["n_tokens"][0] != rt["n_tokens"]:
fails.append(f"transparent image: cosine {c:.6f} (>= {MIN_COS_MEDIA}), tokens {body['n_tokens']} "
f"(want {rt['n_tokens']})")
if "audio" in mods:
wav = base64.b64encode((HERE.parent / "samples" / ref["audio"]["file"]).read_bytes()).decode()
t0 = time.perf_counter()
code, body = C.post(url + "/embed", {"inputs": [{"audio": wav}]})
metrics["audio_ms"] = round(1e3 * (time.perf_counter() - t0), 1)
if code != 200:
fails.append(f"/embed audio: HTTP {code} {body}")
else:
ea = body["embeddings"][0]
c = C.cosine(ea, ref["audio"]["embedding"])
metrics["audio_cos"] = round(c, 7)
if c < MIN_COS_MEDIA or body["n_tokens"][0] != ref["audio"]["n_tokens"]:
fails.append(f"audio: cosine {c:.6f} (>= {MIN_COS_MEDIA}), tokens {body['n_tokens']}")
code, body = C.post(url + "/v1/embeddings", {"input": [ref["audio"]["transcript"], "A recipe for pancakes."],
"prompt_name": "SearchQuery"})
if code == 200:
s = [C.cosine(ea, d["embedding"]) for d in body["data"]]
metrics["audio_vs_text"] = [round(x, 4) for x in s]
if not s[0] > s[1]:
fails.append(f"audio closer to the unrelated text than to its transcript: {s}")
# ---- batching / concurrency: all texts in one request vs alone
allin = [t["text"] for t in ref["texts"]]
code, body = C.post(url + "/v1/embeddings", {"input": allin})
alone = [C.embed(url, [x])[0] for x in allin]
if code == 200:
b = [d["embedding"] for d in sorted(body["data"], key=lambda d: d["index"])]
bc = min(C.cosine(x, y) for x, y in zip(b, alone))
metrics["batch_vs_alone_min_cos"] = round(bc, 7)
if bc < MIN_COS_BATCH:
fails.append(f"in-batch vs alone cosine {bc}")
with concurrent.futures.ThreadPoolExecutor(8) as ex:
res = list(ex.map(lambda x: C.embed(url, [x])[0], allin))
cc = min(C.cosine(x, y) for x, y in zip(res, alone))
metrics["concurrent_min_cos"] = round(cc, 7)
if cc < MIN_COS_BATCH:
fails.append(f"concurrent vs alone cosine {cc}")
lat = []
for i in range(20):
t0 = time.perf_counter()
C.post(url + "/v1/embeddings", {"input": ref["texts"][0]["text"], "prompt_name": "SearchQuery"})
lat.append(1e3 * (time.perf_counter() - t0))
lat.sort()
metrics["query_ms_p50"] = round(lat[len(lat) // 2], 2)
# ---- refusals
for payload, route, want_code in (({"input": "a", "dimensions": 300}, "/v1/embeddings", 400),
({"input": [101, 102]}, "/v1/embeddings", 400),
({"input": []}, "/v1/embeddings", 400),
({"inputs": ["a"], "bogus": 1}, "/embed", 422),
({"inputs": [{"image": "%%%"}]}, "/embed", 400),
({"inputs": ["a"], "prompt_name": "NoSuchTask"}, "/embed", 400)):
code, _ = C.post(url + route, payload)
if code != want_code:
fails.append(f"{route} {str(payload)[:60]}: HTTP {code}, expected {want_code}")
if a.out:
Path(a.out).write_text(json.dumps({"metrics": metrics, "failures": fails, "info": info}, indent=1))
tc = metrics.get("text_cos", {}).values()
summary = f"text_cos_min={min(tc) if tc else None} image={metrics.get('image_cos')} audio={metrics.get('audio_cos')}"
print(json.dumps(metrics))
print(("SMOKE PASS" if not fails else "SMOKE FAIL") + f" {MODEL}: {summary}" + ("" if not fails else f" {fails}"))
return 0 if not fails else 1
if __name__ == "__main__":
sys.exit(main())
|