aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / allen_infer.py
| 1 | #!/usr/bin/env python3 |
| 2 | """allen_infer: the /aien/ speed test (gateway routes infer, infer-verify) and the same benchmark as a CLI. |
| 3 | |
| 4 | Gateway routes (imported by allen_chat.py; CONTRACT in aien-dev/aienos.com scripts/allen/README.md |
| 5 | "Speed test"): |
| 6 | |
| 7 | GET /allen/api/infer-info presets, limits and current load (no model call) |
| 8 | POST /allen/api/infer one run, streamed as server-sent events with gateway-measured timings |
| 9 | POST /allen/api/infer-verify checks the HMAC on a shared result (no storage) |
| 10 | |
| 11 | A run is a plain chat completion on the shared model: no Aien persona, temperature 0, and a |
| 12 | one-line system message `Speed test run <8 hex>.` first, so the engine can never continue a |
| 13 | cached row and prefill is always measured from scratch. Modes: single (one stream), concurrent |
| 14 | (2-4 streams at once, aggregate tokens/s) and sweep (separate requests at prompt sizes doubling |
| 15 | from 512 tokens, so a sweep can stop between steps). |
| 16 | |
| 17 | Protection for the shared server (127.0.0.1:18091, 8 batch rows, also serving Aien's chat): |
| 18 | - tests together hold at most SLOTS (4) rows, and start only while the server reports |
| 19 | in_flight + rows <= SERVER_ROOM (6), so two rows stay free for chat; |
| 20 | - a heavy test (concurrent, any sweep, or a prompt estimated over HEAVY_TOKENS) runs alone and |
| 21 | starts only while no chat turn runs or waits in this gateway; a chat arriving mid-test makes it |
| 22 | yield (sweep: before the next step; concurrent: its streams are closed at once). The reason: a |
| 23 | prefill on this engine slows every generating row 6-9x (AienPage LATENCY.md), so row |
| 24 | reservation alone does not protect chat; |
| 25 | - one run per visitor at a time, RUNS_PER_MIN runs and HEAVY_PER_10MIN heavy runs per visitor, |
| 26 | a FIFO queue of QUEUE_DEPTH with visible position, caps on prompt size and max_tokens, and |
| 27 | timeouts scaled to the work. |
| 28 | |
| 29 | Numbers are measured at the gateway as chunks arrive; nothing is smoothed. Each result carries |
| 30 | host load1 and the server's in_flight at that moment, and an HMAC so a shared link can be checked. |
| 31 | |
| 32 | CLI (the "run it on your own GPU" command; same presets and the same measure() code): |
| 33 | |
| 34 | python3 scripts/allen/allen_infer.py bench http://127.0.0.1:8000 --model <name> [--preset all] |
| 35 | [--streams 4] [--sweep 8192] [--api-key KEY] |
| 36 | |
| 37 | Python standard library only. Host dependency and .om successor: DEPENDENCIES.md (allen-gw.om). |
| 38 | """ |
| 39 | |
| 40 | import argparse |
| 41 | import base64 |
| 42 | import collections |
| 43 | import hashlib |
| 44 | import hmac |
| 45 | import http.client |
| 46 | import json |
| 47 | import math |
| 48 | import os |
| 49 | import queue |
| 50 | import re |
| 51 | import secrets |
| 52 | import socket |
| 53 | import sys |
| 54 | import threading |
| 55 | import time |
| 56 | from urllib.parse import urlsplit |
| 57 | |
| 58 | MODEL = "" |
| 59 | SLOTS = 4 # batch rows all tests together may hold |
| 60 | SERVER_ROOM = 6 # start only while server in_flight + rows <= this (8 rows, 2 kept for chat) |
| 61 | HEAVY_TOKENS = 4096 # an estimated prompt above this is heavy |
| 62 | MAX_PROMPT_BYTES = 48 * 1024 |
| 63 | MAX_PROMPT_TOKENS = 32768 |
| 64 | MAX_TOKENS = 4096 |
| 65 | MAX_TOKENS_CONCURRENT = 1024 |
| 66 | MAX_STREAMS = 4 |
| 67 | SWEEP_MAXES = (4096, 8192, 16384, 32768) |
| 68 | SWEEP_OUT = 8 # output tokens per sweep step |
| 69 | RUNS_PER_MIN = 6 |
| 70 | HEAVY_PER_10MIN = 3 |
| 71 | QUEUE_DEPTH = 8 |
| 72 | QUEUE_WAIT = 180.0 # seconds a run may wait in line |
| 73 | CHUNK_MAX = 1 << 20 |
| 74 | |
| 75 | PRESETS = collections.OrderedDict() |
| 76 | PRESETS["short"] = {"max_tokens": 64, "prompt": "In two sentences, explain why the sky is blue."} |
| 77 | PRESETS["medium"] = {"max_tokens": 256, "prompt": ( |
| 78 | "Explain how a CPU cache hierarchy works: what L1, L2 and L3 caches are, why they exist, " |
| 79 | "what a cache line is, and what happens on a cache miss. Use plain language and short paragraphs.")} |
| 80 | |
| 81 | |
| 82 | def _long_prompt(): |
| 83 | rows = [] |
| 84 | for i in range(1, 41): |
| 85 | rows.append("Record %03d: station %s measured %d.%d degrees at %02d:%02d, humidity %d percent, wind %d km/h from bearing %03d." |
| 86 | % (i, "ABCDEFGHJK"[i % 10] + "ABCDEFGHJK"[(i * 7) % 10], (i * 37) % 40, (i * 3) % 10, |
| 87 | (i * 5) % 24, (i * 11) % 60, 30 + (i * 13) % 60, (i * 17) % 50, (i * 29) % 360)) |
| 88 | return ("Below is a log of weather records.\n\n" + "\n".join(rows) + |
| 89 | "\n\nWrite a detailed report on this log: the temperature range, which stations were warmest and " |
| 90 | "coldest, how humidity and wind varied through the day, and anything unusual. Be thorough.") |
| 91 | |
| 92 | |
| 93 | PRESETS["long"] = {"max_tokens": 1024, "prompt": _long_prompt()} |
| 94 | |
| 95 | FILLER = "Line %05d: the quick brown fox jumps over the lazy dog near the river bank.\n" |
| 96 | FILLER_TOKENS = 23 # per filler line, measured on the live server: 25 lines -> 615 prompt tokens, |
| 97 | FILLER_BASE = 40 # 204 lines -> 4732 (nonce line, chat template and question are the 40); pages show the real count |
| 98 | SWEEP_ASK = "\nHow many lines are above? Reply with one number." |
| 99 | |
| 100 | |
| 101 | def sweep_sizes(top): |
| 102 | out, n = [], 512 |
| 103 | while n <= top: |
| 104 | out.append(n) |
| 105 | n *= 2 |
| 106 | return out |
| 107 | |
| 108 | |
| 109 | def sweep_prompt(target): |
| 110 | return "".join(FILLER % i for i in range(1, max(1, (target - FILLER_BASE) // FILLER_TOKENS) + 1)) + SWEEP_ASK |
| 111 | |
| 112 | |
| 113 | WORD = re.compile(r"[A-Za-z]+|[0-9]|[^\sA-Za-z0-9]") |
| 114 | |
| 115 | |
| 116 | def est_tokens(text): |
| 117 | """A conservative token estimate without the tokenizer: ASCII letter runs count one per 4 |
| 118 | letters, every digit, punctuation mark and non-ASCII character counts one.""" |
| 119 | n = 0 |
| 120 | for m in WORD.finditer(text): |
| 121 | w = m.group(0) |
| 122 | n += (len(w) + 3) // 4 if w[0].isascii() and w[0].isalpha() else 1 |
| 123 | return n |
| 124 | |
| 125 | |
| 126 | def load1(): |
| 127 | try: |
| 128 | with open("/proc/loadavg") as f: |
| 129 | return float(f.read().split()[0]) |
| 130 | except (OSError, ValueError, IndexError): |
| 131 | return None |
| 132 | |
| 133 | |
| 134 | def measure(host, port, path, headers, model, messages, max_tokens, on_tok, cancel, ttft_s, total_s, |
| 135 | hold=None): |
| 136 | """One streamed chat completion, timed as chunks arrive. on_tok(t_monotonic, text) per content |
| 137 | chunk. cancel: threading.Event; set it (and call hold[0].close()) to stop. Returns a dict with |
| 138 | monotonic times: sent, first, last, end; prompt_tokens, completion_tokens, chunks, finish, error.""" |
| 139 | body = json.dumps({"model": model, "messages": messages, "stream": True, |
| 140 | "stream_options": {"include_usage": True}, "max_tokens": max_tokens, |
| 141 | "temperature": 0}).encode() |
| 142 | out = {"sent": None, "first": None, "last": None, "end": None, "prompt_tokens": None, |
| 143 | "completion_tokens": None, "chunks": 0, "finish": None, "error": None} |
| 144 | c = http.client.HTTPConnection(host, port, timeout=ttft_s) |
| 145 | if hold is not None: |
| 146 | hold.append(c) |
| 147 | try: |
| 148 | out["sent"] = time.monotonic() |
| 149 | c.request("POST", path, body, dict(headers, **{"Content-Type": "application/json"})) |
| 150 | r = c.getresponse() |
| 151 | if r.status != 200: |
| 152 | r.read(65536) |
| 153 | out["error"] = "busy" if r.status == 503 else "upstream_%d" % r.status |
| 154 | return out |
| 155 | deadline = out["sent"] + total_s |
| 156 | while True: |
| 157 | if cancel.is_set(): |
| 158 | out["error"] = "cancelled" |
| 159 | return out |
| 160 | if time.monotonic() > deadline: |
| 161 | out["error"] = "timeout" |
| 162 | return out |
| 163 | line = r.readline(CHUNK_MAX) |
| 164 | if not line: |
| 165 | break |
| 166 | if not line.startswith(b"data: "): |
| 167 | continue |
| 168 | payload = line[6:].strip() |
| 169 | if payload == b"[DONE]": |
| 170 | break |
| 171 | chunk = json.loads(payload) |
| 172 | u = chunk.get("usage") |
| 173 | if u: |
| 174 | out["prompt_tokens"] = u.get("prompt_tokens") |
| 175 | out["completion_tokens"] = u.get("completion_tokens") |
| 176 | for ch in chunk.get("choices", ()): |
| 177 | if ch.get("finish_reason"): |
| 178 | out["finish"] = ch["finish_reason"] |
| 179 | text = (ch.get("delta") or {}).get("content") |
| 180 | if text: |
| 181 | now = time.monotonic() |
| 182 | if out["first"] is None: |
| 183 | out["first"] = now |
| 184 | if c.sock is not None: |
| 185 | c.sock.settimeout(30) |
| 186 | out["last"] = now |
| 187 | out["chunks"] += 1 |
| 188 | on_tok(now, text) |
| 189 | except (OSError, ValueError, http.client.HTTPException) as e: |
| 190 | out["error"] = "cancelled" if cancel.is_set() else ("timeout" if isinstance(e, (socket.timeout, TimeoutError)) |
| 191 | else "upstream") |
| 192 | finally: |
| 193 | out["end"] = time.monotonic() |
| 194 | c.close() |
| 195 | return out |
| 196 | |
| 197 | |
| 198 | def rate(n, seconds): |
| 199 | return round(n / seconds, 1) if n is not None and seconds and seconds > 0 else None |
| 200 | |
| 201 | |
| 202 | def stats(m, t0): |
| 203 | """The stream summary the page shows, in ms relative to t0 (the run's start).""" |
| 204 | ms = lambda t: int(round((t - t0) * 1000)) if t is not None else None # noqa: E731 |
| 205 | comp = m["completion_tokens"] if m["completion_tokens"] is not None else m["chunks"] |
| 206 | ttft = (m["first"] - m["sent"]) if m["first"] is not None else None |
| 207 | dec = (m["last"] - m["first"]) if m["first"] is not None and m["last"] is not None else None |
| 208 | return {"prompt_tokens": m["prompt_tokens"], "completion_tokens": comp, |
| 209 | "ttft_ms": int(round(ttft * 1000)) if ttft is not None else None, |
| 210 | "prefill_tps": rate(m["prompt_tokens"], ttft), |
| 211 | "decode_tps": rate(comp - 1, dec) if comp and comp > 1 else None, |
| 212 | "total_ms": int(round((m["end"] - m["sent"]) * 1000)) if m["sent"] else None, |
| 213 | "start_ms": ms(m["sent"]), "first_ms": ms(m["first"]), "last_ms": ms(m["last"]), |
| 214 | "finish": m["finish"] or m["error"] or "stop", "error": m["error"]} |
| 215 | |
| 216 | |
| 217 | def run_messages(prompt, nonce): |
| 218 | return [{"role": "system", "content": "Speed test run %s." % nonce}, {"role": "user", "content": prompt}] |
| 219 | |
| 220 | |
| 221 | # ---------------------------------------------------------------- gateway state |
| 222 | |
| 223 | class Window: |
| 224 | def __init__(self, n, span): |
| 225 | self.n, self.span, self.lock, self.hits = n, span, threading.Lock(), {} |
| 226 | |
| 227 | def take(self, key): |
| 228 | """0 when admitted, else seconds until the oldest hit leaves the window.""" |
| 229 | now = time.monotonic() |
| 230 | with self.lock: |
| 231 | q = [t for t in self.hits.get(key, ()) if now - t < self.span] |
| 232 | if len(q) >= self.n: |
| 233 | self.hits[key] = q |
| 234 | return int(self.span - (now - q[0])) + 1 |
| 235 | q.append(now) |
| 236 | self.hits[key] = q |
| 237 | return 0 |
| 238 | |
| 239 | def sweep(self): |
| 240 | now = time.monotonic() |
| 241 | with self.lock: |
| 242 | for k in [k for k, q in self.hits.items() if not q or now - q[-1] > self.span]: |
| 243 | del self.hits[k] |
| 244 | |
| 245 | |
| 246 | class Lab: |
| 247 | """FIFO admission for speed tests. A run needs `rows` rows; heavy runs go alone and only |
| 248 | while no chat turn runs or waits.""" |
| 249 | |
| 250 | def __init__(self, app): |
| 251 | self.app = app |
| 252 | self.cond = threading.Condition() |
| 253 | self.used = 0 |
| 254 | self.heavy = False |
| 255 | self.waiting = [] |
| 256 | self.ticket = 0 |
| 257 | self.active = set() # visitor keys with a run queued or running |
| 258 | self.runs = Window(RUNS_PER_MIN, 60) |
| 259 | self.heavies = Window(HEAVY_PER_10MIN, 600) |
| 260 | secret = os.environ.get("ALLEN_VISITOR_SECRET", "").strip().encode() |
| 261 | self.key = hmac.new(secret, b"aien-infer-sig-v1", hashlib.sha256).digest() if len(secret) >= 32 \ |
| 262 | else secrets.token_bytes(32) |
| 263 | |
| 264 | def chat_busy(self): |
| 265 | g = self.app.gate |
| 266 | with g.cond: |
| 267 | return g.running > 0 or bool(g.waiting) |
| 268 | |
| 269 | def server(self, fresh=False): |
| 270 | up = self.app.up |
| 271 | if fresh: |
| 272 | up.health_at = 0.0 # admission decides on a read taken now, not the 0.5 s cache |
| 273 | up.admit() |
| 274 | return up.health_ok, up.health_inflight |
| 275 | |
| 276 | def enter(self, vkey): |
| 277 | with self.cond: |
| 278 | if vkey in self.active: |
| 279 | return None, "one" |
| 280 | if len(self.waiting) >= QUEUE_DEPTH: |
| 281 | return None, "full" |
| 282 | self.ticket += 1 |
| 283 | self.waiting.append(self.ticket) |
| 284 | self.active.add(vkey) |
| 285 | return self.ticket, None |
| 286 | |
| 287 | def why_waiting(self, t, rows, heavy): |
| 288 | """None when the run may start now (and it is then started), else the reason.""" |
| 289 | with self.cond: |
| 290 | if not self.waiting or self.waiting[0] != t: |
| 291 | return "line" |
| 292 | ok, inflight = self.server(fresh=True) # only the head of the line reads /health |
| 293 | with self.cond: |
| 294 | if not self.waiting or self.waiting[0] != t: |
| 295 | return "line" |
| 296 | if self.heavy or self.used + rows > SLOTS: |
| 297 | return "slots" |
| 298 | if not ok or inflight + rows > SERVER_ROOM: |
| 299 | return "server" |
| 300 | if heavy and (self.used or self.chat_busy()): |
| 301 | return "chat" if self.chat_busy() else "slots" |
| 302 | self.waiting.pop(0) |
| 303 | self.used += rows |
| 304 | self.heavy = heavy |
| 305 | self.cond.notify_all() |
| 306 | return None |
| 307 | |
| 308 | def position(self, t): |
| 309 | with self.cond: |
| 310 | return self.waiting.index(t) + 1 if t in self.waiting else 0 |
| 311 | |
| 312 | def leave(self, t, vkey, rows=0, started=False): |
| 313 | with self.cond: |
| 314 | if t in self.waiting: |
| 315 | self.waiting.remove(t) |
| 316 | if started: |
| 317 | self.used -= rows |
| 318 | self.heavy = False |
| 319 | self.active.discard(vkey) |
| 320 | self.cond.notify_all() |
| 321 | |
| 322 | def wait(self, s): |
| 323 | with self.cond: |
| 324 | self.cond.wait(s) |
| 325 | |
| 326 | def sign(self, result): |
| 327 | return hmac.new(self.key, canon(result), hashlib.sha256).hexdigest() |
| 328 | |
| 329 | |
| 330 | def _js(o): |
| 331 | """What a browser's JSON.parse/stringify would hand back: 48.0 becomes 48.""" |
| 332 | if isinstance(o, dict): |
| 333 | return {k: _js(v) for k, v in o.items()} |
| 334 | if isinstance(o, list): |
| 335 | return [_js(v) for v in o] |
| 336 | if isinstance(o, float) and o.is_integer(): |
| 337 | return int(o) |
| 338 | return o |
| 339 | |
| 340 | |
| 341 | def canon(obj): |
| 342 | return json.dumps(_js(obj), sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() |
| 343 | |
| 344 | |
| 345 | def init(app): |
| 346 | app.lab = Lab(app) |
| 347 | |
| 348 | |
| 349 | def limits(): |
| 350 | return {"slots": SLOTS, "max_tokens": MAX_TOKENS, "max_tokens_concurrent": MAX_TOKENS_CONCURRENT, |
| 351 | "max_streams": MAX_STREAMS, "max_prompt_bytes": MAX_PROMPT_BYTES, |
| 352 | "max_prompt_tokens": MAX_PROMPT_TOKENS, "heavy_tokens": HEAVY_TOKENS, |
| 353 | "sweep_max": list(SWEEP_MAXES), "sweep_out": SWEEP_OUT, "runs_per_min": RUNS_PER_MIN, |
| 354 | "heavy_per_10min": HEAVY_PER_10MIN, "queue_depth": QUEUE_DEPTH} |
| 355 | |
| 356 | |
| 357 | def get(h): |
| 358 | lab = h.app.lab |
| 359 | ok, inflight = lab.server() |
| 360 | with lab.cond: |
| 361 | st = {"used": lab.used, "heavy": lab.heavy, "queue": len(lab.waiting)} |
| 362 | h.send_json(200, {"model": MODEL, "presets": PRESETS, "limits": limits(), "tests_in_flight": st["used"], |
| 363 | "heavy_running": st["heavy"], "queue": st["queue"], "chat_active": lab.chat_busy(), |
| 364 | "server_ok": ok, "server_in_flight": inflight, "load1": load1()}) |
| 365 | |
| 366 | |
| 367 | def verify(h): |
| 368 | req = h.read_json() |
| 369 | if req is None: |
| 370 | return |
| 371 | res, sig = (req.get("result"), req.get("sig")) if isinstance(req, dict) else (None, None) |
| 372 | if not isinstance(res, dict) or not isinstance(sig, str) or not re.match(r"^[0-9a-f]{64}$", sig): |
| 373 | return h.refuse(400, "bad_request", "Send {result, sig}.") |
| 374 | h.send_json(200, {"ok": hmac.compare_digest(h.app.lab.sign(res), sig)}) |
| 375 | |
| 376 | |
| 377 | def parse(req): |
| 378 | """(plan, error message). plan: mode, prompt(s), max_tokens, streams, sizes, heavy, preset.""" |
| 379 | if not isinstance(req, dict): |
| 380 | return None, "Send a JSON object." |
| 381 | mode = req.get("mode", "single") |
| 382 | if mode not in ("single", "concurrent", "sweep"): |
| 383 | return None, "mode is single, concurrent or sweep." |
| 384 | plan = {"mode": mode, "preset": None, "streams": 1, "sizes": None} |
| 385 | if mode == "sweep": |
| 386 | top = req.get("sweep_max", 8192) |
| 387 | if top not in SWEEP_MAXES: |
| 388 | return None, "sweep_max is one of %s." % ", ".join(map(str, SWEEP_MAXES)) |
| 389 | plan.update(sizes=sweep_sizes(top), max_tokens=SWEEP_OUT, requested=SWEEP_OUT, heavy=True, prompt=None) |
| 390 | return plan, None |
| 391 | preset = req.get("preset") |
| 392 | if preset is not None: |
| 393 | if preset not in PRESETS: |
| 394 | return None, "preset is short, medium or long." |
| 395 | prompt, mt = PRESETS[preset]["prompt"], PRESETS[preset]["max_tokens"] |
| 396 | asked = mt |
| 397 | plan["preset"] = preset |
| 398 | else: |
| 399 | prompt = req.get("prompt") |
| 400 | if not isinstance(prompt, str) or not prompt.strip(): |
| 401 | return None, "Write a prompt or pick a preset." |
| 402 | if len(prompt.encode()) > MAX_PROMPT_BYTES or est_tokens(prompt) > MAX_PROMPT_TOKENS: |
| 403 | return None, "too_long" |
| 404 | asked = req.get("max_tokens", 256) |
| 405 | if not isinstance(asked, int) or isinstance(asked, bool) or asked < 1: |
| 406 | return None, "max_tokens is a whole number from 1." |
| 407 | mt = asked |
| 408 | cap = MAX_TOKENS if mode == "single" else MAX_TOKENS_CONCURRENT |
| 409 | if mode == "concurrent": |
| 410 | n = req.get("streams", 4) |
| 411 | if not isinstance(n, int) or isinstance(n, bool) or not 2 <= n <= MAX_STREAMS: |
| 412 | return None, "streams is 2 to %d." % MAX_STREAMS |
| 413 | plan["streams"] = n |
| 414 | plan.update(prompt=prompt, max_tokens=min(mt, cap), requested=asked, |
| 415 | heavy=mode == "concurrent" or est_tokens(prompt) > HEAVY_TOKENS) |
| 416 | return plan, None |
| 417 | |
| 418 | |
| 419 | def run(h): |
| 420 | app = h.app |
| 421 | lab = app.lab |
| 422 | app.stats.add("infer_requests") |
| 423 | req = h.read_json() |
| 424 | if req is None: |
| 425 | return |
| 426 | plan, problem = parse(req) |
| 427 | if problem == "too_long": |
| 428 | return h.refuse(413, "too_long", "That prompt is over the limit (48 KiB, about 32k tokens).") |
| 429 | if problem: |
| 430 | return h.refuse(400, "bad_request", problem) |
| 431 | if not lab.server(fresh=True)[0]: |
| 432 | app.stats.add("infer_offline") |
| 433 | return h.refuse(503, "offline", "My model server is offline right now (the GPU is in use for other tests). " |
| 434 | "The speed test is back when it is.", 300) |
| 435 | vkey = app.client_key(h) |
| 436 | retry = lab.runs.take(vkey) |
| 437 | if retry: |
| 438 | return h.refuse(429, "rate", "You have run %d tests this minute. Try again in %d s." % (RUNS_PER_MIN, retry), retry) |
| 439 | if plan["heavy"]: |
| 440 | retry = lab.heavies.take(vkey) |
| 441 | if retry: |
| 442 | return h.refuse(429, "rate", "Heavy tests (parallel, sweep, long prompts): %d per 10 minutes each. " |
| 443 | "Try again in %d s." % (HEAVY_PER_10MIN, retry), retry) |
| 444 | ticket, why = lab.enter(vkey) |
| 445 | if ticket is None: |
| 446 | if why == "one": |
| 447 | return h.refuse(409, "one_at_a_time", "You already have a test running. Wait for it to finish.", 5) |
| 448 | return h.refuse(503, "busy", "The test line is full. Try again in 30 s.", 30) |
| 449 | rows = plan["streams"] |
| 450 | started = False |
| 451 | h.sse_headers("infer") |
| 452 | try: |
| 453 | t0 = time.monotonic() |
| 454 | last_pos, last_beat, last_why = -1, 0.0, None |
| 455 | while True: |
| 456 | why = lab.why_waiting(ticket, rows, plan["heavy"]) |
| 457 | if why is None: |
| 458 | started = True |
| 459 | break |
| 460 | now = time.monotonic() |
| 461 | if now - t0 > QUEUE_WAIT: |
| 462 | app.stats.add("infer_queue_timeout") |
| 463 | h.sse("error", {"code": "busy", "message": "The server stayed busy for %d s. Try again in a minute." |
| 464 | % QUEUE_WAIT, "retry_after": 60}) |
| 465 | return |
| 466 | pos = lab.position(ticket) |
| 467 | if pos != last_pos or why != last_why or now - last_beat > 3: |
| 468 | with lab.cond: |
| 469 | used = lab.used |
| 470 | h.sse("queue", {"position": pos, "reason": why, "tests_in_flight": used, "slots": SLOTS, |
| 471 | "waited_ms": int((now - t0) * 1000)}) |
| 472 | last_pos, last_why, last_beat = pos, why, now |
| 473 | lab.wait(0.25) |
| 474 | execute(h, plan, int((time.monotonic() - t0) * 1000)) |
| 475 | except (BrokenPipeError, ConnectionResetError, socket.timeout, TimeoutError): |
| 476 | app.stats.add("client_gone") |
| 477 | except Exception as e: # noqa: BLE001 a gateway bug ends the stream with an error, never silently |
| 478 | app.stats.add("infer_internal_error") |
| 479 | print("allen-chat: internal error in infer: %s" % type(e).__name__, flush=True) |
| 480 | try: |
| 481 | h.sse("error", {"code": "upstream", "message": "The test failed inside the gateway. Try again."}) |
| 482 | except OSError: |
| 483 | pass |
| 484 | finally: |
| 485 | lab.leave(ticket, vkey, rows, started) |
| 486 | |
| 487 | |
| 488 | def execute(h, plan, queued_ms): |
| 489 | app = h.app |
| 490 | lab = app.lab |
| 491 | up = app.up |
| 492 | run_id = secrets.token_hex(4) |
| 493 | t0 = time.monotonic() |
| 494 | ok, inflight = lab.server() |
| 495 | with lab.cond: |
| 496 | used = lab.used |
| 497 | start = {"run": run_id, "mode": plan["mode"], "preset": plan["preset"], "model": MODEL, |
| 498 | "max_tokens": plan["max_tokens"], "max_tokens_requested": plan["requested"], |
| 499 | "streams": plan["streams"], "queued_ms": queued_ms, "server_in_flight": inflight, |
| 500 | "tests_in_flight": used, "load1": load1(), "heavy": plan["heavy"]} |
| 501 | if plan["sizes"]: |
| 502 | start["steps"] = plan["sizes"] |
| 503 | h.sse("start", start) |
| 504 | events = queue.Queue() |
| 505 | cancel = threading.Event() |
| 506 | holds = [] |
| 507 | outs = [] |
| 508 | yielded = False |
| 509 | gone = False |
| 510 | |
| 511 | def worker(i, prompt, nonce, ttft_s, total_s, target=None): |
| 512 | hold = [] |
| 513 | holds.append(hold) |
| 514 | m = measure(up.host, up.port, "/v1/chat/completions", up.headers, MODEL, run_messages(prompt, nonce), |
| 515 | plan["max_tokens"], lambda t, s: events.put(("tok", i, t, s)), cancel, ttft_s, total_s, hold) |
| 516 | events.put(("end", i, m, target)) |
| 517 | |
| 518 | def pump(n): |
| 519 | """Forward events until n streams ended. Watches for a chat arriving (heavy runs yield).""" |
| 520 | nonlocal yielded, gone |
| 521 | left = n |
| 522 | beat = time.monotonic() |
| 523 | while left: |
| 524 | try: |
| 525 | ev = events.get(timeout=0.1) |
| 526 | except queue.Empty: |
| 527 | ev = None |
| 528 | now = time.monotonic() |
| 529 | if ev is None and not gone and now - beat > 5: |
| 530 | beat = now # keeps the proxy and the page informed during a long prefill |
| 531 | try: |
| 532 | h.sse("beat", {"t": int(round((now - t0) * 1000))}) |
| 533 | except OSError: |
| 534 | gone = True |
| 535 | cancel.set() |
| 536 | elif ev is not None: |
| 537 | beat = now |
| 538 | if plan["mode"] == "concurrent" and not yielded and lab.chat_busy(): |
| 539 | yielded = True |
| 540 | cancel.set() |
| 541 | for hold in holds: |
| 542 | for c in hold: |
| 543 | try: |
| 544 | if c.sock is not None: |
| 545 | c.sock.shutdown(socket.SHUT_RDWR) |
| 546 | except OSError: |
| 547 | pass |
| 548 | if ev is None: |
| 549 | continue |
| 550 | if ev[0] == "tok": |
| 551 | if not gone: |
| 552 | try: |
| 553 | h.sse("tok", {"i": ev[1], "t": int(round((ev[2] - t0) * 1000)), "s": ev[3]}) |
| 554 | except OSError: |
| 555 | gone = True |
| 556 | cancel.set() |
| 557 | continue |
| 558 | left -= 1 |
| 559 | s = stats(ev[2], t0) |
| 560 | s["i"] = ev[1] |
| 561 | if ev[3] is not None: |
| 562 | s["target_tokens"] = ev[3] |
| 563 | _, s["server_in_flight"] = lab.server() |
| 564 | s["load1"] = load1() |
| 565 | outs.append(s) |
| 566 | if not gone: |
| 567 | try: |
| 568 | h.sse("stream", s) |
| 569 | except OSError: |
| 570 | gone = True |
| 571 | cancel.set() |
| 572 | |
| 573 | if plan["mode"] == "sweep": |
| 574 | for i, size in enumerate(plan["sizes"]): |
| 575 | if i and lab.chat_busy(): |
| 576 | yielded = True |
| 577 | break |
| 578 | if gone or (outs and outs[-1]["error"]): |
| 579 | break |
| 580 | t = threading.Thread(target=worker, daemon=True, |
| 581 | args=(i, sweep_prompt(size), secrets.token_hex(4), 60 + size / 50, 120 + size / 50, size)) |
| 582 | t.start() |
| 583 | pump(1) |
| 584 | else: |
| 585 | est = est_tokens(plan["prompt"]) |
| 586 | for i in range(plan["streams"]): |
| 587 | threading.Thread(target=worker, daemon=True, |
| 588 | args=(i, plan["prompt"], secrets.token_hex(4), 60 + est / 50, |
| 589 | 120 + est / 50 + plan["max_tokens"] / 4)).start() |
| 590 | pump(plan["streams"]) |
| 591 | if gone: |
| 592 | app.stats.add("client_gone") |
| 593 | return |
| 594 | outs.sort(key=lambda s: s["i"]) |
| 595 | _, inflight_end = lab.server() |
| 596 | result = {"v": 1, "run": run_id, "mode": plan["mode"], "preset": plan["preset"], "model": MODEL, |
| 597 | "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "max_tokens": plan["max_tokens"], |
| 598 | "streams": plan["streams"], "server_in_flight": start["server_in_flight"], |
| 599 | "server_in_flight_end": inflight_end, "tests_in_flight": start["tests_in_flight"], |
| 600 | "load1": start["load1"], "load1_end": load1(), "yielded": yielded, |
| 601 | "streams_out": outs, "wall_ms": int(round((time.monotonic() - t0) * 1000)), "aggregate_tps": None} |
| 602 | if plan["mode"] == "concurrent": |
| 603 | firsts = [s["start_ms"] for s in outs if s["start_ms"] is not None] |
| 604 | lasts = [s["last_ms"] for s in outs if s["last_ms"] is not None] |
| 605 | total = sum(s["completion_tokens"] or 0 for s in outs) |
| 606 | if firsts and lasts and max(lasts) > min(firsts): |
| 607 | result["aggregate_tps"] = round(total * 1000.0 / (max(lasts) - min(firsts)), 1) |
| 608 | if yielded: |
| 609 | app.stats.add("infer_yielded") |
| 610 | h.sse("yielded", {"reason": "chat", "completed_steps": sum(1 for s in outs if not s["error"])}) |
| 611 | app.stats.add("infer_completed") |
| 612 | h.sse("done", {"result": result, "sig": lab.sign(result)}) |
| 613 | |
| 614 | |
| 615 | # ---------------------------------------------------------------- CLI: the same benchmark on your GPU |
| 616 | |
| 617 | def bench(argv): |
| 618 | ap = argparse.ArgumentParser(prog="allen_infer.py bench", |
| 619 | description="The aienos.com/aien/ speed test against your own OpenAI-compatible server.") |
| 620 | ap.add_argument("url", help="server base URL, for example http://127.0.0.1:8000 (POSTs <url>/v1/chat/completions)") |
| 621 | ap.add_argument("--model", required=True) |
| 622 | ap.add_argument("--preset", default="all", choices=["all"] + list(PRESETS)) |
| 623 | ap.add_argument("--streams", type=int, default=0, help="also run the parallel test with this many streams (2-8)") |
| 624 | ap.add_argument("--sweep", type=int, default=0, help="also run the context sweep up to this many prompt tokens") |
| 625 | ap.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "")) |
| 626 | ap.add_argument("--json", action="store_true", help="print one JSON line per run instead of a table") |
| 627 | a = ap.parse_args(argv) |
| 628 | u = urlsplit(a.url.rstrip("/")) |
| 629 | if u.scheme != "http" or not u.hostname: |
| 630 | sys.exit("url must be http://host:port (put a TLS server behind a local proxy)") |
| 631 | path = (u.path or "") + "/v1/chat/completions" |
| 632 | headers = {"Authorization": "Bearer " + a.api_key} if a.api_key else {} |
| 633 | port = u.port or 80 |
| 634 | |
| 635 | def one(prompt, mt, n=1): |
| 636 | t0 = time.monotonic() |
| 637 | res, ths, cancel = [None] * n, [], threading.Event() |
| 638 | for i in range(n): |
| 639 | def go(i=i): |
| 640 | res[i] = measure(u.hostname, port, path, headers, a.model, run_messages(prompt, secrets.token_hex(4)), |
| 641 | mt, lambda t, s: None, cancel, 600, 3600) |
| 642 | ths.append(threading.Thread(target=go)) |
| 643 | ths[-1].start() |
| 644 | for t in ths: |
| 645 | t.join() |
| 646 | return [stats(m, t0) for m in res] |
| 647 | |
| 648 | def show(label, ss, agg=None): |
| 649 | if a.json: |
| 650 | print(json.dumps({"run": label, "load1": load1(), "streams": ss, "aggregate_tps": agg})) |
| 651 | return |
| 652 | for s in ss: |
| 653 | print("%-14s in %6s out %5s ttft %7s ms prefill %8s tok/s decode %7s tok/s total %7s ms %s" |
| 654 | % (label, s["prompt_tokens"], s["completion_tokens"], s["ttft_ms"], s["prefill_tps"], |
| 655 | s["decode_tps"], s["total_ms"], s["finish"])) |
| 656 | if agg is not None: |
| 657 | print("%-14s aggregate %s tok/s over %d streams" % (label, agg, len(ss))) |
| 658 | |
| 659 | print("load1 %s, model %s at %s" % (load1(), a.model, a.url)) |
| 660 | for name in (PRESETS if a.preset == "all" else [a.preset]): |
| 661 | show(name, one(PRESETS[name]["prompt"], PRESETS[name]["max_tokens"])) |
| 662 | if a.streams: |
| 663 | n = max(2, min(8, a.streams)) |
| 664 | ss = one(PRESETS["medium"]["prompt"], PRESETS["medium"]["max_tokens"], n) |
| 665 | lasts, starts = [s["last_ms"] for s in ss if s["last_ms"]], [s["start_ms"] for s in ss if s["start_ms"] is not None] |
| 666 | agg = round(sum(s["completion_tokens"] or 0 for s in ss) * 1000.0 / (max(lasts) - min(starts)), 1) \ |
| 667 | if lasts and starts else None |
| 668 | show("parallel-%d" % n, ss, agg) |
| 669 | if a.sweep: |
| 670 | for size in sweep_sizes(a.sweep): |
| 671 | show("sweep-%d" % size, one(sweep_prompt(size), SWEEP_OUT)) |
| 672 | |
| 673 | |
| 674 | if __name__ == "__main__": |
| 675 | if len(sys.argv) > 1 and sys.argv[1] == "bench": |
| 676 | bench(sys.argv[2:]) |
| 677 | else: |
| 678 | sys.exit("usage: allen_infer.py bench URL --model NAME [--preset all|short|medium|long] [--streams N] [--sweep TOKENS]") |