mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
372 lines
18 KiB
Python
372 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""What the CPU embedding lanes' servers share (clipstral-server.py, pplx-server.py): POST /v1/embeddings on loopback, in
|
|
OpenAI's shape, each vector of norm 1, with the standard library alone. What is a lane's own is its model, what its requests
|
|
may hold and its words: a Lane.
|
|
|
|
It has no key, and listens on loopback alone: the keepalive proxy on :30001 checks the box's key and relays the requests. One
|
|
batch is computed at a time, and the batches of two requests take turns in the order they came; a short text passes between two
|
|
layers of another's batch, so that a query waits for a layer of an indexing job."""
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import os
|
|
import queue
|
|
import select
|
|
import signal
|
|
import socket
|
|
import sys
|
|
import threading
|
|
import time
|
|
from concurrent.futures import Future, ThreadPoolExecutor
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
MAX_BODY = 64 * 1024 * 1024 # one request, its images in base64 included
|
|
MAX_INPUTS = 2048 # as OpenAI's API
|
|
MAX_TOKENS = 8192 # of one text: the attention of a longer one costs the CPU minutes
|
|
MAX_REQUEST_TOKENS = 300_000 # of a request's texts, as OpenAI's API
|
|
MAX_REQUEST_IMAGES = 256 # of a request
|
|
# What a request may take, as its lane's server estimates it before computing it (Engine.SECONDS_*): the proxy gives an embeddings
|
|
# request 900 s to begin its answer, and a client that got a 503 at 900 s asked again for nothing. 37 texts of 8,024 tokens were
|
|
# taken by the embeddings lane, about 30 minutes there (found in the review of v1.61.0, 2026-12-02).
|
|
BUDGET_S = 600
|
|
BATCH_TOKENS = 4096 # of one batch of texts, padding included
|
|
BATCH_IMAGES = 4 # of one batch of images of one size
|
|
SHORT_TOKENS = 256 # of a request of one batch of texts that passes between two layers of another's
|
|
|
|
|
|
class Bad(Exception):
|
|
"""A request this lane does not take, in words for its client."""
|
|
|
|
|
|
class Gone(Exception):
|
|
"""The client closed its connection: what is left of its request is not computed."""
|
|
|
|
|
|
def log(line): # one line per request; the tests silence it
|
|
sys.stderr.write(line)
|
|
|
|
|
|
class Lane:
|
|
"""A lane's own: its model's name and owner, its port, its engine, what a request of it may hold (inputs_of) and the vectors
|
|
it asks (wants: the way they are written, and their dimensions or None)."""
|
|
|
|
def __init__(self, **own):
|
|
self.__dict__.update(own)
|
|
|
|
|
|
def batches(lengths, budget):
|
|
"""Groups of indices, the near lengths together, so that padding costs little: `budget` at most in each, a longer one
|
|
alone."""
|
|
order, out, group = sorted(range(len(lengths)), key=lambda i: lengths[i]), [], []
|
|
for i in order:
|
|
if group and lengths[i] * (len(group) + 1) > budget:
|
|
out.append(group)
|
|
group = []
|
|
group.append(i)
|
|
return [*out, group] if group else out
|
|
|
|
|
|
def shorter(vector, dim):
|
|
"""A vector's first values, of norm 1 again: what a model trained for it (Matryoshka) gives for fewer dimensions."""
|
|
if dim is None or dim == len(vector):
|
|
return vector
|
|
norm = sum(x * x for x in vector[:dim]) ** 0.5 or 1.0
|
|
return [x / norm for x in vector[:dim]]
|
|
|
|
|
|
# -- the model -------------------------------------------------------------------------------------------------------------
|
|
class Turns:
|
|
"""One thread computes, as torch keeps a team of threads for each that does (fifty requests computing on their own reached
|
|
the container's limit, which ends the process): batch after batch, in the order they came. A short one passes sooner,
|
|
between two layers of another."""
|
|
|
|
def __init__(self):
|
|
self.thread, self.short = ThreadPoolExecutor(1), queue.SimpleQueue()
|
|
|
|
def take(self, work, short):
|
|
"""What work() gives, at its turn."""
|
|
done = Future()
|
|
|
|
def run():
|
|
try:
|
|
done.set_result(work())
|
|
except BaseException as e: # noqa: BLE001 (its request's, whoever's layers it passed between)
|
|
done.set_exception(e)
|
|
if short:
|
|
self.short.put(run)
|
|
self.thread.submit(self.let_pass if short else run)
|
|
return done.result()
|
|
|
|
def let_pass(self):
|
|
"""One of the short batches that wait, if any does: between two layers, or at the turn of the one that found it taken."""
|
|
try:
|
|
run = self.short.get_nowait()
|
|
except queue.Empty:
|
|
return
|
|
run()
|
|
|
|
|
|
class Engine:
|
|
"""A lane's model and its tokenizer, on this process's CPUs: load(folder) is the lane's own, and opened() and images() of one
|
|
that reads images. What a request takes on the ten A725 cores is the lane's own too, as its server measured it: seconds per
|
|
token, per token squared of each text (its attention), per image."""
|
|
SECONDS_PER_TOKEN = SECONDS_PER_SQUARE = SECONDS_PER_IMAGE = 0.0
|
|
|
|
def __init__(self, folder, threads, products):
|
|
import torch
|
|
from tokenizers import Tokenizer
|
|
|
|
import cpu_layers
|
|
torch.set_num_threads(threads)
|
|
self.torch = torch
|
|
cpu_layers.MATMUL = {"bf16": "bf16", "fp32": "ieee"}[products]
|
|
self.tok = Tokenizer.from_file(os.path.join(folder, "tokenizer.json"))
|
|
self.tok.no_padding()
|
|
self.tok.no_truncation()
|
|
# a text is words, never the model's own marks: "</s>" inside one would be where its vector is read
|
|
self.tok.encode_special_tokens = True
|
|
# its longest token, in bytes: a text of more of them than MAX_TOKENS such tokens hold is refused unread
|
|
self.longest = max(map(len, self.tok.get_vocab(with_added_tokens=False)))
|
|
self.model = self.load(folder)
|
|
self.turns = Turns()
|
|
|
|
def numbers(self, vectors):
|
|
"""The vectors as lists of floats. One that is not a number is an error, never an answer an index would keep."""
|
|
if not self.torch.isfinite(vectors).all():
|
|
raise ArithmeticError("a vector holds a value that is not a number")
|
|
return vectors.tolist()
|
|
|
|
def texts(self, ids, between=None):
|
|
"""The vectors of texts, each the list of its tokens."""
|
|
torch, n = self.torch, max(map(len, ids))
|
|
row = torch.zeros(len(ids), n, dtype=torch.long)
|
|
keep = torch.zeros(len(ids), n, dtype=torch.bool)
|
|
for r, x in enumerate(ids):
|
|
row[r, :len(x)] = torch.tensor(x)
|
|
keep[r, :len(x)] = True
|
|
return self.numbers(self.model.texts(row, keep, between))
|
|
|
|
def encode(self, inputs, gone=lambda: False):
|
|
"""Each input's vector (a list of floats) and its tokens, in order. The whole request is read before any of it is
|
|
computed, so that one refused costs nothing."""
|
|
out, tokens, texts, ids, images = [None] * len(inputs), [0] * len(inputs), [], [], {}
|
|
total, pictures = 0, sum(kind == "image" for kind, _ in inputs)
|
|
if pictures > MAX_REQUEST_IMAGES:
|
|
raise Bad(f"this request holds {pictures} images, over {MAX_REQUEST_IMAGES}: send its inputs in several")
|
|
seconds = self.SECONDS_PER_IMAGE * pictures
|
|
|
|
def too_long(seconds):
|
|
return Bad(f"this request would take about {seconds / 60:.0f} min on this box's CPU, over the {BUDGET_S // 60} min a "
|
|
"request is given: send its inputs in several")
|
|
if seconds > BUDGET_S:
|
|
raise too_long(seconds)
|
|
for i, (kind, x) in enumerate(inputs):
|
|
if kind == "text":
|
|
if len(x) > MAX_TOKENS * self.longest:
|
|
raise Bad(f"input[{i}] is {len(x)} characters, over {MAX_TOKENS} tokens: send it in parts")
|
|
try:
|
|
x.encode()
|
|
except UnicodeEncodeError:
|
|
raise Bad(f"input[{i}] holds half a character (a surrogate alone): cut texts between characters") from None
|
|
got = self.tok.encode(x).ids
|
|
if len(got) > MAX_TOKENS:
|
|
raise Bad(f"input[{i}] is {len(got)} tokens, over {MAX_TOKENS}: send it in parts")
|
|
texts.append(i)
|
|
ids.append(got)
|
|
tokens[i] = len(got)
|
|
total += len(got)
|
|
if total > MAX_REQUEST_TOKENS:
|
|
raise Bad(f"this request holds over {MAX_REQUEST_TOKENS} tokens of text: send its inputs in several")
|
|
seconds += self.SECONDS_PER_TOKEN * len(got) + self.SECONDS_PER_SQUARE * len(got) ** 2
|
|
if seconds > BUDGET_S:
|
|
raise too_long(seconds)
|
|
else:
|
|
what, size = self.opened(x, f"input[{i}]")
|
|
images.setdefault(size, []).append((i, what))
|
|
tokens[i] = size[0] // self.lib.GRID * (size[1] // self.lib.GRID)
|
|
work = [([texts[k] for k in group], self.texts, [ids[k] for k in group])
|
|
for group in batches([len(x) for x in ids], BATCH_TOKENS)]
|
|
for some in images.values():
|
|
work += [([i for i, _ in some[a:a + BATCH_IMAGES]], self.images, [(f"input[{i}]", what) for i, what in some[a:a + BATCH_IMAGES]])
|
|
for a in range(0, len(some), BATCH_IMAGES)]
|
|
short = len(work) == 1 and not images and sum(map(len, ids)) <= SHORT_TOKENS
|
|
between = None if short else self.turns.let_pass
|
|
for at, compute, what in work:
|
|
for i, v in zip(at, self.turns.take(lambda: self.one(compute, what, gone, between), short)):
|
|
out[i] = v
|
|
return out, tokens
|
|
|
|
@staticmethod
|
|
def one(compute, what, gone, between):
|
|
"""A batch at its turn, unless its client left while it waited."""
|
|
if gone():
|
|
raise Gone
|
|
return compute(what, between)
|
|
|
|
|
|
# -- the routes ------------------------------------------------------------------------------------------------------------
|
|
def written(vector, fmt):
|
|
"""A vector as the answer writes it: base64 of its little-endian float32s, or its floats in the nine digits that give
|
|
each float32 back."""
|
|
if fmt == "base64":
|
|
import array
|
|
a = array.array("f", vector)
|
|
if sys.byteorder != "little":
|
|
a.byteswap()
|
|
return base64.b64encode(a.tobytes()).decode()
|
|
return [float(f"{x:.9g}") for x in vector]
|
|
|
|
|
|
def make_handler(state, lane):
|
|
"""`state` holds the engine once it is loaded ("engine"): until then /health and /v1/embeddings answer 503."""
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
server_version = lane.server
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, fmt, *args): # one line per request, below
|
|
pass
|
|
|
|
def _send(self, code, obj, extra=None, note=""):
|
|
body = json.dumps(obj, ensure_ascii=False).encode()
|
|
unread = self.command == "POST" and not self._read_whole
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
for k, v in (extra or {}).items():
|
|
self.send_header(k, v)
|
|
if unread:
|
|
# what is left of the body would be read as the next request of this connection
|
|
self.send_header("Connection", "close")
|
|
try:
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
except OSError: # its client left meanwhile
|
|
self.close_connection, unread, code = True, False, f"{code} gone"
|
|
log(f"{self.command} {self.path} {code} {note}{time.time() - self._t0:.2f}s\n")
|
|
if unread:
|
|
self._linger()
|
|
|
|
def _linger(self, idle_s=2.0, total_s=10.0):
|
|
"""After an answer that leaves a body unread: end our side, then read and drop what its client still sends, for
|
|
a while. Closed at once, the socket answers it with a reset, and the reset takes the answer back."""
|
|
self.close_connection = True
|
|
try:
|
|
self.wfile.flush()
|
|
self.connection.shutdown(socket.SHUT_WR)
|
|
self.connection.settimeout(idle_s)
|
|
end = time.monotonic() + total_s
|
|
while time.monotonic() < end and self.connection.recv(65536):
|
|
pass
|
|
except OSError:
|
|
pass
|
|
|
|
def _err(self, code, message, kind="invalid_request_error", extra=None):
|
|
self._send(code, {"error": {"message": message, "type": kind}}, extra)
|
|
|
|
def _body(self):
|
|
"""The body, or None once refused: over the cap, or with no length. A body sent in chunks has none: the proxy, and
|
|
every client of /v1/embeddings read for this lane, sends a Content-Length."""
|
|
try:
|
|
n = int(self.headers.get("Content-Length") or -1)
|
|
except ValueError:
|
|
n = -1
|
|
if n < 0 or self.headers.get("Transfer-Encoding") is not None:
|
|
return self._err(411, "the request has no Content-Length, or not one")
|
|
if n > MAX_BODY:
|
|
return self._err(413, f"the request body is over {MAX_BODY // (1024 * 1024)} MiB")
|
|
self._read_whole = True
|
|
return self.rfile.read(n)
|
|
|
|
def _gone(self):
|
|
"""Whether the client closed its side while its request waited or was computed."""
|
|
try:
|
|
poller = select.poll() # select() refuses a descriptor past 1024
|
|
poller.register(self.connection, select.POLLIN)
|
|
return bool(poller.poll(0)) and not self.connection.recv(1, socket.MSG_PEEK)
|
|
except (OSError, ValueError):
|
|
return True
|
|
|
|
def do_GET(self):
|
|
self._t0, self._read_whole = time.time(), True
|
|
path = self.path.split("?", 1)[0]
|
|
ready = state.get("engine") is not None
|
|
if path == "/health":
|
|
self._send(200 if ready else 503, {"status": "ok" if ready else "loading"})
|
|
elif path == "/v1/models":
|
|
self._send(200, {"object": "list", "data": [{"id": lane.name, "object": "model", "owned_by": lane.owner}]})
|
|
else:
|
|
self._err(404, f"no route {path}")
|
|
|
|
def do_POST(self):
|
|
self._t0, self._read_whole = time.time(), False
|
|
path = self.path.split("?", 1)[0]
|
|
if path != "/v1/embeddings":
|
|
return self._err(404, f"no route {path}")
|
|
raw = self._body()
|
|
if raw is None:
|
|
return None
|
|
engine = state.get("engine")
|
|
if engine is None:
|
|
return self._err(503, "the model is loading: try again in a few seconds", "engine_unavailable",
|
|
{"Retry-After": "5"})
|
|
try:
|
|
req = json.loads(raw)
|
|
if not isinstance(req, dict):
|
|
raise ValueError
|
|
except (ValueError, RecursionError):
|
|
return self._err(400, "the body must be a JSON object")
|
|
try:
|
|
fmt, dim = lane.wants(req)
|
|
inputs = lane.inputs_of(req)
|
|
del raw, req # the images in base64, twice: not kept while the request waits its turn
|
|
vectors, tokens = engine.encode(inputs, self._gone)
|
|
except Bad as e:
|
|
return self._err(400, str(e))
|
|
except Gone:
|
|
self.close_connection = True
|
|
log(f"POST {path} gone {time.time() - self._t0:.2f}s\n")
|
|
return None
|
|
except Exception as e: # noqa: BLE001 (the engine's own message, not a trace)
|
|
return self._err(500, f"the model did not compute it: {type(e).__name__}: {e}", "server_error")
|
|
total, n = sum(tokens), sum(kind == "image" for kind, _ in inputs)
|
|
return self._send(200, {"object": "list", "model": lane.name, "usage": {"prompt_tokens": total, "total_tokens": total},
|
|
"data": [{"object": "embedding", "index": i, "embedding": written(shorter(v, dim), fmt)}
|
|
for i, v in enumerate(vectors)]},
|
|
note=f"{len(inputs) - n} texts {n} images {total} tokens ")
|
|
|
|
return Handler
|
|
|
|
|
|
class Server(ThreadingHTTPServer):
|
|
daemon_threads = True
|
|
request_queue_size = 128 # Python's 5: the sixth connection of a burst waited a second for its SYN to be sent again
|
|
|
|
|
|
def main(lane):
|
|
ap = argparse.ArgumentParser(description=lane.about)
|
|
ap.add_argument("--host", default="127.0.0.1")
|
|
ap.add_argument("--port", type=int, default=lane.port)
|
|
ap.add_argument("--model-id", required=True, help="the snapshot's folder: model.safetensors and tokenizer.json")
|
|
ap.add_argument("--revision", help="the snapshot's revision, for the readers of the unit: nothing reads it here")
|
|
ap.add_argument("--threads", type=int, default=len(os.sched_getaffinity(0)))
|
|
ap.add_argument("--products", choices=("bf16", "fp32"), default="bf16",
|
|
help="how the matrices are multiplied: on the cores' bf16 instructions, or in float32")
|
|
a = ap.parse_args()
|
|
# The container's first process, which the kernel gives no default for SIGTERM: without this docker stop waited its
|
|
# 20 s and killed it, and systemd read that exit, 137, as a failure at every stop of the lane.
|
|
signal.signal(signal.SIGTERM, lambda *_: os._exit(0))
|
|
state = {}
|
|
srv = Server((a.host, a.port), make_handler(state, lane))
|
|
|
|
def load():
|
|
t0 = time.time()
|
|
try:
|
|
state["engine"] = lane.engine(a.model_id, a.threads, a.products)
|
|
except BaseException as e: # noqa: BLE001 (said, then the unit ends: systemd starts it again)
|
|
log(f"the model did not load: {type(e).__name__}: {e}\n")
|
|
os._exit(1)
|
|
log(f"{lane.name} ready on {a.host}:{a.port}: products in {a.products}, {a.threads} threads, loaded in {time.time() - t0:.1f} s\n")
|
|
threading.Thread(target=load, daemon=True).start()
|
|
srv.serve_forever()
|