Files
alzeo/pplx-server.py

81 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""The embeddings lane's server: Perplexity's pplx-embed v1 0.6B on the CPU, POST /v1/embeddings on loopback.
Texts, in 1,024 dimensions or the first of them (`dimensions`: the model is trained for it), each vector of norm 1. The request
is OpenAI's: `input` is a string or a list of them. Token ids are refused: a client's tokenizer is another model's.
python3 -I pplx-server.py --model-id <the snapshot's folder> [--host 127.0.0.1] [--port 30028] [--threads 10]
[--products bf16]
The proxy relays it the requests of /v1/embeddings that no other lane is named by (docs/embed-lane.md); its routes, its batches
and their turns are vectors_server.py's."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # python -I leaves its folder out
from vectors_server import MAX_INPUTS, Bad, Engine, Lane, main # noqa: E402
NAME = "pplx-embed-v1-0.6b"
DIM = 1024
def inputs_of(req):
"""What a request asks to embed, in its order: ("text", str)."""
given = req.get("input")
if isinstance(given, str):
given = [given]
if not isinstance(given, list) or not given:
raise Bad("'input' must be a string or a list of them, and not empty")
if len(given) > MAX_INPUTS:
raise Bad(f"'input' holds {len(given)} entries, over {MAX_INPUTS}")
for i, x in enumerate(given):
if isinstance(x, dict) and x.get("type") == "text":
given[i] = x = x.get("text")
if isinstance(x, (int, list)):
raise Bad(f"input[{i}]: token ids are not taken (another model's ids would mean other words here): send the text "
"(LangChain's OpenAIEmbeddings: check_embedding_ctx_length=False)")
if not isinstance(x, str):
raise Bad(f"input[{i}] must be a string: this model reads texts alone (the Mistral Multimodal Embed 1B lane reads "
"images too)")
# an empty string has no token, so no mean to take; one of spaces has its own, as TEI took it in v1.60.0 (a splitter's
# blank chunk refused the whole batch of an indexing job, found in the review of v1.61.0)
if not x:
raise Bad(f"input[{i}] is an empty text")
return [("text", x) for x in given]
def wants(req):
"""How the vectors are written ("float" or "base64") and their dimensions, all of them or the first ones."""
dim = req.get("dimensions")
if dim is None:
dim = req.get("output_dimension")
if dim is not None and (isinstance(dim, bool) or not isinstance(dim, int) or not 1 <= dim <= DIM):
raise Bad(f"'dimensions' is {dim!r}: from 1 to {DIM}")
if req.get("output_dtype") not in (None, "float"):
raise Bad(f"'output_dtype' is {req['output_dtype']!r}: this lane writes floats")
fmt = req.get("encoding_format") or "float"
if fmt not in ("float", "base64"):
raise Bad(f"'encoding_format' is {fmt!r}: float or base64")
return fmt, dim
class Pplx(Engine):
# measured on the reference box (docs/embed-lane.md, 2026-12-02): a text of 2,048 tokens 4.7 s, one of 8,024 49.2 s
SECONDS_PER_TOKEN, SECONDS_PER_SQUARE = 0.001, 6.5e-7
def __init__(self, folder, threads, products):
super().__init__(folder, threads, products)
# its weights are its file's own pages, read as they are asked: all of them once before it says it is ready
self.texts([self.tok.encode("ready").ids])
def load(self, folder):
import pplx_model
return pplx_model.Pplx.load(folder)
LANE = Lane(name=NAME, owner="perplexity-ai", server="qwen38-embed", port=30028, engine=Pplx, inputs_of=inputs_of, wants=wants,
about="the embeddings lane's server (see the module docstring)")
if __name__ == "__main__":
main(LANE)