embeddinggemma-2 / code /tt_embgemma /tests /test_host_server.py
changh95's picture
tt-model push embeddinggemma-2 (container)
5c33f00 verified
Raw History Blame Contribute Delete
12.2 kB
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the HTTP server with the fake device (no ttnn, no weights): routes, schemas, every modality's
input parsing, MRL dimensions, encodings, errors, batching."""
import base64
import io
import os
import struct
import numpy as np
import pytest
from tt_embgemma.tests.goldens import MODEL as MODEL_DIR # noqa: E402
pytestmark = pytest.mark.skipif(not (MODEL_DIR and os.path.isfile(os.path.join(MODEL_DIR, "tokenizer.json"))),
reason="tokenizer files not available (EMBGEMMA_WEIGHTS_DIR or the pinned HF snapshot)")
def _png(w=64, h=48, seed=0):
from PIL import Image
a = np.random.default_rng(seed).integers(0, 255, (h, w, 3), dtype=np.uint8)
b = io.BytesIO()
Image.fromarray(a).save(b, format="PNG")
return base64.b64encode(b.getvalue()).decode()
def _wav(sec=1.0, sr=16000, bits=16):
t = np.arange(int(sec * sr)) / sr
x = (0.3 * np.sin(2 * np.pi * 440 * t))
if bits == 16:
pcm = (x * 32767).astype("<i2").tobytes()
tag = 1
else:
pcm = x.astype("<f4").tobytes()
tag = 3
fmt = struct.pack("<HHIIHH", tag, 1, sr, sr * bits // 8, bits // 8, bits)
data = b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVE" + b"fmt " + struct.pack("<I", 16) + fmt + \
b"data" + struct.pack("<I", len(pcm)) + pcm
return base64.b64encode(data).decode()
@pytest.fixture()
def client(monkeypatch):
from fastapi.testclient import TestClient
from tt_embgemma.server.app import create_app
from tt_embgemma.server.fake_device import FakeModel
monkeypatch.setenv("EMBGEMMA_MAX_BATCH", "4")
monkeypatch.setenv("EMBGEMMA_MAX_INPUTS", "50")
monkeypatch.setenv("EMBGEMMA_MAX_IMAGES", "8")
monkeypatch.setenv("EMBGEMMA_MAX_SEQ_LEN", "2048")
monkeypatch.delenv("TT_MESH_SHAPE", raising=False)
holder = {}
def factory(cfg):
holder["m"] = FakeModel(MODEL_DIR, cfg)
return holder["m"]
app = create_app(model_factory=factory)
with TestClient(app) as c:
c.model = holder["m"]
yield c
def _expected(m, inputs, prompt="", **opts):
from tt_embgemma import pipeline as P
from tt_embgemma.api import parse_input
opt = m.options(**opts)
preps = [m.prepare(parse_input(x, prompt), opt) for x in inputs]
sums, n, _ = m.run(preps)
return P.finish(sums, n, opt.dimensions, opt.normalize), n
def test_health_info_models(client):
r = client.get("/health")
assert r.status_code == 200 and r.json()["status"] == "ok"
info = client.get("/info").json()
assert info["limits"]["max_batch"] == 4 and info["limits"]["dimensions"] == [768, 512, 256, 128]
assert info["prompts"]["SearchQuery"] == "task: search result | query: "
assert client.get("/v1/models").json()["data"][0]["id"] == "embeddinggemma-2"
assert "POST /embed" in client.get("/").json()["routes"]
def test_openai_float_base64_dimensions(client):
texts = ["hello world", "A man is playing a guitar.", "", "x " * 300, "x"]
r = client.post("/v1/embeddings", json={"input": texts, "model": "m1"})
assert r.status_code == 200, r.text
d = r.json()
assert d["object"] == "list" and d["model"] == "m1" and len(d["data"]) == 5
want, n = _expected(client.model, texts)
got = np.array([e["embedding"] for e in d["data"]], dtype=np.float32)
assert got.shape == (5, 768) and np.allclose(got, want, atol=1e-6)
assert np.allclose(np.linalg.norm(got, axis=1), 1.0, atol=1e-5)
assert d["usage"]["prompt_tokens"] == sum(n)
for dims in (512, 256, 128):
r = client.post("/v1/embeddings", json={"input": "hello world", "dimensions": dims,
"encoding_format": "base64"})
v = np.frombuffer(base64.b64decode(r.json()["data"][0]["embedding"]), dtype="<f4")
w, _ = _expected(client.model, ["hello world"], dimensions=dims)
assert v.shape == (dims,) and np.allclose(v, w[0], atol=1e-6) and abs(np.linalg.norm(v) - 1) < 1e-5
# MRL = prefix of the full embedding, re-normalized
full = np.array(client.post("/v1/embeddings", json={"input": "hello world"}).json()["data"][0]["embedding"])
assert np.allclose(full[:dims] / np.linalg.norm(full[:dims]), v, atol=1e-5)
def test_openai_prompt_name(client):
r1 = client.post("/v1/embeddings", json={"input": "northern lights", "prompt_name": "SearchQuery"}).json()
r2 = client.post("/v1/embeddings", json={"input": "task: search result | query: northern lights"}).json()
assert np.allclose(r1["data"][0]["embedding"], r2["data"][0]["embedding"], atol=1e-6)
assert r1["usage"]["prompt_tokens"] == r2["usage"]["prompt_tokens"]
r = client.post("/v1/embeddings", json={"input": "x", "prompt_name": "nope"})
assert r.status_code == 400 and "prompt_name" in r.json()["detail"]
def test_openai_errors(client):
assert client.post("/v1/embeddings", json={"input": [1, 2, 3]}).status_code == 400
assert client.post("/v1/embeddings", json={"input": []}).status_code == 400
assert client.post("/v1/embeddings", json={"input": {"a": 1}}).status_code == 400
r = client.post("/v1/embeddings", json={"input": "x", "dimensions": 300})
assert r.status_code == 400 and "dimensions" in r.json()["detail"]
r = client.post("/v1/embeddings", json={"input": ["a"] * 51})
assert r.status_code == 413
def test_embed_multimodal(client):
img = _png()
wav = _wav(1.0)
frames = [_png(seed=i) for i in range(3)]
inputs = [
"just text",
{"image": img},
{"text": "a picture: <|image|> done", "image": [img]},
{"audio": wav},
{"video": {"frames": frames, "fps": 1.0}},
{"content": [{"type": "text", "text": "mixed "}, {"type": "image", "image": img},
{"type": "audio", "audio": wav}]},
]
r = client.post("/embed", json={"inputs": inputs, "dimensions": 256})
assert r.status_code == 200, r.text
d = r.json()
assert d["dim"] == 256 and len(d["embeddings"]) == 6
got = np.array(d["embeddings"], dtype=np.float32)
assert np.allclose(np.linalg.norm(got, axis=1), 1.0, atol=1e-5)
n = d["n_tokens"]
# image (64x48 -> 1 x 1 x ... patches); audio 1 s = 25 tokens + boa/eoa; 3 frames of video
assert n[0] < 10 and n[3] == 2 + 25 + 2
assert (n[4] - 2) % 3 == 0 and 0 < (n[4] - 2) // 3 - 2 <= 140 # 3 frames x (<boi> m <eoi>), m <= 140
calls = [c[0] for c in client.model.engine.calls]
assert "vision" in calls and "audio" in calls and "text" in calls
def test_embed_tokens_output(client):
r = client.post("/embed", json={"inputs": ["hello world"], "output": "tokens"})
assert r.status_code == 200, r.text
d = r.json()
t = np.array(d["embeddings"][0], dtype=np.float32)
assert t.shape == (d["n_tokens"][0], 768)
def test_embed_truncation(client):
long = "word " * 3000
r = client.post("/embed", json={"inputs": [long], "max_length": 100})
assert r.status_code == 200, r.text
assert r.json()["n_tokens"] == [100] and r.json()["truncated"] == [True]
r = client.post("/embed", json={"inputs": [long], "max_length": 100, "truncate": "error"})
assert r.status_code == 400
def test_image_cap(client):
"""EMBGEMMA_MAX_IMAGES bounds the images + video frames of one request (host memory), 413 above."""
img = _png()
assert client.post("/embed", json={"inputs": [{"image": img}] * 8}).status_code == 200
r = client.post("/embed", json={"inputs": [{"image": img}] * 5 + [{"video": {"frames": [img] * 4, "fps": 1}}]})
assert r.status_code == 413 and "EMBGEMMA_MAX_IMAGES" in r.json()["detail"]
assert client.get("/info").json()["limits"]["max_images"] == 8
def test_transparent_png_composited_on_white(client):
"""An RGBA PNG through the server's decoder = the official RGB conversion (transparency onto white)."""
import base64
from PIL import Image
from tt_embgemma import media as MD
from tt_embgemma.preprocess.image import to_rgb_pil
a = np.zeros((40, 60, 4), np.uint8)
a[..., :3] = 7 # dark colors under a fully transparent background
a[10:30, 20:40] = (200, 30, 30, 255) # an opaque red square
b = io.BytesIO()
Image.fromarray(a, "RGBA").save(b, format="PNG")
im = np.asarray(MD.decode_image(b.getvalue()))
assert im.shape == (40, 60, 3) and (im[0, 0] == 255).all() and tuple(im[20, 30]) == (200, 30, 30)
assert np.array_equal(im, np.asarray(to_rgb_pil(Image.fromarray(a, "RGBA"))))
r = client.post("/embed", json={"inputs": [{"image": base64.b64encode(b.getvalue()).decode()}]})
assert r.status_code == 200
def test_embed_errors(client):
assert client.post("/embed", json={"inputs": [{"image": "not base64 !!"}]}).status_code == 400
assert client.post("/embed", json={"inputs": [{"bogus": 1}]}).status_code == 400
assert client.post("/embed", json={"inputs": ["x"], "image_tokens": 300}).status_code == 400
assert client.post("/embed", json={"inputs": ["x"], "image_tokens": 560}).status_code == 400 # > max 280
assert client.post("/embed", json={"inputs": [{"text": "<|image|>"}]}).status_code == 400
assert client.post("/embed", json={"inputs": ["x"], "nope": 1}).status_code == 422
def test_similarity(client):
r = client.post("/similarity", json={"source": "northern lights", "targets": ["aurora", "pizza"],
"prompt_name": "SearchQuery", "target_prompt_name": "Document"})
assert r.status_code == 200, r.text
s = r.json()["scores"]
assert len(s) == 2 and all(-1.0001 <= x <= 1.0001 for x in s)
def test_batching_splits(client):
texts = [f"text number {i}" for i in range(10)]
r = client.post("/v1/embeddings", json={"input": texts})
assert r.status_code == 200
calls = [c for c in client.model.engine.calls if c[0] == "text"]
assert max(c[1] for c in calls) <= 4
def test_device_opened_and_closed_off_the_device_thread(monkeypatch):
"""The default factory path: the chip is opened and closed on the lifespan's thread (the main thread under
uvicorn), the model is built on the device thread. UMD's per-chip lock must be released by the thread that took it,
and tt-metal releases it at exit on the main thread (a chip opened on the device thread aborts the process at exit
with ``CHIP_IN_USE``, all-MiniLM-L6-v2 r3)."""
import threading
from fastapi.testclient import TestClient
from tt_embgemma import device as D
from tt_embgemma.server import app as A
from tt_embgemma.server.fake_device import FakeModel
monkeypatch.setenv("EMBGEMMA_TEXT_ENGINE", "ttnn")
monkeypatch.delenv("TT_MESH_SHAPE", raising=False)
seen = {}
def fake_open(**kw):
seen["open"] = threading.get_ident()
return "chip"
def fake_close(dev):
seen["close"] = (threading.get_ident(), dev)
def fake_factory(cfg, device=None):
seen["build"] = (threading.get_ident(), device)
return FakeModel(MODEL_DIR, cfg)
monkeypatch.setattr(D, "open_device", fake_open)
monkeypatch.setattr(D, "close_device", fake_close)
monkeypatch.setattr(A, "default_model_factory", fake_factory)
app = A.create_app()
with TestClient(app) as c:
assert c.get("/health").json()["status"] == "ok"
assert c.post("/v1/embeddings", json={"input": "hello"}).status_code == 200
assert seen["build"][1] == "chip" and seen["close"][1] == "chip"
assert seen["open"] == seen["close"][0] # same thread opens and closes the chip
assert seen["build"][0] != seen["open"] # the model is built (and run) on the device thread
def test_model_does_not_close_a_borrowed_device():
"""close() of a model built on a device it did not open leaves the chip to its owner (the lifespan)."""
from tt_embgemma.api import EmbeddingGemma2
class Eng:
closed = False
def close(self):
Eng.closed = True
m = EmbeddingGemma2(None, None, None, Eng(), device="chip", owns_device=False)
m.close()
assert Eng.closed and m.device is None