interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

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.
2Usage:
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"""
7import argparse
8import json
9import os
10import sys
11import time
12import threading
13from pathlib import Path
14
15# Add project root to path
16sys.path.insert(0, str(Path(__file__).resolve().parent))
17
18from flask import Flask, request, jsonify, render_template_string, send_from_directory
19
20from src.mojollama.model.inference import LLMInference
21from src.mojollama.model.device import list_devices
22from src.mojollama.quantizer import convert, quantize, get_info, validate, benchmark
23
24# ─── Config ──────────────────────────────────────────────────────────────────
25DEFAULT_HOST = "0.0.0.0"
26DEFAULT_PORT = 9000
27DEFAULT_MAX_TOKENS = 256
28
29app = Flask(__name__)
30model = None
31model_lock = threading.Lock()
32current_model_path = None
33
34# ─── HTML Template (embedded for single-file deployment) ────────────────────
35
36HTML_TEMPLATE = r"""<!DOCTYPE html>
37<html lang="en">
38<head>
39<meta charset="UTF-8">
40<meta name="viewport" content="width=device-width, initial-scale=1.0">
41<title>Mojo Hybrid Serve</title>
42<style>
43 * { box-sizing: border-box; margin: 0; padding: 0; }
44 body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
45 background: #0d1117; color: #c9d1d9; height: 100vh; display: flex; flex-direction: column; }
46 header { background: #161b22; border-bottom: 1px solid #30363d; padding: 12px 20px; display: flex;
47 align-items: center; gap: 12px; flex-shrink: 0; }
48 header h1 { font-size: 18px; font-weight: 600; color: #f0f6fc; }
49 header span { color: #8b949e; font-size: 13px; }
50 .model-badge { background: #1f6feb22; border: 1px solid #1f6feb44; color: #58a6ff;
51 padding: 2px 10px; border-radius: 12px; font-size: 12px; }
52 .chat-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 12px; }
53 .msg { max-width: 80%; padding: 12px 16px; border-radius: 8px; line-height: 1.5; white-space: pre-wrap; font-size: 14px; }
54 .msg.user { align-self: flex-end; background: #1f6feb; color: #fff; }
55 .msg.assistant { align-self: flex-start; background: #21262d; border: 1px solid #30363d; color: #c9d1d9; }
56 .msg.system { align-self: center; background: #1c2128; border: 1px solid #30363d; color: #8b949e; font-style: italic; font-size: 12px; }
57 .msg .meta { font-size: 11px; color: #8b949e; margin-top: 4px; }
58 .input-area { background: #161b22; border-top: 1px solid #30363d; padding: 12px 20px; display: flex; gap: 8px; flex-shrink: 0; }
59 .input-area textarea { flex: 1; background: #0d1117; border: 1px solid #30363d; border-radius: 6px;
60 color: #c9d1d9; padding: 10px 12px; font-size: 14px; resize: none; min-height: 44px;
61 font-family: inherit; outline: none; }
62 .input-area textarea:focus { border-color: #1f6feb; }
63 .input-area button { background: #238636; color: #fff; border: none; border-radius: 6px;
64 padding: 0 20px; font-size: 14px; font-weight: 600; cursor: pointer; white-space: nowrap; }
65 .input-area button:hover { background: #2ea043; }
66 .input-area button:disabled { opacity: 0.5; cursor: not-allowed; }
67 .spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid #30363d;
68 border-top-color: #58a6ff; border-radius: 50%; animation: spin 0.8s linear infinite; vertical-align: middle; }
69 @keyframes spin { to { transform: rotate(360deg); } }
70 .typing { color: #8b949e; font-size: 13px; padding: 8px 16px; }
71 pre { background: #161b22; padding: 8px; border-radius: 4px; overflow-x: auto; font-size: 12px; }
72</style>
73</head>
74<body>
75<header>
76 <h1>🔥 Mojo Hybrid Serve</h1>
77 <span class="model-badge" id="model-name">Loading...</span>
78 <span id="perf-stats" style="font-size:12px;color:#8b949e;margin-left:auto;"></span>
79</header>
80<div class="chat-container" id="chat"></div>
81<div class="input-area">
82 <textarea id="input" placeholder="Type a message..." rows="1"
83 onkeydown="if(event.key=='Enter'&&!event.shiftKey){event.preventDefault();send()}"></textarea>
84 <button id="send-btn" onclick="send()">Send</button>
85</div>
86
87<script>
88let messages = [{"role": "system", "content": "You are a helpful AI assistant."}];
89let generating = false;
90let perfData = {};
91
92async function fetchModels() {
93 const r = await fetch('/v1/models');
94 const data = await r.json();
95 const name = data.data?.[0]?.id || 'unknown';
96 document.getElementById('model-name').textContent = name;
97}
98fetchModels();
99
100function addMsg(role, content) {
101 const chat = document.getElementById('chat');
102 const div = document.createElement('div');
103 div.className = 'msg ' + role;
104 div.textContent = content;
105 if (role === 'assistant') {
106 const meta = document.createElement('div');
107 meta.className = 'meta';
108 meta.id = 'perf-meta';
109 chat.appendChild(div);
110 chat.appendChild(meta);
111 } else {
112 chat.appendChild(div);
113 }
114 chat.scrollTop = chat.scrollHeight;
115 return div;
116}
117
118function showTyping() {
119 const chat = document.getElementById('chat');
120 const div = document.createElement('div');
121 div.className = 'typing';
122 div.id = 'typing-indicator';
123 div.innerHTML = '<span class="spinner"></span> Thinking...';
124 chat.appendChild(div);
125 chat.scrollTop = chat.scrollHeight;
126}
127
128function hideTyping() {
129 const el = document.getElementById('typing-indicator');
130 if (el) el.remove();
131}
132
133async function send() {
134 if (generating) return;
135 const input = document.getElementById('input');
136 const text = input.value.trim();
137 if (!text) return;
138 input.value = '';
139 generating = true;
140 document.getElementById('send-btn').disabled = true;
141
142 messages.push({"role": "user", "content": text});
143 addMsg('user', text);
144 showTyping();
145
146 try {
147 const r = await fetch('/v1/chat/completions', {
148 method: 'POST',
149 headers: {'Content-Type': 'application/json'},
150 body: JSON.stringify({model: '', messages: messages, max_tokens: 50, stream: false})
151 });
152 const data = await r.json();
153 hideTyping();
154 const reply = data.choices?.[0]?.message?.content || '[no response]';
155 messages.push({"role": "assistant", "content": reply});
156 addMsg('assistant', reply);
157 if (data.usage) {
158 document.getElementById('perf-stats').textContent =
159 `${data.usage.total_tokens || '?'} tokens | ${data.usage.completion_tokens || '?'} generated`;
160 }
161 } catch(e) {
162 hideTyping();
163 addMsg('system', 'Error: ' + e.message);
164 }
165 generating = false;
166 document.getElementById('send-btn').disabled = false;
167 input.focus();
168}
169</script>
170</body>
171</html>"""
172
173# ─── API Routes ──────────────────────────────────────────────────────────────
174
175@app.route("/")
176def web_ui():
177 return render_template_string(HTML_TEMPLATE)
178
179
180@app.route("/v1/models")
181def 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"])
197def 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"])
252def 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"])
285def 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"])
315def 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"])
345def 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"])
369def 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"])
393def 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
421def _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
440def 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
469def 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
500if __name__ == "__main__":
501 main()