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/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 / server.py` 501 lines · 18941 bytes Raw Blame History 1 """Mojo Hybrid Serve — OpenAI-compatible API server with web UI. 2 Usage: 3 python server.py # Uses default model path 4 MODEL_PATH=model.gguf python server.py # Custom model 5 python server.py --help # All options 6 """ 7 import argparse 8 import json 9 import os 10 import sys 11 import time 12 import threading 13 from pathlib import Path 14 15 # Add project root to path 16 sys.path.insert(0, str(Path(__file__).resolve().parent)) 17 18 from flask import Flask, request, jsonify, render_template_string, send_from_directory 19 20 from src.mojollama.model.inference import LLMInference 21 from src.mojollama.model.device import list_devices 22 from src.mojollama.quantizer import convert, quantize, get_info, validate, benchmark 23 24 # ─── Config ────────────────────────────────────────────────────────────────── 25 DEFAULT_HOST = "0.0.0.0" 26 DEFAULT_PORT = 9000 27 DEFAULT_MAX_TOKENS = 256 28 29 app = Flask(__name__) 30 model = None 31 model_lock = threading.Lock() 32 current_model_path = None 33 34 # ─── HTML Template (embedded for single-file deployment) ──────────────────── 35 36 HTML_TEMPLATE = r""" 37 38 39 40 41 Mojo Hybrid Serve 42 73 74 75
76

🔥 Mojo Hybrid Serve

77 Loading... 78 79
80
81
82 84 85
86 87 170 171 """ 172 173 # ─── API Routes ────────────────────────────────────────────────────────────── 174 175 @app.route("/") 176 def web_ui(): 177 return render_template_string(HTML_TEMPLATE) 178 179 180 @app.route("/v1/models") 181 def list_models(): 182 with model_lock: 183 path = current_model_path or "none" 184 name = os.path.splitext(os.path.basename(path))[0] if path != "none" else "unknown" 185 return jsonify({ 186 "object": "list", 187 "data": [{ 188 "id": name, 189 "object": "model", 190 "created": int(time.time()), 191 "owned_by": "mojollama", 192 }] 193 }) 194 195 196 @app.route("/v1/chat/completions", methods=["POST"]) 197 def chat_completions(): 198 data = request.get_json(force=True) 199 messages = data.get("messages", []) 200 max_tokens = int(data.get("max_tokens", DEFAULT_MAX_TOKENS)) 201 temperature = float(data.get("temperature", 0.7)) 202 stream = data.get("stream", False) 203 204 # Extract the last user message as prompt 205 prompt = "" 206 for msg in messages: 207 if msg.get("role") == "user": 208 prompt = msg.get("content", "") 209 elif msg.get("role") == "assistant" and msg.get("content"): 210 prompt += "\n" + msg.get("content", "") 211 212 if not prompt: 213 prompt = messages[-1].get("content", "") if messages else "" 214 215 # Format as instruct prompt 216 full_prompt = _format_chat_prompt(messages) 217 218 with model_lock: 219 if model is None: 220 return jsonify({"error": "No model loaded"}), 500 221 222 # Generate 223 t0 = time.time() 224 try: 225 output = model.generate(full_prompt, max_tokens=max_tokens) 226 except Exception as e: 227 return jsonify({"error": str(e)}), 500 228 elapsed = time.time() - t0 229 230 usage = { 231 "prompt_tokens": len(model.encode(full_prompt)), 232 "completion_tokens": len(model.encode(output)), 233 } 234 usage["total_tokens"] = usage["prompt_tokens"] + usage["completion_tokens"] 235 236 result = { 237 "id": f"chatcmpl-{int(time.time())}", 238 "object": "chat.completion", 239 "created": int(time.time()), 240 "model": os.path.splitext(os.path.basename(current_model_path or ""))[0], 241 "choices": [{ 242 "index": 0, 243 "message": {"role": "assistant", "content": output.strip()}, 244 "finish_reason": "stop", 245 }], 246 "usage": usage, 247 } 248 return jsonify(result) 249 250 251 @app.route("/v1/completions", methods=["POST"]) 252 def completions(): 253 data = request.get_json(force=True) 254 prompt = data.get("prompt", "") 255 max_tokens = int(data.get("max_tokens", DEFAULT_MAX_TOKENS)) 256 257 with model_lock: 258 if model is None: 259 return jsonify({"error": "No model loaded"}), 500 260 261 t0 = time.time() 262 try: 263 output = model.generate(prompt, max_tokens=max_tokens) 264 except Exception as e: 265 return jsonify({"error": str(e)}), 500 266 elapsed = time.time() - t0 267 268 return jsonify({ 269 "id": f"cmpl-{int(time.time())}", 270 "object": "text_completion", 271 "created": int(time.time()), 272 "model": os.path.splitext(os.path.basename(current_model_path or ""))[0], 273 "choices": [{ 274 "index": 0, 275 "text": output, 276 "finish_reason": "stop", 277 }], 278 }) 279 280 281 # ─── Export / Quantize API ────────────────────────────────────────────────── 282 283 284 @app.route("/api/export", methods=["POST"]) 285 def api_export(): 286 """Convert a HuggingFace model to GGUF format.""" 287 data = request.get_json(force=True) 288 model_name = data.get("model", "") 289 outtype = data.get("outtype", "f16") 290 outfile = data.get("outfile", "") 291 292 if not model_name: 293 return jsonify({"error": "model is required"}), 400 294 if outtype not in ("f32", "f16", "bf16", "q8_0", "auto"): 295 return jsonify({"error": f"unsupported outtype: {outtype}"}), 400 296 297 try: 298 result = convert( 299 model_name, 300 outtype=outtype, 301 outfile=outfile if outfile else None, 302 ) 303 return jsonify({ 304 "status": "ok", 305 "output_path": result.get("output_path"), 306 "size_bytes": result.get("size_bytes"), 307 "size_human": result.get("size_human"), 308 "elapsed_seconds": result.get("elapsed_seconds"), 309 }) 310 except Exception as e: 311 return jsonify({"error": str(e)}), 500 312 313 314 @app.route("/api/quantize", methods=["POST"]) 315 def api_quantize(): 316 """Quantize an existing GGUF file.""" 317 data = request.get_json(force=True) 318 input_path = data.get("input", "") 319 quant_type = data.get("type", "q4_k_m") 320 output_path = data.get("output", "") 321 322 if not input_path or not os.path.exists(input_path): 323 return jsonify({"error": f"input file not found: {input_path}"}), 400 324 325 try: 326 result = quantize( 327 input_path, 328 quant_type=quant_type, 329 output_path=output_path if output_path else None, 330 ) 331 return jsonify({ 332 "status": "ok", 333 "output_path": result.get("output_path"), 334 "quant_type": result.get("quant_type"), 335 "input_size_bytes": result.get("input_size_bytes"), 336 "output_size_bytes": result.get("output_size_bytes"), 337 "compression_ratio": result.get("compression_ratio"), 338 "elapsed_seconds": result.get("elapsed_seconds"), 339 }) 340 except Exception as e: 341 return jsonify({"error": str(e)}), 500 342 343 344 @app.route("/api/model-info", methods=["GET"]) 345 def api_model_info(): 346 """Get info about the currently loaded or specified model.""" 347 model_path = request.args.get("path", current_model_path or "") 348 if not model_path or not os.path.exists(model_path): 349 return jsonify({"error": "No model loaded and no path specified"}), 400 350 351 try: 352 info = get_info(model_path) 353 return jsonify({ 354 "status": "ok", 355 "path": info.get("path"), 356 "file_size_human": info.get("file_size_human"), 357 "file_size_bytes": info.get("file_size_bytes"), 358 "tensor_count": info.get("tensor_count"), 359 "total_parameters": info.get("total_parameters"), 360 "primary_quantization": info.get("primary_quantization"), 361 "metadata": info.get("metadata"), 362 "tensor_type_counts": info.get("tensor_type_counts"), 363 }) 364 except Exception as e: 365 return jsonify({"error": str(e)}), 500 366 367 368 @app.route("/api/validate", methods=["POST"]) 369 def api_validate(): 370 """Validate a quantized model against a reference.""" 371 data = request.get_json(force=True) 372 input_path = data.get("input", "") 373 reference_path = data.get("reference", "") 374 375 if not input_path or not os.path.exists(input_path): 376 return jsonify({"error": f"input file not found: {input_path}"}), 400 377 378 try: 379 result = validate( 380 input_path, 381 reference_path=reference_path if reference_path and os.path.exists(reference_path) else None, 382 ) 383 return jsonify({ 384 "status": result.get("status"), 385 "checks": result.get("checks"), 386 "tensor_count": result.get("tensor_count"), 387 }) 388 except Exception as e: 389 return jsonify({"error": str(e)}), 500 390 391 392 @app.route("/api/benchmark", methods=["POST"]) 393 def api_benchmark(): 394 """Benchmark a GGUF model.""" 395 data = request.get_json(force=True) 396 model_path = data.get("model", current_model_path or "") 397 prompt = data.get("prompt", "Hello") 398 max_tokens = int(data.get("max_tokens", 10)) 399 400 if not model_path or not os.path.exists(model_path): 401 return jsonify({"error": f"model not found: {model_path}"}), 400 402 403 try: 404 result = benchmark( 405 model_path, 406 prompt=prompt, 407 max_tokens=max_tokens, 408 ) 409 return jsonify({ 410 "status": "ok", 411 "tokens_per_second": result.get("tokens_per_second"), 412 "generated_tokens": result.get("generated_tokens"), 413 "elapsed_seconds": result.get("elapsed_seconds"), 414 "output": result.get("output"), 415 "architecture": result.get("architecture"), 416 }) 417 except Exception as e: 418 return jsonify({"error": str(e)}), 500 419 420 421 def _format_chat_prompt(messages: list) -> str: 422 """Format chat messages into a prompt string for Llama 3 instruct.""" 423 # Llama 3 chat template 424 parts = [] 425 for msg in messages: 426 role = msg.get("role", "user") 427 content = msg.get("content", "").strip() 428 if role == "system": 429 parts.append(f"System: {content}") 430 elif role == "user": 431 parts.append(f"User: {content}") 432 elif role == "assistant": 433 parts.append(f"Assistant: {content}") 434 parts.append("Assistant:") 435 return "\n".join(parts) 436 437 438 # ─── Server Init ────────────────────────────────────────────────────────────── 439 440 def load_model_file(path: str, device: str = 'auto'): 441 global model, current_model_path 442 path = str(path) 443 if not os.path.exists(path): 444 # Try to find .gguf files 445 import glob 446 files = glob.glob("*.gguf") or glob.glob(os.path.join(os.path.dirname(path) or ".", "*.gguf")) 447 if files: 448 path = files[0] 449 print(f"Auto-discovered model: {path}") 450 else: 451 print(f"ERROR: Model not found at {path}") 452 sys.exit(1) 453 454 print(f"Loading model: {path}") 455 print(f"Device: {device}") 456 t0 = time.time() 457 model = LLMInference(path, device=device) 458 elapsed = time.time() - t0 459 current_model_path = path 460 print(f"Model loaded in {elapsed:.1f}s") 461 print(f" Architecture: {model.arch}") 462 print(f" Parameters: {model.n_layers} layers, {model.n_embd} dim, {model.n_head} heads") 463 if model.device.device_type.value != 'cpu': 464 print(f" Accelerator: {model.device.capability}") 465 else: 466 print(f" Accelerator: CPU") 467 468 469 def main(): 470 parser = argparse.ArgumentParser(description="Mojo Hybrid Serve — LLM inference server") 471 parser.add_argument("--model", "-m", default=os.environ.get("MODEL_PATH", ""), 472 help="Path to GGUF model file") 473 parser.add_argument("--device", "-d", default=os.environ.get("MOJOLLAMA_DEVICE", "auto"), 474 choices=['auto', 'cpu', 'intel_arc', 'nvidia'], 475 help="Compute device: auto, cpu, intel_arc, nvidia (default: auto)") 476 parser.add_argument("--list-devices", action="store_true", 477 help="List available compute devices and exit") 478 parser.add_argument("--host", default=os.environ.get("HOST", DEFAULT_HOST), 479 help=f"Host to bind (default: {DEFAULT_HOST})") 480 parser.add_argument("--port", "-p", type=int, 481 default=int(os.environ.get("PORT", DEFAULT_PORT)), 482 help=f"Port to bind (default: {DEFAULT_PORT})") 483 parser.add_argument("--debug", action="store_true", help="Enable debug mode") 484 args = parser.parse_args() 485 486 if args.list_devices: 487 devices = list_devices() 488 print("Available compute devices:") 489 for d in devices: 490 print(f" {d['device']:12s} {d['name']:40s} VRAM: {d['vram_gb']:.1f}GB CUs: {d['compute_units']}") 491 sys.exit(0) 492 493 load_model_file(args.model, args.device) 494 print(f"\n🔥 Mojo Hybrid Serve running at http://{args.host}:{args.port}") 495 print(f" API: http://{args.host}:{args.port}/v1/chat/completions") 496 print(f" Web UI: http://{args.host}:{args.port}/") 497 app.run(host=args.host, port=args.port, debug=args.debug, threaded=True) 498 499 500 if __name__ == "__main__": 501 main()