Files
alzeo/tests/test_pplx_server.py

136 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""The embeddings lane's server (pplx-server.py), its model replaced by one that answers at once: what it takes, what it refuses
and in which words, and the vectors a client may ask shorter. What it shares with the Clipstral lane's server is tested there
(test_clipstral_server.py); the model itself is proved on a box (install-embeddings.sh)."""
import base64
import http.client
import importlib.util
import json
import math
import pathlib
import struct
import threading
import unittest
REPO = pathlib.Path(__file__).resolve().parents[1]
_spec = importlib.util.spec_from_file_location("pplx_server", REPO / "pplx-server.py")
S = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(S)
import vectors_server as V # noqa: E402 (the module above puts the repository on the path)
class Words:
def encode(self, text):
return type("Enc", (), {"ids": list(range(3, 3 + len(text.split())))})()
class Fake(S.Pplx):
def __init__(self): # not its own: that one reads the model
self.tok, self.turns, self.longest, self.calls = Words(), V.Turns(), 9, []
def texts(self, ids, between=None):
self.calls.append([len(x) for x in ids])
return [[3.0, 4.0] + [0.0] * (S.DIM - 2) for _ in ids]
class WhatItComputes(unittest.TestCase):
def test_a_request_longer_than_ten_minutes_here_is_refused_before_it_is_computed(self):
"""37 texts of 8,024 tokens were taken: about 30 minutes on these cores, and the proxy gives a request 15 to begin its answer,
so its client got a 503 and asked again for nothing (review of v1.61.0, 2026-12-02). Its estimate is the lane's measures:
a text of 2,048 tokens 4.7 s, one of 8,024 49.2 s."""
e = Fake()
self.assertAlmostEqual(e.SECONDS_PER_TOKEN * 2048 + e.SECONDS_PER_SQUARE * 2048 ** 2, 4.7, delta=0.3)
self.assertAlmostEqual(e.SECONDS_PER_TOKEN * 8024 + e.SECONDS_PER_SQUARE * 8024 ** 2, 49.2, delta=1.5)
with self.assertRaises(V.Bad) as bad:
e.encode([("text", "word " * 8000)] * 37)
self.assertIn("would take about", str(bad.exception))
self.assertIn("send its inputs in several", str(bad.exception))
self.assertEqual(e.calls, [])
e.encode([("text", "word " * 8000)] * 9) # 7.5 min: taken
self.assertEqual(sum(len(c) for c in e.calls), 9)
e.encode([("text", "word " * 500)] * 600) # 300,000 tokens of short texts: 5 min, taken
self.assertLessEqual(V.BUDGET_S, 600)
class WhatARequestAsks(unittest.TestCase):
def test_a_text_of_spaces_is_a_text(self):
"""TEI took it in v1.60.0, and an indexing job's splitter may give a blank chunk: refused, it took its whole batch with it."""
self.assertEqual(S.inputs_of({"input": ["a", " \n", "\t"]}), [("text", "a"), ("text", " \n"), ("text", "\t")])
def test_a_text_or_a_list_of_them(self):
for given, want in (("a", ["a"]), (["a", "b"], ["a", "b"]), ([{"type": "text", "text": "a"}, " b "], ["a", " b "])):
self.assertEqual(S.inputs_of({"input": given}), [("text", x) for x in want])
def test_what_it_refuses_names_the_entry_and_why(self):
for given, words in ((None, "'input' must be"), ([], "not empty"), (3, "'input' must be"), ("", "input[0] is an empty text"),
(["a", ""], "input[1] is an empty text"), ([1, 2], "token ids"), (["a", [1]], "input[1]: token ids"),
([[1]], "check_embedding_ctx_length"), ([None], "input[0] must be a string"),
([{"type": "image_url", "image_url": "data:image/png;base64,AAAA"}], "reads texts alone"),
(["a"] * (V.MAX_INPUTS + 1), f"over {V.MAX_INPUTS}")):
with self.subTest(str(given)[:60]):
with self.assertRaises(V.Bad) as e:
S.inputs_of({"input": given} if given is not None else {})
self.assertIn(words, str(e.exception))
def test_the_vectors_it_makes_and_no_other(self):
for req, want in (({}, ("float", None)), ({"dimensions": 256}, ("float", 256)), ({"output_dimension": 1}, ("float", 1)),
({"dimensions": 1024, "encoding_format": "base64"}, ("base64", 1024)), ({"dimensions": None}, ("float", None))):
self.assertEqual(S.wants(req), want)
for bad in ({"dimensions": 0}, {"dimensions": 1025}, {"dimensions": True}, {"dimensions": "256"}, {"dimensions": 1.5},
{"output_dtype": "int8"}, {"encoding_format": "hex"}):
with self.subTest(bad), self.assertRaises(V.Bad):
S.wants(bad)
class OverHttp(unittest.TestCase):
def setUp(self):
self.was, V.log = V.log, lambda line: None
self.addCleanup(setattr, V, "log", self.was)
self.state = {"engine": Fake()}
self.srv = V.Server(("127.0.0.1", 0), V.make_handler(self.state, S.LANE))
threading.Thread(target=self.srv.serve_forever, daemon=True).start()
self.addCleanup(self.srv.server_close)
self.addCleanup(self.srv.shutdown)
def ask(self, body, path="/v1/embeddings", method="POST"):
c = http.client.HTTPConnection("127.0.0.1", self.srv.server_port, timeout=10)
self.addCleanup(c.close)
c.request(method, path, json.dumps(body) if body is not None else None, {"Content-Type": "application/json"})
r = c.getresponse()
return r.status, json.loads(r.read())
def test_openais_shape_under_its_own_name_whatever_the_client_calls_it(self):
for name in ("pplx-embed-v1-0.6b", "text-embedding-3-small", None):
status, d = self.ask({"model": name, "input": ["one two", "three"]})
self.assertEqual((status, d["object"], d["model"], d["usage"]), (200, "list", "pplx-embed-v1-0.6b", {"prompt_tokens": 3, "total_tokens": 3}))
self.assertEqual([(x["object"], x["index"], len(x["embedding"])) for x in d["data"]], [("embedding", 0, 1024), ("embedding", 1, 1024)])
def test_the_first_dimensions_are_of_norm_1_again(self):
_, d = self.ask({"input": "a", "dimensions": 1})
self.assertEqual(d["data"][0]["embedding"], [1.0])
_, d = self.ask({"input": "a", "dimensions": 8, "encoding_format": "base64"})
v = struct.unpack("<8f", base64.b64decode(d["data"][0]["embedding"]))
self.assertAlmostEqual(math.sqrt(sum(x * x for x in v)), 1.0, places=6)
self.assertEqual([round(x, 6) for x in v[:2]], [0.6, 0.8])
def test_a_request_it_refuses_is_a_400_that_says_why(self):
status, d = self.ask({"input": [1, 2, 3]})
self.assertEqual((status, d["error"]["type"]), (400, "invalid_request_error"))
self.assertIn("token ids", d["error"]["message"])
self.assertEqual(self.state["engine"].calls, [])
def test_its_health_and_its_name(self):
self.assertEqual(self.ask(None, "/health", "GET"), (200, {"status": "ok"}))
self.assertEqual(self.ask(None, "/v1/models", "GET")[1]["data"], [{"id": "pplx-embed-v1-0.6b", "object": "model", "owned_by": "perplexity-ai"}])
self.state.clear()
self.assertEqual(self.ask(None, "/health", "GET")[0], 503)
def test_a_text_too_long_is_refused_whole_never_cut(self):
status, d = self.ask({"input": ["word " * (V.MAX_TOKENS + 1)]})
self.assertEqual(status, 400)
self.assertIn(f"over {V.MAX_TOKENS}", d["error"]["message"])
if __name__ == "__main__":
unittest.main()