MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / benchmarks / server_batch_qwen36.py
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Qwen3.6 MXFP4 continuous batching server — B_MAX=10 concurrent users. |
| 4 | Uses C engine batch_forward with full SSM+attention hybrid support. |
| 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 | |
| 12 | MODEL = "/tmp/models/qwen3.6-mxfp4.gguf" |
| 13 | PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080 |
| 14 | B_MAX = 10 # concurrent users |
| 15 | |
| 16 | # ── Engine ── |
| 17 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kernels')) |
| 18 | from turbo_engine_v7_moe import TurboEngineV7MoE |
| 19 | e = TurboEngineV7MoE(MODEL, 32) |
| 20 | 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 |
| 21 | NE=e.n_experts; NK=e.n_experts_per_tok; moe_int=e.n_ff_expert |
| 22 | LT = e.layer_types if hasattr(e, 'layer_types') else None |
| 23 | S = max(N, NH*HD, FF, NKH*HD, moe_int, 8192); BOS=1; EOS=2 |
| 24 | print(f"Engine: {L}L/{N}D/{NH}H/{NKH}KV/{HD}hd | MoE {NE}x{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.abspath(__file__)), 'kernels', 'cengine_batch_instr.so')) |
| 28 | cv=ctypes.c_void_p; ci=ctypes.c_int; cf=ctypes.c_float |
| 29 | |
| 30 | # ── Structs ── |
| 31 | class PageTable(ctypes.Structure): |
| 32 | _fields_=[('page_size',ci),('n_pages',ci),('pages',cv),('table',cv),('free_pages',cv),('free_count',ci),('_nkh',ci),('_hd',ci),('_n_layers',ci)] |
| 33 | class KVBlock(ctypes.Structure): |
| 34 | _fields_=[('k',cv),('v',cv),('n_blocks',ci),('seq_len',ci*64),('block_map',(ci*1024)*64),('pt',PageTable)] |
| 35 | class BC(ctypes.Structure): |
| 36 | _fields_=[ |
| 37 | ('L',ci),('N',ci),('NH',ci),('NKH',ci),('HD',ci),('FF',ci),('V',ci),('eps',cf), |
| 38 | ('wQ',cv),('wK',cv),('wV',cv),('wO',cv),('wG',cv),('wU',cv),('wD',cv), |
| 39 | ('wAN',cv),('wFN',cv),('nQ',cv),('nK',cv),('nV',cv),('nO',cv),('nG',cv),('nU',cv),('nD',cv), |
| 40 | ('nc',ci),('emb',cv),('onw',cv),('wOut',cv),('outNR',ci),('outNC',ci),('outQuant',ci), |
| 41 | ('kv_array',cv),('logits',cv), |
| 42 | ('n_experts',ci),('n_experts_per_tok',ci),('moe_intermediate',ci), |
| 43 | ('w_gate_inp',cv),('w_gate_exps',cv),('w_up_exps',cv),('w_down_exps',cv), |
| 44 | ('gate_exp_quant',ci),('up_exp_quant',ci),('down_exp_quant',ci), |
| 45 | ('q_quant',cv),('k_quant',cv),('v_quant',cv),('o_quant',cv), |
| 46 | ('g_quant',cv),('u_quant',cv),('d_quant',cv),('emb_quant',ci), |
| 47 | ('wQK',cv),('qk_quant',cv),('cos_table',cv),('sin_table',cv),('max_ctx',ci), |
| 48 | ('workspace',cv),('ws_size',ci), |
| 49 | ('rope_dim',ci),('full_attn_interval',ci), |
| 50 | ('wQKV',cv),('qkv_quant',cv),('wAttnG',cv),('attnG_quant',cv), |
| 51 | ('ssm_conv1d',cv),('ssm_a',cv),('ssm_dt_bias',cv),('ssm_alpha',cv), |
| 52 | ('ssm_beta',cv),('ssm_norm',cv),('wSsmOut',cv),('ssm_out_quant',cv),('ssm_state',cv), |
| 53 | ('wSHexpG',cv),('wSHexpU',cv),('wSHexpD',cv), |
| 54 | ('shexp_g_quant',cv),('shexp_u_quant',cv),('shexp_d_quant',cv),('wShexpRouter',cv), |
| 55 | ('layer_types',cv),('n_layers_actual',ci) |
| 56 | ] |
| 57 | |
| 58 | lib.kv_init.argtypes=[cv,ci,ci,ci]; lib.kv_init.restype=None |
| 59 | lib.batch_forward.argtypes=[cv,cv,ci,cv]; lib.batch_forward.restype=None |
| 60 | lib.rope_init.argtypes=[cv,cv,ci,ci,ci]; lib.rope_init.restype=None |
| 61 | |
| 62 | def wa(arr): return (cv*L)(*[ctypes.cast(a,cv) for a in arr]) |
| 63 | def ia(arr): return (ci*L)(*[int(a) for a in arr]) |
| 64 | |
| 65 | # ── Build Qwen3.6 weight arrays ── |
| 66 | print("Building Qwen3.6 weight arrays...", flush=True) |
| 67 | |
| 68 | wQKV=[cv(0)]*L; qkv_qt=[0]*L |
| 69 | wQ_sep=[cv(0)]*L; nQ_sep=[0]*L; qQ_sep=[0]*L |
| 70 | wK_sep=[cv(0)]*L; nK_sep=[0]*L; qK_sep=[0]*L |
| 71 | wV_sep=[cv(0)]*L; nV_sep=[0]*L; qV_sep=[0]*L |
| 72 | wAG=[cv(0)]*L; ag_qt=[0]*L |
| 73 | wO_attn=[cv(0)]*L; nO_attn=[0]*L; qO_attn=[0]*L |
| 74 | wSO=[cv(0)]*L; so_qt=[0]*L |
| 75 | ssm_c1d=[cv(0)]*L; ssm_a=[cv(0)]*L; ssm_db=[cv(0)]*L |
| 76 | ssm_al=[cv(0)]*L; ssm_be=[cv(0)]*L; ssm_nm=[cv(0)]*L |
| 77 | wSHG=[cv(0)]*L; wSHU=[cv(0)]*L; wSHD=[cv(0)]*L; wSHR=[cv(0)]*L |
| 78 | shg_qt=[0]*L; shu_qt=[0]*L; shd_qt=[0]*L |
| 79 | wAN=[0]*L; wFN=[0]*L |
| 80 | wGI=[cv(0)]*L; wGE=[cv(0)]*L; wUE=[cv(0)]*L; wDE=[cv(0)]*L |
| 81 | ns_G=[0]*L; ns_U=[0]*L; ns_D=[0]*L; qt_G=[0]*L; qt_U=[0]*L; qt_D=[0]*L |
| 82 | |
| 83 | for i in range(L): |
| 84 | lw=e._layers[i]; me=e._moe_layers[i] |
| 85 | if hasattr(lw,'attn_qkv_raw') and lw.attn_qkv_raw is not None: |
| 86 | wQKV[i]=lw.attn_qkv_raw; qkv_qt[i]=lw.attn_qkv_qt.value |
| 87 | if hasattr(lw,'attn_q_raw') and lw.attn_q_raw is not None: |
| 88 | wQ_sep[i]=lw.attn_q_raw; nQ_sep[i]=lw.attn_q_nr.value; qQ_sep[i]=lw.attn_q_qt.value |
| 89 | if hasattr(lw,'attn_k_raw') and lw.attn_k_raw is not None: |
| 90 | wK_sep[i]=lw.attn_k_raw; nK_sep[i]=lw.attn_k_nr.value; qK_sep[i]=lw.attn_k_qt.value |
| 91 | if hasattr(lw,'attn_v_raw') and lw.attn_v_raw is not None: |
| 92 | wV_sep[i]=lw.attn_v_raw; nV_sep[i]=lw.attn_v_nr.value; qV_sep[i]=lw.attn_v_qt.value |
| 93 | if hasattr(lw,'attn_gate_raw') and lw.attn_gate_raw is not None: |
| 94 | wAG[i]=lw.attn_gate_raw; ag_qt[i]=lw.attn_gate_qt.value |
| 95 | if hasattr(lw,'attn_out_raw') and lw.attn_out_raw is not None: |
| 96 | wO_attn[i]=lw.attn_out_raw; nO_attn[i]=lw.attn_out_nr.value; qO_attn[i]=lw.attn_out_qt.value |
| 97 | if hasattr(lw,'ssm_conv1d_ptr') and lw.ssm_conv1d_ptr is not None: |
| 98 | ssm_c1d[i]=lw.ssm_conv1d_ptr; ssm_a[i]=lw.ssm_a_ptr; ssm_db[i]=lw.ssm_dt_bias_ptr |
| 99 | ssm_al[i]=lw.ssm_alpha_ptr; ssm_be[i]=lw.ssm_beta_ptr; ssm_nm[i]=lw.ssm_norm_ptr |
| 100 | if hasattr(lw,'ssm_out_raw') and lw.ssm_out_raw is not None: |
| 101 | wSO[i]=lw.ssm_out_raw; so_qt[i]=lw.ssm_out_qt.value |
| 102 | if hasattr(lw,'shexp_gate_raw') and lw.shexp_gate_raw is not None: |
| 103 | wSHG[i]=lw.shexp_gate_raw; shg_qt[i]=lw.shexp_gate_qt.value |
| 104 | if hasattr(lw,'shexp_up_raw') and lw.shexp_up_raw is not None: |
| 105 | wSHU[i]=lw.shexp_up_raw; shu_qt[i]=lw.shexp_up_qt.value |
| 106 | if hasattr(lw,'shexp_down_raw') and lw.shexp_down_raw is not None: |
| 107 | wSHD[i]=lw.shexp_down_raw; shd_qt[i]=lw.shexp_down_qt.value |
| 108 | if hasattr(lw,'shexp_router_ptr') and lw.shexp_router_ptr is not None: |
| 109 | wSHR[i]=lw.shexp_router_ptr |
| 110 | if hasattr(me,'router_f32') and me.router_f32 is not None: |
| 111 | wGI[i]=me.router_f32.ctypes.data_as(cv) |
| 112 | if me.gate_raw and len(me.gate_raw)>0: |
| 113 | wGE[i]=me.gate_raw[0].ctypes.data_as(cv) |
| 114 | ns_G[i]=me.gate_nr.value; qt_G[i]=me.gate_qt.value |
| 115 | if me.up_raw and len(me.up_raw)>0: |
| 116 | wUE[i]=me.up_raw[0].ctypes.data_as(cv) |
| 117 | ns_U[i]=me.up_nr.value; qt_U[i]=me.up_qt.value |
| 118 | if me.down_raw and len(me.down_raw)>0: |
| 119 | wDE[i]=me.down_raw[0].ctypes.data_as(cv) |
| 120 | ns_D[i]=me.down_nr.value; qt_D[i]=me.down_qt.value |
| 121 | if hasattr(lw,'attn_norm_w') and lw.attn_norm_w is not None: |
| 122 | wAN[i]=lw.attn_norm_w.ctypes.data_as(cv) |
| 123 | if hasattr(lw,'ffn_norm_w') and lw.ffn_norm_w is not None: |
| 124 | wFN[i]=lw.ffn_norm_w.ctypes.data_as(cv) |
| 125 | |
| 126 | me0=e._moe_layers[0] |
| 127 | gate_qt_all=me0.gate_qt.value; up_qt_all=me0.up_qt.value; down_qt_all=me0.down_qt.value |
| 128 | |
| 129 | # ── BC struct ── |
| 130 | bc=BC() |
| 131 | for a,v in [('L',L),('N',N),('NH',NH),('NKH',NKH),('HD',HD),('FF',FF),('V',V),('eps',e.eps), |
| 132 | ('nc',N),('outNR',V),('outNC',N),('outQuant',8), |
| 133 | ('n_experts',NE),('n_experts_per_tok',NK),('moe_intermediate',moe_int), |
| 134 | ('gate_exp_quant',gate_qt_all),('up_exp_quant',up_qt_all),('down_exp_quant',down_qt_all), |
| 135 | ('emb_quant',0),('max_ctx',4096),('rope_dim',HD),('full_attn_interval',4),('n_layers_actual',L)]: |
| 136 | setattr(bc,a,v) |
| 137 | |
| 138 | bc.wQKV=ctypes.cast(wa(wQKV),cv); bc.qkv_quant=ctypes.cast(ia(qkv_qt),cv) |
| 139 | bc.wQ=ctypes.cast(wa(wQ_sep),cv); bc.wK=ctypes.cast(wa(wK_sep),cv); bc.wV=ctypes.cast(wa(wV_sep),cv) |
| 140 | bc.nQ=ctypes.cast(ia(nQ_sep),cv); bc.nK=ctypes.cast(ia(nK_sep),cv); bc.nV=ctypes.cast(ia(nV_sep),cv) |
| 141 | bc.q_quant=ctypes.cast(ia(qQ_sep),cv); bc.k_quant=ctypes.cast(ia(qK_sep),cv); bc.v_quant=ctypes.cast(ia(qV_sep),cv) |
| 142 | bc.wAttnG=ctypes.cast(wa(wAG),cv); bc.attnG_quant=ctypes.cast(ia(ag_qt),cv) |
| 143 | bc.wO=ctypes.cast(wa(wO_attn),cv); bc.nO=ctypes.cast(ia(nO_attn),cv); bc.o_quant=ctypes.cast(ia(qO_attn),cv) |
| 144 | bc.wSsmOut=ctypes.cast(wa(wSO),cv); bc.ssm_out_quant=ctypes.cast(ia(so_qt),cv) |
| 145 | bc.ssm_conv1d=ctypes.cast(wa(ssm_c1d),cv); bc.ssm_a=ctypes.cast(wa(ssm_a),cv) |
| 146 | bc.ssm_dt_bias=ctypes.cast(wa(ssm_db),cv); bc.ssm_alpha=ctypes.cast(wa(ssm_al),cv) |
| 147 | bc.ssm_beta=ctypes.cast(wa(ssm_be),cv); bc.ssm_norm=ctypes.cast(wa(ssm_nm),cv) |
| 148 | bc.wSHexpG=ctypes.cast(wa(wSHG),cv); bc.wSHexpU=ctypes.cast(wa(wSHU),cv) |
| 149 | bc.wSHexpD=ctypes.cast(wa(wSHD),cv); bc.wShexpRouter=ctypes.cast(wa(wSHR),cv) |
| 150 | bc.shexp_g_quant=ctypes.cast(ia(shg_qt),cv); bc.shexp_u_quant=ctypes.cast(ia(shu_qt),cv) |
| 151 | bc.shexp_d_quant=ctypes.cast(ia(shd_qt),cv) |
| 152 | bc.wAN=ctypes.cast(wa(wAN),cv); bc.wFN=ctypes.cast(wa(wFN),cv) |
| 153 | bc.w_gate_inp=ctypes.cast(wa(wGI),cv) |
| 154 | bc.w_gate_exps=ctypes.cast(wa(wGE),cv); bc.w_up_exps=ctypes.cast(wa(wUE),cv) |
| 155 | bc.w_down_exps=ctypes.cast(wa(wDE),cv) |
| 156 | bc.nG=ctypes.cast(ia(ns_G),cv); bc.nU=ctypes.cast(ia(ns_U),cv); bc.nD=ctypes.cast(ia(ns_D),cv) |
| 157 | bc.g_quant=ctypes.cast(ia(qt_G),cv); bc.u_quant=ctypes.cast(ia(qt_U),cv); bc.d_quant=ctypes.cast(ia(qt_D),cv) |
| 158 | for pf in ['wG','wU','wD','nG','nU','nD','g_quant','u_quant','d_quant','wQK','qk_quant']: |
| 159 | setattr(bc,pf,cv(0)) |
| 160 | bc.emb=e.emb.ctypes.data_as(cv) if hasattr(e,'emb') and e.emb is not None else cv(0) |
| 161 | bc.onw=e._out_norm_w.ctypes.data_as(cv) if hasattr(e,'_out_norm_w') else cv(0) |
| 162 | bc.wOut=ctypes.cast(e._out_raw,cv) |
| 163 | |
| 164 | # SSM state |
| 165 | ssm_state = np.zeros(L * e.ssm_groups * e.ssm_state_size, dtype=np.float32) |
| 166 | bc.ssm_state = ssm_state.ctypes.data_as(cv) |
| 167 | |
| 168 | # Layer types |
| 169 | if LT: |
| 170 | lt_arr=(ci*L)(*LT) |
| 171 | bc.layer_types=ctypes.cast(lt_arr,cv) |
| 172 | |
| 173 | # RoPE |
| 174 | max_ctx=4096; hd2=HD//2 |
| 175 | freq = e.rope_freq_base ** (np.arange(0, HD, 2, dtype=np.float32) / HD) |
| 176 | ang = np.arange(max_ctx, dtype=np.float32).reshape(-1, 1) / freq.reshape(1, -1) |
| 177 | cos_all = np.cos(ang).astype(np.float32).reshape(-1) |
| 178 | sin_all = np.sin(ang).astype(np.float32).reshape(-1) |
| 179 | bc.cos_table=cos_all.ctypes.data_as(cv) |
| 180 | bc.sin_table=sin_all.ctypes.data_as(cv) |
| 181 | bc.max_ctx=max_ctx |
| 182 | lib.rope_init(bc.cos_table, bc.sin_table, ci(max_ctx), ci(HD), ci(HD)) |
| 183 | |
| 184 | # Workspace for KV temp in batch_forward |
| 185 | ws_bc_size = 2 * max_ctx * NKH * HD + 4096 |
| 186 | ws_bc = np.zeros(ws_bc_size, dtype=np.float32) |
| 187 | bc.workspace = ws_bc.ctypes.data_as(cv) |
| 188 | bc.ws_size = ws_bc_size |
| 189 | print(f"BC workspace: {ws_bc_size} floats", flush=True) |
| 190 | |
| 191 | # Shared buffers for B_MAX concurrent |
| 192 | ws = np.zeros(B_MAX * 12 * S, dtype=np.float32) |
| 193 | logits_buf = np.zeros(B_MAX * V, dtype=np.float32) |
| 194 | |
| 195 | def mk_kv(): |
| 196 | kv = KVBlock() |
| 197 | lib.kv_init(ctypes.byref(kv), ci(L), ci(NKH), ci(HD)) |
| 198 | return kv |
| 199 | |
| 200 | def sample_token(logits, temperature=0.0): |
| 201 | safe = np.nan_to_num(logits, nan=-1e10, posinf=1e10, neginf=-1e10) |
| 202 | if temperature <= 0: return int(np.argmax(safe)) |
| 203 | safe -= safe.max() |
| 204 | p = np.exp(np.clip(safe / temperature, -50, 50)) |
| 205 | p[np.isnan(p)] = 0; s = p.sum() |
| 206 | return int(np.random.choice(len(p), p=p/s)) if s > 0 else 0 |
| 207 | |
| 208 | # Tokenizer |
| 209 | print("Loading tokenizer...", flush=True) |
| 210 | from transformers import AutoTokenizer |
| 211 | tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.6-35B-A3B", trust_remote_code=True) |
| 212 | tokenizer.bos_token_id = BOS; tokenizer.eos_token_id = EOS |
| 213 | print(f"Tokenizer loaded, vocab={tokenizer.vocab_size}", flush=True) |
| 214 | |
| 215 | # ── Scheduler ── |
| 216 | class Sequence: |
| 217 | __slots__ = ('kv','tokens','gen_tokens','done','result','event','max_tokens','temperature','token_queue','stream') |
| 218 | def __init__(self): |
| 219 | self.kv = mk_kv() |
| 220 | self.tokens = []; self.gen_tokens = [] |
| 221 | self.done = False; self.result = None |
| 222 | self.event = threading.Event() |
| 223 | self.max_tokens = 100; self.temperature = 0.0 |
| 224 | self.token_queue = None; self.stream = False |
| 225 | |
| 226 | pending = queue.Queue() |
| 227 | active_slots = [None] * B_MAX |
| 228 | forward_lock = threading.Lock() |
| 229 | |
| 230 | def run_scheduler(): |
| 231 | global bc, ws, logits_buf |
| 232 | while True: |
| 233 | # Fill slots |
| 234 | while not pending.empty(): |
| 235 | try: seq = pending.get_nowait() |
| 236 | except queue.Empty: break |
| 237 | for i in range(B_MAX): |
| 238 | if active_slots[i] is None: |
| 239 | active_slots[i] = seq; break |
| 240 | |
| 241 | batch = [(i, s) for i, s in enumerate(active_slots) if s is not None and not s.done] |
| 242 | if not batch: |
| 243 | time.sleep(0.002); continue |
| 244 | |
| 245 | B = len(batch) |
| 246 | tokens_arr = (ci * B)() |
| 247 | kv_ptrs = (cv * B)() |
| 248 | for j, (slot, seq) in enumerate(batch): |
| 249 | tokens_arr[j] = seq.tokens[-1] if seq.tokens else BOS |
| 250 | kv_ptrs[j] = ctypes.cast(ctypes.pointer(seq.kv), cv) |
| 251 | |
| 252 | try: |
| 253 | with forward_lock: |
| 254 | bc.kv_array = ctypes.cast(kv_ptrs, cv) |
| 255 | bc.logits = logits_buf.ctypes.data_as(cv) |
| 256 | lib.batch_forward(ctypes.byref(bc), tokens_arr, ci(B), ws.ctypes.data_as(cv)) |
| 257 | except Exception as ex: |
| 258 | print(f"SCHEDULER error: {ex}", flush=True); continue |
| 259 | |
| 260 | for j, (slot, seq) in enumerate(batch): |
| 261 | logits = logits_buf[j*V:(j+1)*V].copy() |
| 262 | next_tok = sample_token(logits, seq.temperature) |
| 263 | seq.tokens.append(next_tok); seq.gen_tokens.append(next_tok) |
| 264 | if seq.token_queue is not None: |
| 265 | seq.token_queue.put(next_tok) |
| 266 | if next_tok == EOS or len(seq.gen_tokens) >= seq.max_tokens: |
| 267 | seq.done = True |
| 268 | seq.result = {'tokens': seq.gen_tokens.copy(), 'finish_reason': 'stop' if next_tok == EOS else 'length'} |
| 269 | if seq.token_queue: seq.token_queue.put(None) |
| 270 | seq.event.set(); 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 ── |
| 277 | class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): |
| 278 | allow_reuse_address = True; daemon_threads = True |
| 279 | |
| 280 | class Handler(BaseHTTPRequestHandler): |
| 281 | def do_GET(self): |
| 282 | path = urlparse(self.path).path |
| 283 | if path == '/health': |
| 284 | active = sum(1 for s in active_slots if s is not None and not s.done) |
| 285 | self.send_response(200) |
| 286 | self.send_header('Content-Type', 'application/json'); self.end_headers() |
| 287 | self.wfile.write(json.dumps({'status':'ok','model':'qwen3.6-mxfp4','active':active,'max':B_MAX}).encode()) |
| 288 | else: self.send_error(404) |
| 289 | |
| 290 | def do_POST(self): |
| 291 | if urlparse(self.path).path != '/v1/completions': self.send_error(404); return |
| 292 | try: |
| 293 | n = int(self.headers.get('Content-Length',0)) |
| 294 | body = json.loads(self.rfile.read(n)) if n else {} |
| 295 | prompt = body.get('prompt',''); max_tokens = body.get('max_tokens',100) |
| 296 | temperature = body.get('temperature',0.0); stream = body.get('stream',False) |
| 297 | |
| 298 | prompt_ids = tokenizer.encode(prompt) if isinstance(prompt,str) else prompt[:512] |
| 299 | prompt_ids = [t for t in prompt_ids if t != BOS][:512] |
| 300 | if not prompt_ids: prompt_ids = [BOS] |
| 301 | |
| 302 | t0 = time.perf_counter() |
| 303 | seq = Sequence(); seq.max_tokens=max_tokens; seq.temperature=temperature; seq.stream=stream |
| 304 | |
| 305 | # Prefill token-by-token |
| 306 | if prompt_ids: |
| 307 | with forward_lock: |
| 308 | kva1=(cv*1)(ctypes.cast(ctypes.pointer(seq.kv),cv)) |
| 309 | bc.kv_array=ctypes.cast(kva1,cv) |
| 310 | bc.logits=logits_buf[:V].ctypes.data_as(cv) |
| 311 | logits_buf[:V]=0 |
| 312 | for pt in prompt_ids: |
| 313 | lib.batch_forward(ctypes.byref(bc),(ci*1)(pt),ci(1),ws.ctypes.data_as(cv)) |
| 314 | |
| 315 | first_tok = sample_token(logits_buf[:V].copy(), temperature) |
| 316 | seq.tokens=[first_tok]; seq.gen_tokens=[first_tok] |
| 317 | |
| 318 | if stream: |
| 319 | seq.token_queue=queue.Queue() |
| 320 | seq.token_queue.put(first_tok) |
| 321 | |
| 322 | pending.put(seq) |
| 323 | |
| 324 | if stream: |
| 325 | self.send_response(200) |
| 326 | self.send_header('Content-Type','text/event-stream'); self.send_header('Cache-Control','no-cache') |
| 327 | self.end_headers() |
| 328 | while True: |
| 329 | tok=seq.token_queue.get() |
| 330 | if tok is None: break |
| 331 | self.wfile.write(f'data: {json.dumps({"choices":[{"text":tokenizer.decode([tok],skip_special_tokens=True),"index":0}]})}\n\n'.encode()) |
| 332 | self.wfile.flush() |
| 333 | self.wfile.write('data: [DONE]\n\n'.encode()) |
| 334 | else: |
| 335 | if not seq.event.wait(timeout=600): |
| 336 | gen_tokens=seq.gen_tokens[:20]; finish='timeout' |
| 337 | elif seq.result is None: |
| 338 | gen_tokens=seq.gen_tokens; finish='length' if len(gen_tokens)>=max_tokens else 'stop' |
| 339 | else: |
| 340 | gen_tokens=seq.result['tokens']; finish=seq.result['finish_reason'] |
| 341 | t_total=time.perf_counter()-t0 |
| 342 | text=tokenizer.decode(gen_tokens,skip_special_tokens=True) |
| 343 | self.send_response(200) |
| 344 | self.send_header('Content-Type','application/json'); self.end_headers() |
| 345 | self.wfile.write(json.dumps({ |
| 346 | 'choices':[{'text':text,'index':0,'finish_reason':finish}], |
| 347 | 'usage':{'prompt_tokens':len(prompt_ids),'completion_tokens':len(gen_tokens),'total_tokens':len(prompt_ids)+len(gen_tokens)} |
| 348 | }).encode()) |
| 349 | print(f" [{len(prompt_ids)}p+{len(gen_tokens)}g {t_total:.1f}s {len(gen_tokens)/t_total:.0f}t/s]", flush=True) |
| 350 | except Exception as ex: |
| 351 | print(f" ERROR: {ex}",flush=True) |
| 352 | try: self.send_response(500); self.send_header('Content-Type','application/json'); self.end_headers(); self.wfile.write(json.dumps({'error':str(ex)}).encode()) |
| 353 | except: pass |
| 354 | |
| 355 | def log_message(self,*a): pass |
| 356 | |
| 357 | if __name__ == '__main__': |
| 358 | print(f"Serving on 0.0.0.0:{PORT}", flush=True) |
| 359 | print(f" POST /v1/completions (B_MAX={B_MAX}, ~{B_MAX * 2.5:.0f} tok/s at saturation)", flush=True) |
| 360 | print(f" GET /health", flush=True) |
| 361 | server = ThreadedHTTPServer(('0.0.0.0', PORT), Handler) |
| 362 | try: server.serve_forever() |
| 363 | except KeyboardInterrupt: print("\nShutdown", flush=True) |