MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / benchmarks / server_batch_moe.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Continuous batching server for MoE models using PagedAttention KV cache. |
| 3 | Adapted from server_batch.py (dense) and server_moe.py (single-request MoE). |
| 4 | Uses TurboEngineV7MoE + cengine_batch_instr.so with batch_forward(B≥1). |
| 5 | """ |
| 6 | import sys, os, json, time, threading, queue, ctypes |
| 7 | import numpy as np |
| 8 | from http.server import HTTPServer, BaseHTTPRequestHandler |
| 9 | from urllib.parse import urlparse |
| 10 | from socketserver import ThreadingMixIn |
| 11 | from transformers import AutoTokenizer |
| 12 | |
| 13 | MODEL_PATH = sys.argv[1] if len(sys.argv) > 1 else '/tmp/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf' |
| 14 | PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8080 |
| 15 | B_MAX = 4 # maximum concurrent sequences in a batch |
| 16 | |
| 17 | # ── Engine ── |
| 18 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'kernels')) |
| 19 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 20 | e = TurboEngineV7MoE(MODEL_PATH, 32) |
| 21 | L=e.n_layers; N=e.n_embd; NH=e.n_head; NKH=e.n_kv_head; HD=e.head_dim; FF=e.n_ff; V=e.vocab_size |
| 22 | NE=e.n_experts; NK=e.n_experts_per_tok; moe_int=e.n_ff_expert |
| 23 | S = max(N, NH*HD, FF, NKH*HD, moe_int); BOS=1; EOS=2 |
| 24 | print(f"Engine: {L}L/{N}D/{FF}FF/{NH}H/{NKH}KV | MoE {NE}×{NK} | V={V} | B_MAX={B_MAX}", flush=True) |
| 25 | |
| 26 | # ── C library ── |
| 27 | lib = ctypes.CDLL(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'kernels', 'cengine_batch_instr.so')) |
| 28 | cv=ctypes.c_void_p; ci=ctypes.c_int; cf=ctypes.c_float |
| 29 | |
| 30 | # ── PagedAttention-backed KVBlock (Python side matches C struct) ── |
| 31 | class PageTable(ctypes.Structure): |
| 32 | _fields_ = [ |
| 33 | ('page_size', ci), ('n_pages', ci), ('pages', cv), ('table', cv), |
| 34 | ('free_pages', cv), ('free_count', ci), ('_nkh', ci), ('_hd', ci), ('_n_layers', ci), |
| 35 | ] |
| 36 | |
| 37 | class KVBlock(ctypes.Structure): |
| 38 | _fields_ = [ |
| 39 | ('k', cv), ('v', cv), ('n_blocks', ci), |
| 40 | ('seq_len', ci * 64), ('block_map', (ci * 1024) * 64), |
| 41 | ('pt', PageTable), |
| 42 | ] |
| 43 | |
| 44 | class BC(ctypes.Structure): |
| 45 | _fields_ = [ |
| 46 | ("L",ci),("N",ci),("NH",ci),("NKH",ci),("HD",ci),("FF",ci),("V",ci),("eps",cf), |
| 47 | ("wQ",cv),("wK",cv),("wV",cv),("wO",cv),("wG",cv),("wU",cv),("wD",cv), |
| 48 | ("wAN",cv),("wFN",cv),("nQ",cv),("nK",cv),("nV",cv),("nO",cv),("nG",cv),("nU",cv),("nD",cv), |
| 49 | ("nc",ci),("emb",cv),("onw",cv),("wOut",cv),("outNR",ci),("outNC",ci),("outQuant",ci), |
| 50 | ("kv_array",cv),("logits",cv), |
| 51 | ("n_experts",ci),("n_experts_per_tok",ci),("moe_intermediate",ci), |
| 52 | ("w_gate_inp",cv),("w_gate_exps",cv),("w_up_exps",cv),("w_down_exps",cv), |
| 53 | ("gate_exp_quant",ci),("up_exp_quant",ci),("down_exp_quant",ci), |
| 54 | ("q_quant",cv),("k_quant",cv),("v_quant",cv),("o_quant",cv), |
| 55 | ("g_quant",cv),("u_quant",cv),("d_quant",cv),("emb_quant",ci), |
| 56 | ("wQK",cv),("qk_quant",cv), |
| 57 | ("cos_table",cv),("sin_table",cv),("max_ctx",ci), |
| 58 | ("workspace",cv),("ws_size",ci), |
| 59 | ] |
| 60 | |
| 61 | lib.kv_init.argtypes=[cv,ci,ci,ci]; lib.kv_init.restype=None |
| 62 | lib.batch_forward.argtypes=[cv,cv,ci,cv]; lib.batch_forward.restype=None |
| 63 | |
| 64 | # ── Build per-layer pointer arrays (from server_moe.py) ── |
| 65 | def wa(arr): return (cv*L)(*[ctypes.cast(a,cv) for a in arr]) |
| 66 | def ia(arr): return (ci*L)(*[int(a) for a in arr]) |
| 67 | |
| 68 | wQ_arr=[0]*L; wK_arr=[0]*L; wV_arr=[0]*L; wO_arr=[0]*L |
| 69 | wG_arr=[0]*L; wU_arr=[0]*L; wD_arr=[0]*L |
| 70 | wAN_arr=[0]*L; wFN_arr=[0]*L |
| 71 | wQK_arr=[0]*L; qkQ_arr=[0]*L |
| 72 | nQ_arr=[0]*L; nK_arr=[0]*L; nV_arr=[0]*L; nO_arr=[0]*L; nG_arr=[0]*L; nU_arr=[0]*L; nD_arr=[0]*L |
| 73 | qQ_arr=[0]*L; qK_arr=[0]*L; qV_arr=[0]*L; qO_arr=[0]*L; qG_arr=[0]*L; qU_arr=[0]*L; qD_arr=[0]*L |
| 74 | |
| 75 | for i,lw in enumerate(e._layers): |
| 76 | wQ_arr[i]=lw.attn_q_raw; nQ_arr[i]=lw.attn_q_nr.value; qQ_arr[i]=lw.attn_q_qt.value |
| 77 | wK_arr[i]=lw.attn_k_raw; nK_arr[i]=lw.attn_k_nr.value; qK_arr[i]=lw.attn_k_qt.value |
| 78 | wV_arr[i]=lw.attn_v_raw; nV_arr[i]=lw.attn_v_nr.value; qV_arr[i]=lw.attn_v_qt.value |
| 79 | wO_arr[i]=lw.attn_out_raw; nO_arr[i]=lw.attn_out_nr.value; qO_arr[i]=lw.attn_out_qt.value |
| 80 | wAN_arr[i]=lw.attn_norm_w.ctypes.data_as(cv); wFN_arr[i]=lw.ffn_norm_w.ctypes.data_as(cv) |
| 81 | if hasattr(lw,'attn_qk_use_c') and lw.attn_qk_use_c: |
| 82 | wQK_arr[i]=lw.attn_qk_raw; qkQ_arr[i]=lw.attn_qk_qt.value |
| 83 | else: |
| 84 | wQK_arr[i]=cv(0); qkQ_arr[i]=0 |
| 85 | for i,me in enumerate(e._moe_layers): |
| 86 | wG_arr[i]=me.gate_raw[0].ctypes.data_as(cv) if me.gate_raw else cv(0) |
| 87 | wU_arr[i]=me.up_raw[0].ctypes.data_as(cv) if me.up_raw else cv(0) |
| 88 | wD_arr[i]=me.down_raw[0].ctypes.data_as(cv) if me.down_raw else cv(0) |
| 89 | nG_arr[i]=me.gate_nr.value; nU_arr[i]=me.up_nr.value; nD_arr[i]=me.down_nr.value |
| 90 | qG_arr[i]=me.gate_qt.value; qU_arr[i]=me.up_qt.value; qD_arr[i]=me.down_qt.value |
| 91 | |
| 92 | w_gate_inp_arr=[0]*L; w_gate_exps_arr=[0]*L; w_up_exps_arr=[0]*L; w_down_exps_arr=[0]*L |
| 93 | for i,lw in enumerate(e._layers): |
| 94 | if e.is_moe: |
| 95 | me = e._moe_layers[i] |
| 96 | if me.router_raw is not None: |
| 97 | w_gate_inp_arr[i] = me.router_raw.ctypes.data_as(cv) |
| 98 | elif me.router_f32 is not None: |
| 99 | w_gate_inp_arr[i] = me.router_f32.ctypes.data_as(cv) |
| 100 | else: |
| 101 | w_gate_inp_arr[i] = cv(0) |
| 102 | gate_raw_t = me.gate_raw |
| 103 | up_raw_t = me.up_raw |
| 104 | down_raw_t = me.down_raw |
| 105 | if gate_raw_t and len(gate_raw_t) > 0: |
| 106 | w_gate_exps_arr[i] = gate_raw_t[0].ctypes.data_as(cv) |
| 107 | else: |
| 108 | w_gate_exps_arr[i] = cv(0) |
| 109 | if up_raw_t and len(up_raw_t) > 0: |
| 110 | w_up_exps_arr[i] = up_raw_t[0].ctypes.data_as(cv) |
| 111 | else: |
| 112 | w_up_exps_arr[i] = cv(0) |
| 113 | if down_raw_t and len(down_raw_t) > 0: |
| 114 | w_down_exps_arr[i] = down_raw_t[0].ctypes.data_as(cv) |
| 115 | else: |
| 116 | w_down_exps_arr[i] = cv(0) |
| 117 | |
| 118 | if e.is_moe and len(e._moe_layers) > 0: |
| 119 | me = e._moe_layers[0] |
| 120 | gate_qt = me.gate_qt.value; up_qt = me.up_qt.value; down_qt = me.down_qt.value |
| 121 | else: |
| 122 | gate_qt = 2; up_qt = 2; down_qt = 2 |
| 123 | print(f"Expert quant types: gate={gate_qt} up={up_qt} down={down_qt}", flush=True) |
| 124 | |
| 125 | # ── Build BC struct ── |
| 126 | bc=BC() |
| 127 | for attr,val in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',e.eps), |
| 128 | ('nc',N),('outNR',V),('outNC',N),('outQuant',8), |
| 129 | ('n_experts',NE),('n_experts_per_tok',NK),('moe_intermediate',moe_int), |
| 130 | ('gate_exp_quant',gate_qt),('up_exp_quant',up_qt),('down_exp_quant',down_qt), |
| 131 | ('emb_quant',0)]: |
| 132 | setattr(bc,attr,val) |
| 133 | bc.wQ=ctypes.cast(wa(wQ_arr),cv); bc.wK=ctypes.cast(wa(wK_arr),cv); bc.wV=ctypes.cast(wa(wV_arr),cv); bc.wO=ctypes.cast(wa(wO_arr),cv) |
| 134 | bc.wG=ctypes.cast(wa(wG_arr),cv); bc.wU=ctypes.cast(wa(wU_arr),cv); bc.wD=ctypes.cast(wa(wD_arr),cv) |
| 135 | bc.wAN=ctypes.cast(wa(wAN_arr),cv); bc.wFN=ctypes.cast(wa(wFN_arr),cv) |
| 136 | bc.wQK=ctypes.cast(wa(wQK_arr),cv); bc.qk_quant=ctypes.cast(ia(qkQ_arr),cv) |
| 137 | bc.nQ=ctypes.cast(ia(nQ_arr),cv); bc.nK=ctypes.cast(ia(nK_arr),cv); bc.nV=ctypes.cast(ia(nV_arr),cv); bc.nO=ctypes.cast(ia(nO_arr),cv) |
| 138 | bc.nG=ctypes.cast(ia(nG_arr),cv); bc.nU=ctypes.cast(ia(nU_arr),cv); bc.nD=ctypes.cast(ia(nD_arr),cv) |
| 139 | bc.q_quant=ctypes.cast(ia(qQ_arr),cv); bc.k_quant=ctypes.cast(ia(qK_arr),cv); bc.v_quant=ctypes.cast(ia(qV_arr),cv); bc.o_quant=ctypes.cast(ia(qO_arr),cv) |
| 140 | bc.g_quant=ctypes.cast(ia(qG_arr),cv); bc.u_quant=ctypes.cast(ia(qU_arr),cv); bc.d_quant=ctypes.cast(ia(qD_arr),cv) |
| 141 | bc.w_gate_inp=ctypes.cast(wa(w_gate_inp_arr),cv); bc.w_gate_exps=ctypes.cast(wa(w_gate_exps_arr),cv) |
| 142 | bc.w_up_exps=ctypes.cast(wa(w_up_exps_arr),cv); bc.w_down_exps=ctypes.cast(wa(w_down_exps_arr),cv) |
| 143 | bc.emb=e.emb.ctypes.data_as(cv) if hasattr(e,'emb') else cv(0) |
| 144 | bc.onw=e._out_norm_w.ctypes.data_as(cv) if hasattr(e,'_out_norm_w') else cv(0) |
| 145 | bc.wOut=ctypes.cast(e._out_raw,cv) if hasattr(e,'_out_raw') else cv(0) |
| 146 | |
| 147 | # RoPE precompute |
| 148 | max_ctx=4096; hd2=HD//2 |
| 149 | freq = e.rope_freq_base ** (np.arange(0, HD, 2, dtype=np.float32) / HD) |
| 150 | ang = np.arange(max_ctx, dtype=np.float32).reshape(-1, 1) / freq.reshape(1, -1) |
| 151 | cos_all = np.cos(ang).astype(np.float32).reshape(-1) |
| 152 | sin_all = np.sin(ang).astype(np.float32).reshape(-1) |
| 153 | cos_t = cos_all.ctypes.data_as(cv) |
| 154 | sin_t = sin_all.ctypes.data_as(cv) |
| 155 | bc.cos_table=cos_t; bc.sin_table=sin_t; bc.max_ctx=max_ctx |
| 156 | print(f"RoPE table: {max_ctx}x{hd2} = {len(cos_all)*4*2//1024}KB", flush=True) |
| 157 | |
| 158 | # BC workspace: replaces __builtin_alloca for kct/vct in batch_forward |
| 159 | # Size = 2 * max_ctx * NKH * HD (kct + vct) + safety margin |
| 160 | ws_bc_size = 2 * max_ctx * NKH * HD + 4096 |
| 161 | ws_bc = np.zeros(ws_bc_size, dtype=np.float32) |
| 162 | bc.workspace = ws_bc.ctypes.data_as(cv) |
| 163 | bc.ws_size = ws_bc_size |
| 164 | print(f"BC workspace: {ws_bc_size} floats = {ws_bc_size*4//1024}KB", flush=True) |
| 165 | |
| 166 | # ── Shared buffers ── |
| 167 | # Allocate enough workspace for B_MAX concurrent sequences |
| 168 | ws = np.zeros(B_MAX * 12 * S, dtype=np.float32) |
| 169 | logits_buf = np.zeros(B_MAX * V, dtype=np.float32) |
| 170 | |
| 171 | def mk_kv(): |
| 172 | kv = KVBlock() |
| 173 | lib.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) |
| 174 | return kv |
| 175 | |
| 176 | def sample_token(logits, temperature=0.0): |
| 177 | safe = np.nan_to_num(logits, nan=-1e10, posinf=1e10, neginf=-1e10) |
| 178 | if temperature <= 0: |
| 179 | return int(np.argmax(safe)) |
| 180 | safe -= safe.max() |
| 181 | p = np.exp(np.clip(safe / temperature, -50, 50)) |
| 182 | p[np.isnan(p)] = 0 |
| 183 | s = p.sum() |
| 184 | return int(np.random.choice(len(p), p=p/s)) if s > 0 else 0 |
| 185 | |
| 186 | # ── Tokenizer ── |
| 187 | print(f"Loading tokenizer from /tmp/qwen3-tokenizer/...", flush=True) |
| 188 | tokenizer = AutoTokenizer.from_pretrained('/tmp/qwen3-tokenizer/') |
| 189 | tokenizer.bos_token_id = BOS |
| 190 | tokenizer.eos_token_id = EOS |
| 191 | print(f"Tokenizer loaded, vocab={tokenizer.vocab_size}", flush=True) |
| 192 | |
| 193 | # ── Sequence state ── |
| 194 | class Sequence: |
| 195 | __slots__ = ('kv','tokens','gen_tokens','done','result','event','max_tokens','temperature','token_queue','stream') |
| 196 | def __init__(self): |
| 197 | self.kv = mk_kv() |
| 198 | self.tokens = [] |
| 199 | self.gen_tokens = [] |
| 200 | self.done = False |
| 201 | self.result = None |
| 202 | self.event = threading.Event() |
| 203 | self.max_tokens = 100 |
| 204 | self.temperature = 0.0 |
| 205 | self.token_queue = None |
| 206 | self.stream = False |
| 207 | |
| 208 | # ── Scheduler ── |
| 209 | pending = queue.Queue() |
| 210 | active_slots = [None] * B_MAX |
| 211 | forward_lock = threading.Lock() |
| 212 | |
| 213 | def run_scheduler(): |
| 214 | global bc, ws, logits_buf, active_slots |
| 215 | while True: |
| 216 | # Fill empty slots from pending queue |
| 217 | while not pending.empty(): |
| 218 | try: |
| 219 | seq = pending.get_nowait() |
| 220 | except queue.Empty: |
| 221 | break |
| 222 | for i in range(B_MAX): |
| 223 | if active_slots[i] is None: |
| 224 | active_slots[i] = seq |
| 225 | break |
| 226 | |
| 227 | # Collect active non-done sequences |
| 228 | batch = [(i, s) for i, s in enumerate(active_slots) if s is not None and not s.done] |
| 229 | if not batch: |
| 230 | time.sleep(0.002) |
| 231 | continue |
| 232 | |
| 233 | B = len(batch) |
| 234 | tokens_arr = (ci * B)() |
| 235 | kv_ptrs = (cv * B)() |
| 236 | for j, (slot, seq) in enumerate(batch): |
| 237 | tokens_arr[j] = seq.tokens[-1] if seq.tokens else BOS |
| 238 | kv_ptrs[j] = ctypes.cast(ctypes.pointer(seq.kv), cv) |
| 239 | |
| 240 | try: |
| 241 | with forward_lock: |
| 242 | bc.kv_array = ctypes.cast(kv_ptrs, cv) |
| 243 | bc.logits = logits_buf.ctypes.data_as(cv) |
| 244 | lib.batch_forward(ctypes.byref(bc), tokens_arr, ci(B), ws.ctypes.data_as(cv)) |
| 245 | except Exception as ex: |
| 246 | print(f"SCHEDULER forward error: {ex}", flush=True) |
| 247 | import traceback |
| 248 | traceback.print_exc() |
| 249 | continue |
| 250 | |
| 251 | for j, (slot, seq) in enumerate(batch): |
| 252 | logits = logits_buf[j*V:(j+1)*V].copy() |
| 253 | next_tok = sample_token(logits, seq.temperature) |
| 254 | seq.tokens.append(next_tok) |
| 255 | seq.gen_tokens.append(next_tok) |
| 256 | |
| 257 | # Push token to streaming queue if active |
| 258 | if seq.token_queue is not None: |
| 259 | seq.token_queue.put(next_tok) |
| 260 | |
| 261 | if next_tok == EOS or len(seq.gen_tokens) >= seq.max_tokens: |
| 262 | seq.done = True |
| 263 | seq.result = { |
| 264 | 'tokens': seq.gen_tokens.copy(), |
| 265 | 'finish_reason': 'stop' if next_tok == EOS else 'length', |
| 266 | } |
| 267 | if seq.token_queue is not None: |
| 268 | seq.token_queue.put(None) # signal done |
| 269 | seq.event.set() |
| 270 | active_slots[slot] = None |
| 271 | |
| 272 | scheduler_thread = threading.Thread(target=run_scheduler, daemon=True) |
| 273 | scheduler_thread.start() |
| 274 | print(f"Scheduler started (B_MAX={B_MAX})", flush=True) |
| 275 | |
| 276 | # ── HTTP Server ── |
| 277 | class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): |
| 278 | allow_reuse_address = True |
| 279 | daemon_threads = True |
| 280 | |
| 281 | class Handler(BaseHTTPRequestHandler): |
| 282 | def do_GET(self): |
| 283 | path = urlparse(self.path).path |
| 284 | if path == '/health': |
| 285 | # Count active sequences |
| 286 | active_count = sum(1 for s in active_slots if s is not None and not s.done) |
| 287 | pending_count = pending.qsize() |
| 288 | self.send_response(200) |
| 289 | self.send_header('Content-Type', 'application/json') |
| 290 | self.end_headers() |
| 291 | self.wfile.write(json.dumps({ |
| 292 | 'status': 'ok', |
| 293 | 'model': 'mojollama-moe', |
| 294 | 'active_sequences': active_count, |
| 295 | 'pending_requests': pending_count, |
| 296 | 'max_concurrent': B_MAX, |
| 297 | }).encode()) |
| 298 | else: |
| 299 | self.send_error(404) |
| 300 | |
| 301 | def do_POST(self): |
| 302 | path = urlparse(self.path).path |
| 303 | if path != '/v1/completions': |
| 304 | self.send_error(404) |
| 305 | return |
| 306 | |
| 307 | try: |
| 308 | n = int(self.headers.get('Content-Length', 0)) |
| 309 | body = json.loads(self.rfile.read(n)) if n else {} |
| 310 | prompt = body.get('prompt', '') |
| 311 | max_tokens = body.get('max_tokens', 100) |
| 312 | temperature = body.get('temperature', 0.0) |
| 313 | stream = body.get('stream', False) |
| 314 | |
| 315 | # Tokenize |
| 316 | prompt_ids = tokenizer.encode(prompt) if isinstance(prompt, str) else prompt[:512] |
| 317 | prompt_ids = [t for t in prompt_ids if t != BOS] # strip BOS |
| 318 | # Filter out-of-range tokens |
| 319 | prompt_ids = [t for t in prompt_ids if 0 <= t < V][:512] |
| 320 | if not prompt_ids: |
| 321 | prompt_ids = [BOS] |
| 322 | |
| 323 | t0 = time.perf_counter() |
| 324 | |
| 325 | # Create sequence |
| 326 | seq = Sequence() |
| 327 | seq.max_tokens = max_tokens |
| 328 | seq.temperature = temperature |
| 329 | seq.stream = stream |
| 330 | |
| 331 | # Prefill: token-by-token (MoE engine doesn't have prefill_forward) |
| 332 | if prompt_ids: |
| 333 | kva1 = (cv * 1)(ctypes.cast(ctypes.pointer(seq.kv), cv)) |
| 334 | with forward_lock: |
| 335 | bc.kv_array = ctypes.cast(kva1, cv) |
| 336 | bc.logits = logits_buf[0:V].ctypes.data_as(cv) |
| 337 | logits_buf[:V] = 0 |
| 338 | for pt in prompt_ids: |
| 339 | lib.batch_forward(ctypes.byref(bc), (ci * 1)(pt), ci(1), ws.ctypes.data_as(cv)) |
| 340 | |
| 341 | # Sample first generated token |
| 342 | first_tok = sample_token(logits_buf[:V].copy(), temperature) |
| 343 | seq.tokens = [first_tok] |
| 344 | seq.gen_tokens = [first_tok] |
| 345 | |
| 346 | # Streaming mode: send token-by-token via SSE |
| 347 | if stream: |
| 348 | seq.token_queue = queue.Queue() |
| 349 | seq.token_queue.put(first_tok) |
| 350 | |
| 351 | # Enqueue for generation |
| 352 | pending.put(seq) |
| 353 | |
| 354 | if stream: |
| 355 | self.send_response(200) |
| 356 | self.send_header('Content-Type', 'text/event-stream') |
| 357 | self.send_header('Cache-Control', 'no-cache') |
| 358 | self.end_headers() |
| 359 | |
| 360 | while True: |
| 361 | tok = seq.token_queue.get() |
| 362 | if tok is None: |
| 363 | break |
| 364 | chunk_data = json.dumps({ |
| 365 | 'choices': [{ |
| 366 | 'text': tokenizer.decode([tok], skip_special_tokens=True), |
| 367 | 'index': 0, |
| 368 | }] |
| 369 | }) |
| 370 | self.wfile.write(f'data: {chunk_data}\n\n'.encode()) |
| 371 | self.wfile.flush() |
| 372 | |
| 373 | self.wfile.write('data: [DONE]\n\n'.encode()) |
| 374 | t_total = time.perf_counter() - t0 |
| 375 | tok_s = len(seq.gen_tokens) / t_total if t_total > 0 else 0 |
| 376 | generated_text = tokenizer.decode(seq.gen_tokens, skip_special_tokens=True) |
| 377 | print(f" [{len(prompt_ids)}p+{len(seq.gen_tokens)}g {t_total:.1f}s {tok_s:.0f}t/s] '{generated_text[:60]}'", flush=True) |
| 378 | else: |
| 379 | # Non-streaming: wait for completion |
| 380 | if not seq.event.wait(timeout=600): |
| 381 | gen_tokens = seq.gen_tokens[:20] |
| 382 | finish = 'timeout' |
| 383 | elif seq.result is None: |
| 384 | gen_tokens = seq.gen_tokens |
| 385 | finish = 'length' if len(gen_tokens) >= max_tokens else 'stop' |
| 386 | else: |
| 387 | gen_tokens = seq.result['tokens'] |
| 388 | finish = seq.result['finish_reason'] |
| 389 | |
| 390 | t_total = time.perf_counter() - t0 |
| 391 | generated_text = tokenizer.decode(gen_tokens, skip_special_tokens=True) |
| 392 | |
| 393 | res = { |
| 394 | 'id': f'cmpl-{int(time.time())}', |
| 395 | 'object': 'text_completion', |
| 396 | 'model': 'mojollama-moe-batch', |
| 397 | 'choices': [{ |
| 398 | 'text': generated_text, |
| 399 | 'index': 0, |
| 400 | 'finish_reason': finish, |
| 401 | 'logprobs': None, |
| 402 | }], |
| 403 | 'usage': { |
| 404 | 'prompt_tokens': len(prompt_ids), |
| 405 | 'completion_tokens': len(gen_tokens), |
| 406 | 'total_tokens': len(prompt_ids) + len(gen_tokens), |
| 407 | }, |
| 408 | } |
| 409 | |
| 410 | self.send_response(200) |
| 411 | self.send_header('Content-Type', 'application/json') |
| 412 | self.end_headers() |
| 413 | self.wfile.write(json.dumps(res).encode()) |
| 414 | |
| 415 | tok_s = len(gen_tokens) / t_total if t_total > 0 else 0 |
| 416 | print(f" [{len(prompt_ids)}p+{len(gen_tokens)}g {t_total:.1f}s {tok_s:.0f}t/s] '{generated_text[:60]}'", flush=True) |
| 417 | |
| 418 | except Exception as ex: |
| 419 | print(f" [handler] EXCEPTION: {ex}", flush=True) |
| 420 | import traceback |
| 421 | traceback.print_exc() |
| 422 | try: |
| 423 | self.send_response(500) |
| 424 | self.send_header('Content-Type', 'application/json') |
| 425 | self.end_headers() |
| 426 | self.wfile.write(json.dumps({'error': str(ex)}).encode()) |
| 427 | except: |
| 428 | pass |
| 429 | |
| 430 | def log_message(self, *a): pass |
| 431 | |
| 432 | if __name__ == '__main__': |
| 433 | print(f"Serving on 0.0.0.0:{PORT}", flush=True) |
| 434 | print(f" POST /v1/completions (streaming + non-streaming)", flush=True) |
| 435 | print(f" GET /health", flush=True) |
| 436 | server = ThreadedHTTPServer(('0.0.0.0', PORT), Handler) |
| 437 | try: |
| 438 | server.serve_forever() |
| 439 | except KeyboardInterrupt: |
| 440 | print("\nShutdown", flush=True) |