Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/scheduler.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / scheduler.py` 289 lines · 11453 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """MojoLlama Scheduler — vLLM-style continuous batching proxy. 3 4 Collects requests over a time window, batches them into a single 5 forward pass on llama.cpp, and distributes responses back. 6 Provides higher throughput than individual dispatch by maximizing 7 weight reuse across concurrent sequences. 8 9 Architecture: 10 ┌──────────┐ window ┌──────────┐ batch ┌───────────┐ 11 │ Clients │ ──────────→ │ Batcher │ ──────────→ │ llama.cpp │ 12 │ (HTTP) │ ←────────── │ (Queue) │ ←────────── │ (np=high) │ 13 └──────────┘ responses └──────────┘ └───────────┘ 14 """ 15 16 import json 17 import time 18 import uuid 19 import threading 20 import queue 21 import urllib.request 22 import http.client 23 from http.server import HTTPServer, BaseHTTPRequestHandler 24 25 BACKEND_URL = "http://127.0.0.1:8081" 26 BATCH_WINDOW = 0.050 # 50ms — collect requests before dispatching batch 27 MAX_BATCH = 64 # max sequences per batch 28 BACKEND_NP = 64 # must match llama.cpp -np setting 29 30 # ─── Batcher ────────────────────────────────────────────────────────── 31 32 class Batcher: 33 """Collects individual requests into batches for llama.cpp.""" 34 35 def __init__(self, backend_url=BACKEND_URL, max_batch=MAX_BATCH, 36 window=BATCH_WINDOW): 37 self.backend_url = backend_url 38 self.max_batch = max_batch 39 self.window = window 40 self._pending = [] # [(prompt, max_tokens, result_queue), ...] 41 self._lock = threading.Lock() 42 self._flush_event = threading.Event() 43 self._running = True 44 self._thread = threading.Thread(target=self._run, daemon=True) 45 self._thread.start() 46 self._metrics = {"batches": 0, "total_requests": 0, "avg_batch_size": 0} 47 self._conn_pool = queue.Queue() 48 49 def _get_conn(self): 50 try: 51 return self._conn_pool.get_nowait() 52 except queue.Empty: 53 return http.client.HTTPConnection("127.0.0.1", 8081, timeout=120) 54 55 def _return_conn(self, conn): 56 try: 57 self._conn_pool.put_nowait(conn) 58 except queue.Full: 59 try: conn.close() 60 except: pass 61 62 def submit(self, prompt, max_tokens, temperature=0.7): 63 """Submit a request. Returns a queue that will receive the result.""" 64 result_queue = queue.Queue() 65 with self._lock: 66 self._pending.append({ 67 "prompt": prompt, 68 "max_tokens": max_tokens, 69 "temperature": temperature, 70 "result": result_queue, 71 "id": str(uuid.uuid4())[:8], 72 }) 73 self._flush_event.set() # wake up batcher 74 return result_queue 75 76 def _run(self): 77 """Main batch loop: collect requests, dispatch batch, return results.""" 78 while self._running: 79 self._flush_event.wait() 80 self._flush_event.clear() 81 82 while True: 83 # Collect a batch 84 batch = self._drain_pending() 85 if not batch: 86 break 87 88 # Wait a bit more for more requests (up to window time) 89 time.sleep(self.window) 90 more = self._drain_pending() 91 batch.extend(more) 92 93 # Dispatch 94 self._dispatch_batch(batch) 95 96 def _drain_pending(self): 97 """Thread-safe drain of pending queue.""" 98 with self._lock: 99 batch = list(self._pending) 100 self._pending.clear() 101 return batch 102 103 def _dispatch_batch(self, batch): 104 """Send a batch of prompts to llama.cpp.""" 105 if not batch: 106 return 107 108 # Build a single prompt by concatenating all prompts 109 # Format: one conversation per batch entry 110 # llama.cpp handles multiple sequences via its internal batcher 111 # For batch efficiency, we craft a single prompt that produces 112 # all required responses, then split them. 113 # 114 # Simpler approach: just dispatch concurrently via HTTP, 115 # but schedule carefully to maximize batch utilization. 116 117 # Track metrics 118 with self._lock: 119 self._metrics["batches"] += 1 120 self._metrics["total_requests"] += len(batch) 121 self._metrics["avg_batch_size"] = ( 122 self._metrics["avg_batch_size"] * 0.9 + len(batch) * 0.1 123 ) 124 125 # Dispatch each request individually (using np for parallelism) 126 # A true batcher would merge all prompts into one forward pass, 127 # but llama.cpp's internal continuous batching already handles 128 # multiple sequences efficiently when np is set high. 129 threads = [] 130 for req in batch: 131 t = threading.Thread(target=self._dispatch_one, args=(req,)) 132 t.start() 133 threads.append(t) 134 for t in threads: 135 t.join() 136 137 def _dispatch_one(self, req): 138 """Send one request to llama.cpp.""" 139 data = json.dumps({ 140 "messages": [{"role": "user", "content": req["prompt"]}], 141 "max_tokens": req["max_tokens"], 142 "temperature": req["temperature"], 143 "stream": False, 144 }).encode() 145 146 conn = self._get_conn() 147 try: 148 conn.request("POST", "/v1/chat/completions", body=data, 149 headers={"Content-Type": "application/json"}) 150 resp = conn.getresponse() 151 raw = resp.read() 152 resp.close() 153 result = json.loads(raw.decode("utf-8")) 154 text = (result.get("choices", [{}])[0] 155 .get("message", {}).get("content", "")) 156 usage = result.get("usage", {}) 157 req["result"].put({ 158 "ok": True, "text": text, 159 "tokens": usage.get("completion_tokens", 0), 160 "prompt_tokens": usage.get("prompt_tokens", 0), 161 }) 162 except Exception as e: 163 req["result"].put({"ok": False, "error": str(e)}) 164 finally: 165 self._return_conn(conn) 166 167 def get_metrics(self): 168 with self._lock: 169 return dict(self._metrics) 170 171 def stop(self): 172 self._running = False 173 self._flush_event.set() 174 175 176 # ─── HTTP Handler ───────────────────────────────────────────────────── 177 178 batcher = Batcher() 179 180 class SchedulerHandler(BaseHTTPRequestHandler): 181 """HTTP handler that routes through the batcher.""" 182 183 def log_message(self, format, *args): 184 pass # reduce noise 185 186 def do_GET(self): 187 if self.path == "/health": 188 self._send_json({"status": "ok", "batcher": "active"}) 189 elif self.path == "/metrics": 190 self._send_json(batcher.get_metrics()) 191 else: 192 self._send_error(404) 193 194 def do_POST(self): 195 if self.path in ("/v1/chat/completions", "/api/chat"): 196 content_len = int(self.headers.get("Content-Length", 0)) 197 body = json.loads(self.rfile.read(content_len)) 198 messages = body.get("messages", []) 199 max_tokens = body.get("max_tokens", 256) 200 temperature = body.get("temperature", 0.7) 201 prompt = messages[-1]["content"] if messages else "" 202 203 # Submit to batcher 204 result_queue = batcher.submit(prompt, max_tokens, temperature) 205 result = result_queue.get(timeout=120) 206 207 if result["ok"]: 208 if self.path == "/api/chat": 209 # SSE streaming 210 self.send_response(200) 211 self.send_header("Content-Type", "text/event-stream") 212 self.send_header("Access-Control-Allow-Origin", "*") 213 self.end_headers() 214 text = result["text"] 215 # Send tokens gradually (simulate streaming from batch) 216 for token in text.split(" "): 217 chunk = json.dumps({ 218 "choices": [{"delta": {"content": token + " "}, "index": 0}] 219 }) 220 self.wfile.write(f"data: {chunk}\n\n".encode()) 221 self.wfile.flush() 222 time.sleep(0.01) # throttle for UX 223 self.wfile.write(b"data: [DONE]\n\n") 224 else: 225 self._send_json({ 226 "id": f"chatcmpl-{uuid.uuid4().hex[:8]}", 227 "object": "chat.completion", 228 "choices": [{ 229 "index": 0, 230 "message": {"role": "assistant", "content": result["text"]}, 231 "finish_reason": "stop", 232 }], 233 "usage": { 234 "prompt_tokens": result.get("prompt_tokens", 0), 235 "completion_tokens": result.get("tokens", 0), 236 "total_tokens": result.get("prompt_tokens", 0) + result.get("tokens", 0), 237 }, 238 "backend": "mojollama-scheduler", 239 }) 240 else: 241 self._send_error(f"Batch error: {result.get('error', 'unknown')}", 502) 242 else: 243 self._send_error(404) 244 245 def _send_json(self, data, status=200): 246 body = json.dumps(data).encode() 247 self.send_response(status) 248 self.send_header("Content-Type", "application/json") 249 self.send_header("Access-Control-Allow-Origin", "*") 250 self.send_header("Content-Length", str(len(body))) 251 self.end_headers() 252 self.wfile.write(body) 253 254 def _send_error(self, msg, status=500): 255 self._send_json({"error": msg}, status) 256 257 258 def main(): 259 from argparse import ArgumentParser 260 parser = ArgumentParser(description="MojoLlama Scheduler Proxy") 261 parser.add_argument("--port", type=int, default=8090) 262 parser.add_argument("--backend", default="http://127.0.0.1:8081") 263 parser.add_argument("--batch-window", type=float, default=0.05) 264 parser.add_argument("--max-batch", type=int, default=64) 265 args = parser.parse_args() 266 267 global batcher, BACKEND_URL, BATCH_WINDOW, MAX_BATCH 268 BACKEND_URL = args.backend 269 BATCH_WINDOW = args.batch_window 270 MAX_BATCH = args.max_batch 271 batcher = Batcher(args.backend, args.max_batch, args.batch_window) 272 273 server = HTTPServer(("0.0.0.0", args.port), SchedulerHandler) 274 print(f"MojoLlama Scheduler on :{args.port} → {args.backend}") 275 print(f" Batch window: {args.batch_window*1000:.0f}ms") 276 print(f" Max batch: {args.max_batch}") 277 print(f" /v1/chat/completions — batched completions") 278 print(f" /api/chat — streaming batched completions") 279 print(f" /metrics — batch metrics") 280 print(f" /health — health check") 281 try: 282 server.serve_forever() 283 except KeyboardInterrupt: 284 batcher.stop() 285 server.server_close() 286 287 288 if __name__ == "__main__": 289 main()