"""Optional: concurrent HTTP requests to mlx_lm.server, compared with batch_generate. Starts mlx_lm.server on localhost, sends 1, 4 and 8 simultaneous streaming chat requests (greedy, max_tokens 256, EOS banned via logit_bias so requests run to the limit), records time to first token and end-to-end throughput, then stops the server. Stdlib only. """ import argparse import http.client import json import os import subprocess import sys import threading import time from pathlib import Path def eos_ids(repo): from huggingface_hub import snapshot_download snap = Path(snapshot_download(repo, local_files_only=True)) ids = set() for name in ("generation_config.json", "config.json"): f = snap / name if f.exists(): v = json.loads(f.read_text()).get("eos_token_id") ids.update(v if isinstance(v, list) else [v] if v is not None else []) return sorted(ids) def request(port, content, max_tokens, bias, result): body = { "messages": [{"role": "user", "content": content}], "max_tokens": max_tokens, "temperature": 0.0, "stream": True, "stream_options": {"include_usage": True}, "logit_bias": bias, "chat_template_kwargs": {"enable_thinking": False}, } t0 = time.perf_counter() conn = http.client.HTTPConnection("127.0.0.1", port, timeout=600) conn.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"}) resp = conn.getresponse() first, chunks, usage = None, 0, None for line in resp: line = line.decode().strip() if not line.startswith("data:") or line == "data: [DONE]": continue msg = json.loads(line[5:]) if msg.get("usage"): usage = msg["usage"] for ch in msg.get("choices", []): if (ch.get("delta") or {}).get("content"): chunks += 1 if first is None: first = time.perf_counter() t1 = time.perf_counter() conn.close() result.update( t0=t0, t1=t1, ttft_s=None if first is None else first - t0, completion_tokens=(usage or {}).get("completion_tokens", chunks), cached_tokens=((usage or {}).get("prompt_tokens_details") or {}).get("cached_tokens"), content_chunks=chunks, ) def burst(port, prompts, tag, max_tokens, bias): # A unique first line per request so the server's prompt cache cannot reuse an earlier prefill. results = [{} for _ in prompts] threads = [ threading.Thread(target=request, args=(port, f"Request {tag}-{i}.\n\n{p}", max_tokens, bias, results[i])) for i, p in enumerate(prompts) ] for t in threads: t.start() for t in threads: t.join() start = min(r["t0"] for r in results) end = max(r["t1"] for r in results) tokens = sum(r["completion_tokens"] for r in results) return { "concurrency": len(prompts), "wall_s": end - start, "completion_tokens": [r["completion_tokens"] for r in results], "cached_tokens": [r["cached_tokens"] for r in results], "ttft_s": [r["ttft_s"] for r in results], "end_to_end_tps": tokens / (end - start), } def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--out", required=True) ap.add_argument("--python", default=sys.executable) ap.add_argument("--port", type=int, default=8765) ap.add_argument("--concurrency", default="1,4,8") ap.add_argument("--reps", type=int, default=2) ap.add_argument("--max-tokens", type=int, default=256) ap.add_argument("--prompts", default="prompts/prompts.json") ap.add_argument("--deadline", type=float, default=None) args = ap.parse_args() prompts = json.loads(Path(args.prompts).read_text()) bias = {str(i): -1e9 for i in eos_ids(args.model)} out = {"model": args.model, "eos_banned": list(bias), "bursts": [], "skipped": []} log = open(Path(args.out).with_suffix(".server.log"), "w") server = subprocess.Popen( [args.python, "-m", "mlx_lm.server", "--model", args.model, "--port", str(args.port), "--max-tokens", str(args.max_tokens), "--decode-concurrency", "16", "--prompt-concurrency", "16", "--temp", "0"], stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, HF_HUB_OFFLINE="1"), ) try: for _ in range(240): try: c = http.client.HTTPConnection("127.0.0.1", args.port, timeout=2) c.request("GET", "/health") if c.getresponse().status == 200: break except OSError: pass if server.poll() is not None: raise RuntimeError("mlx_lm.server exited early, see server log") time.sleep(0.5) else: raise RuntimeError("mlx_lm.server did not become healthy") burst(args.port, prompts[:2], "warmup", 16, bias) # loads the model, compiles kernels last = 0.0 for rep in range(args.reps): for c in [int(x) for x in args.concurrency.split(",")]: if args.deadline and time.time() + max(last, 30) * c * 1.5 > args.deadline: out["skipped"].append({"rep": rep, "concurrency": c, "reason": "time budget"}) continue r = burst(args.port, prompts[:c], f"r{rep}c{c}", args.max_tokens, bias) last = r["wall_s"] / c r["rep"] = rep out["bursts"].append(r) print(f"[server] rep {rep} c={c}: {r['end_to_end_tps']:.1f} tok/s end-to-end, " f"tokens {r['completion_tokens']}", flush=True) Path(args.out).write_text(json.dumps(out)) finally: server.terminate() try: server.wait(timeout=30) except subprocess.TimeoutExpired: server.kill() log.close() Path(args.out).write_text(json.dumps(out)) if __name__ == "__main__": main()