Download code/tt_minilm/tests/test_host_server.py from changh95/all-MiniLM-L6-v2: direct link, hf CLI and curl.
- Browser
- Download file 7.32 kB
-
https://huggingface.co/changh95/all-MiniLM-L6-v2/resolve/main/code/tt_minilm/tests/test_host_server.py
- Command line
-
hf download hf://changh95/all-MiniLM-L6-v2/code/tt_minilm/tests/test_host_server.py
-
curl -L -o test_host_server.py https://huggingface.co/changh95/all-MiniLM-L6-v2/resolve/main/code/tt_minilm/tests/test_host_server.py
7.32 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Host tests of the HTTP server with the fake device (no ttnn): routes, schemas, encodings, errors, batching.""" | |
| import base64 | |
| import concurrent.futures | |
| import os | |
| import numpy as np | |
| import pytest | |
| from tt_minilm.tests.gates import model_dir # noqa: E402 | |
| MODEL_DIR = model_dir() | |
| pytestmark = pytest.mark.skipif(not os.path.isfile(os.path.join(MODEL_DIR, "tokenizer.json")), | |
| reason="tokenizer files not available") | |
| def client(monkeypatch): | |
| from fastapi.testclient import TestClient | |
| from tt_minilm.server.app import create_app | |
| from tt_minilm.server.fake_device import FakeModel | |
| monkeypatch.setenv("MINILM_MAX_BATCH", "4") | |
| monkeypatch.setenv("MINILM_MAX_INPUTS", "50") | |
| 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 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"]["dim"] == 384 and info["limits"]["max_batch"] == 4 | |
| assert client.get("/v1/models").json()["data"][0]["id"] == "all-MiniLM-L6-v2" | |
| assert "POST /v1/embeddings" in client.get("/").json()["routes"] | |
| def test_openai_float_and_base64(client): | |
| texts = ["hello world", "A man is playing a guitar.", "", "x " * 300] | |
| 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"]) == 4 | |
| ids = client.model.tokenize(texts) | |
| want = client.model.expected(ids) | |
| got = np.array([e["embedding"] for e in d["data"]], dtype=np.float32) | |
| assert 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(len(x) for x in ids) | |
| r = client.post("/v1/embeddings", json={"input": "hello world", "encoding_format": "base64"}) | |
| v = np.frombuffer(base64.b64decode(r.json()["data"][0]["embedding"]), dtype="<f4") | |
| assert v.shape == (384,) and np.allclose(v, want[0], atol=1e-6) | |
| 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", "dimensions": 128}).status_code == 400 | |
| assert client.post("/v1/embeddings", json={"input": "a", "dimensions": 384}).status_code == 200 | |
| assert client.post("/v1/embeddings", json={"input": ["a"] * 51}).status_code == 413 | |
| assert client.post("/v1/embeddings", json={"input": "a", "encoding_format": "int8"}).status_code == 422 | |
| def test_native_embed_options(client): | |
| texts = ["The quick brown fox", "jumps over the lazy dog today"] | |
| ids = client.model.tokenize(texts) | |
| for pooling in ("mean", "cls", "max"): | |
| for norm in (True, False): | |
| r = client.post("/embed", json={"texts": texts, "pooling": pooling, "normalize": norm}) | |
| assert r.status_code == 200, r.text | |
| got = np.array(r.json()["embeddings"], dtype=np.float32) | |
| want = client.model.expected(ids, pooling, norm) | |
| assert np.allclose(got, want, atol=1e-5), (pooling, norm) | |
| r = client.post("/embed", json={"texts": texts, "pooling": "none", "normalize": False}) | |
| toks = r.json()["embeddings"] | |
| assert [len(t) for t in toks] == [len(x) for x in ids] | |
| assert r.json()["n_tokens"] == [len(x) for x in ids] | |
| def test_native_truncation(client): | |
| long = "word " * 400 | |
| r = client.post("/embed", json={"texts": long}) | |
| assert r.status_code == 200 and r.json()["n_tokens"] == [256] | |
| r = client.post("/embed", json={"texts": long, "max_length": 16, "truncate": "left"}) | |
| assert r.json()["n_tokens"] == [16] | |
| assert client.post("/embed", json={"texts": long, "truncate": "error"}).status_code == 400 | |
| assert client.post("/embed", json={"texts": "a", "max_length": 1}).status_code == 400 | |
| assert client.post("/embed", json={"texts": "a", "max_length": 300}).status_code == 400 | |
| assert client.post("/embed", json={"texts": "a", "bogus": 1}).status_code == 422 | |
| def test_similarity(client): | |
| r = client.post("/similarity", json={"source": "a cat", "targets": ["a cat", "a dog"]}) | |
| s = r.json()["scores"] | |
| assert len(s) == 2 and abs(s[0] - 1.0) < 1e-5 | |
| def test_batching_splits_and_merges(client): | |
| eng = client.model.engine | |
| eng.calls.clear() | |
| r = client.post("/v1/embeddings", json={"input": [f"text {i}" for i in range(10)]}) | |
| assert r.status_code == 200 | |
| assert max(eng.calls) <= 4 and sum(eng.calls) == 10 | |
| eng.calls.clear() | |
| with concurrent.futures.ThreadPoolExecutor(8) as ex: | |
| futs = [ex.submit(client.post, "/v1/embeddings", json={"input": f"sentence number {i}"}) for i in range(16)] | |
| rs = [f.result() for f in futs] | |
| assert all(r.status_code == 200 for r in rs) | |
| assert sum(eng.calls) == 16 and max(eng.calls) <= 4 | |
| for i, r in enumerate(rs): | |
| ids = client.model.tokenize([f"sentence number {i}"]) | |
| assert np.allclose(r.json()["data"][0]["embedding"], client.model.expected(ids)[0], atol=1e-6) | |
| def test_mesh_shape_refused(monkeypatch): | |
| from tt_minilm.server.app import load_config | |
| monkeypatch.setenv("TT_MESH_SHAPE", "1x2") | |
| with pytest.raises(RuntimeError): | |
| load_config() | |
| 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.""" | |
| import threading | |
| from fastapi.testclient import TestClient | |
| from tt_minilm import device as D | |
| from tt_minilm.server import app as A | |
| from tt_minilm.server.fake_device import FakeModel | |
| monkeypatch.setenv("MINILM_ENGINE", "mk") | |
| 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 | |