# 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(" 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 ( m ), 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