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/kernels/batch_server.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 / kernels / batch_server.py` 191 lines · 6868 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """MojoLlama Multi-Worker Batch Server. 3 4 Spawns N worker processes with K OMP threads each. 5 Routes concurrent inference requests across workers round-robin. 6 Achieves aggregate throughput > single-llama.cpp by utilizing all CPU cores 7 with independent model copies (each reading weights from shared mmap'd files). 8 9 Optimal config for Threadripper 3970X (32C/64T): 8-10 workers × 3 threads. 10 """ 11 import os, sys, time, json, socket, multiprocessing, queue 12 import numpy as np 13 from multiprocessing import Process, Queue, Value, Lock 14 from ctypes import c_bool 15 16 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 17 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 18 19 WORKER_OMP_THREADS = 3 20 NUM_WORKERS = 10 21 MODEL_PATH = None 22 23 def worker_main(worker_id, model_path, request_queue, response_queue, stop_flag): 24 """Worker process: loads model copy and serves inference requests.""" 25 os.environ["OMP_NUM_THREADS"] = str(WORKER_OMP_THREADS) 26 os.environ["OMP_PROC_BIND"] = "close" 27 os.environ["OMP_PLACES"] = "cores" 28 29 # Delay import to avoid forking issues with C extensions 30 from turbo_engine_v7_moe import TurboEngineV7MoE 31 32 try: 33 eng = TurboEngineV7MoE(model_path, n_threads=WORKER_OMP_THREADS) 34 except Exception as e: 35 response_queue.put({ 36 "worker_id": worker_id, 37 "error": f"Engine load failed: {e}", 38 "done": True 39 }) 40 return 41 42 V = int(eng.vocab_size) 43 response_queue.put({"worker_id": worker_id, "ready": True}) 44 45 while not stop_flag.value: 46 try: 47 req = request_queue.get(timeout=0.5) 48 except queue.Empty: 49 continue 50 if req is None: 51 break 52 53 req_id = req.get("id", 0) 54 tokens = req.get("tokens", [0]) 55 n_gen = req.get("n_gen", 1) 56 57 eng.reset() 58 times = [] 59 for i, tok in enumerate(tokens): 60 t0 = time.perf_counter() 61 _, logits = eng.forward([tok]) 62 t1 = time.perf_counter() 63 if i > 0: # skip prompt processing (first token) 64 times.append((t1 - t0) * 1000) 65 66 result = { 67 "worker_id": worker_id, 68 "req_id": req_id, 69 "n_tokens": len(tokens), 70 "ms_per_token": np.mean(times) if times else 0, 71 "tok_s": 1000 / np.mean(times) if times else 0, 72 "max_logit": float(np.max(logits)), 73 } 74 response_queue.put(result) 75 76 response_queue.put({"worker_id": worker_id, "done": True}) 77 78 79 def run_benchmark(model_path, num_workers=10, threads_per_worker=3, 80 tokens_per_request=10, num_requests=50): 81 """Run batch benchmark with multiple workers.""" 82 global WORKER_OMP_THREADS, NUM_WORKERS 83 WORKER_OMP_THREADS = threads_per_worker 84 NUM_WORKERS = num_workers 85 86 request_queue = Queue() 87 response_queue = Queue() 88 stop_flag = Value(c_bool, False) 89 90 workers = [] 91 for i in range(num_workers): 92 p = Process(target=worker_main, args=( 93 i, model_path, request_queue, response_queue, stop_flag)) 94 p.start() 95 workers.append(p) 96 97 # Wait for all workers to be ready 98 ready_count = 0 99 while ready_count < num_workers: 100 resp = response_queue.get() 101 if resp.get("ready"): 102 ready_count += 1 103 print(f" Worker {resp['worker_id']} ready ({ready_count}/{num_workers})", flush=True) 104 105 # Generate tokens for each request (same tokens for all) 106 test_tokens = list(range(tokens_per_request)) 107 108 # Benchmark: send requests round-robin 109 print(f"\n Running {num_requests} requests × {tokens_per_request} tokens across {num_workers} workers...", flush=True) 110 t_start = time.perf_counter() 111 112 for i in range(num_requests): 113 request_queue.put({ 114 "id": i, 115 "tokens": test_tokens, 116 "n_gen": tokens_per_request, 117 }) 118 119 # Collect results 120 results = [] 121 for i in range(num_requests): 122 resp = response_queue.get() 123 results.append(resp) 124 125 t_elapsed = time.perf_counter() - t_start 126 127 # Signal workers to stop 128 stop_flag.value = True 129 for _ in range(num_workers): 130 request_queue.put(None) 131 for p in workers: 132 p.join(timeout=5) 133 if p.is_alive(): 134 p.terminate() 135 136 # Analyze results 137 tok_rates = [r["tok_s"] for r in results if r.get("tok_s", 0) > 0] 138 total_tokens = sum(r["n_tokens"] for r in results if "n_tokens" in r) 139 140 agg_tok_s = total_tokens / t_elapsed if t_elapsed > 0 else 0 141 avg_per_worker = np.mean(tok_rates) if tok_rates else 0 142 143 print(f" Elapsed: {t_elapsed:.2f}s") 144 print(f" Total tokens: {total_tokens}") 145 print(f" Aggregate throughput: {agg_tok_s:.1f} tok/s") 146 print(f" Avg per worker: {avg_per_worker:.1f} tok/s") 147 print(f" Best worker: {max(tok_rates):.1f} tok/s" if tok_rates else "") 148 149 return { 150 "model": os.path.basename(model_path), 151 "workers": num_workers, 152 "threads_per_worker": threads_per_worker, 153 "total_threads": num_workers * threads_per_worker, 154 "total_tokens": total_tokens, 155 "elapsed_s": round(t_elapsed, 2), 156 "aggregate_tok_s": round(agg_tok_s, 1), 157 "avg_per_worker_tok_s": round(avg_per_worker, 1), 158 "per_request": tok_rates, 159 } 160 161 162 if __name__ == "__main__": 163 import argparse 164 parser = argparse.ArgumentParser(description="Multi-worker batch server") 165 parser.add_argument("-m", "--model", required=True, help="GGUF model path") 166 parser.add_argument("-w", "--workers", type=int, default=10, help="Number of workers") 167 parser.add_argument("-t", "--threads", type=int, default=3, help="OMP threads per worker") 168 parser.add_argument("-n", "--n-tokens", type=int, default=10, help="Tokens per request") 169 parser.add_argument("-r", "--n-requests", type=int, default=50, help="Number of requests") 170 args = parser.parse_args() 171 172 print(f"MojoLlama Batch Server") 173 print(f" Model: {args.model}") 174 print(f" Workers: {args.workers} × {args.threads}t = {args.workers*args.threads} total threads") 175 print(f" Tokens/request: {args.n_tokens}") 176 print(f" Requests: {args.n_requests}") 177 178 result = run_benchmark( 179 args.model, args.workers, args.threads, 180 args.n_tokens, args.n_requests) 181 182 print(f"\n{'='*55}") 183 print(f" Result: {result['aggregate_tok_s']} tok/s aggregate") 184 print(f" Per worker avg: {result['avg_per_worker_tok_s']} tok/s") 185 print(f"{'='*55}") 186 187 # Save result 188 result_path = f"/tmp/batch_result_{os.path.basename(args.model)}.json" 189 with open(result_path, "w") as f: 190 json.dump(result, f, indent=2) 191 print(f" Saved to {result_path}")