File size: 12,176 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# 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