MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / llama_backend.py
| 1 | #!/usr/bin/env python3 |
| 2 | """MojoLlama bridge — llama.cpp backend integration. |
| 3 | |
| 4 | Uses llama.cpp server as the high-performance compute backend while |
| 5 | preserving the MojoLlama op graph architecture. |
| 6 | """ |
| 7 | |
| 8 | import json |
| 9 | import urllib.request |
| 10 | import urllib.error |
| 11 | import numpy as np |
| 12 | from typing import Optional |
| 13 | |
| 14 | |
| 15 | class LlamaCppBackend: |
| 16 | """Inference backend using llama.cpp server.""" |
| 17 | |
| 18 | def __init__(self, base_url: str = "http://localhost:9000"): |
| 19 | self.base_url = base_url.rstrip("/") |
| 20 | self._model_info = None |
| 21 | |
| 22 | def _request(self, endpoint: str, data: dict) -> dict: |
| 23 | """Send request to llama.cpp server.""" |
| 24 | url = f"{self.base_url}/{endpoint.lstrip('/')}" |
| 25 | req = urllib.request.Request( |
| 26 | url, |
| 27 | data=json.dumps(data).encode(), |
| 28 | headers={"Content-Type": "application/json"}, |
| 29 | method="POST", |
| 30 | ) |
| 31 | with urllib.request.urlopen(req, timeout=120) as resp: |
| 32 | return json.loads(resp.read()) |
| 33 | |
| 34 | def _get(self, endpoint: str) -> dict: |
| 35 | """GET request.""" |
| 36 | url = f"{self.base_url}/{endpoint.lstrip('/')}" |
| 37 | with urllib.request.urlopen(url, timeout=10) as resp: |
| 38 | return json.loads(resp.read()) |
| 39 | |
| 40 | @property |
| 41 | def model_info(self) -> dict: |
| 42 | if self._model_info is None: |
| 43 | models = self._get("v1/models") |
| 44 | self._model_info = models |
| 45 | return self._model_info |
| 46 | |
| 47 | @property |
| 48 | def is_healthy(self) -> bool: |
| 49 | try: |
| 50 | info = self._get("health") if self.base_url else self._get("v1/models") |
| 51 | return True |
| 52 | except Exception: |
| 53 | return False |
| 54 | |
| 55 | def generate( |
| 56 | self, |
| 57 | prompt: str, |
| 58 | max_tokens: int = 128, |
| 59 | temperature: float = 0.7, |
| 60 | top_p: float = 0.9, |
| 61 | seed: int = 42, |
| 62 | ) -> dict: |
| 63 | """Generate text using llama.cpp server.""" |
| 64 | result = self._request("completion", { |
| 65 | "prompt": prompt, |
| 66 | "n_predict": max_tokens, |
| 67 | "temperature": temperature, |
| 68 | "top_p": top_p, |
| 69 | "seed": seed, |
| 70 | "cache_prompt": True, |
| 71 | }) |
| 72 | return { |
| 73 | "text": result.get("content", ""), |
| 74 | "tokens_generated": result.get("tokens_predicted", 0), |
| 75 | "tokens_evaluated": result.get("tokens_evaluated", 0), |
| 76 | "timings": result.get("timings", {}), |
| 77 | "model": result.get("model", ""), |
| 78 | } |
| 79 | |
| 80 | def chat( |
| 81 | self, |
| 82 | messages: list, |
| 83 | max_tokens: int = 256, |
| 84 | temperature: float = 0.7, |
| 85 | ) -> dict: |
| 86 | """Chat completion via llama.cpp's OpenAI-compatible endpoint.""" |
| 87 | result = self._request("v1/chat/completions", { |
| 88 | "messages": messages, |
| 89 | "max_tokens": max_tokens, |
| 90 | "temperature": temperature, |
| 91 | }) |
| 92 | choice = result.get("choices", [{}])[0] |
| 93 | usage = result.get("usage", {}) |
| 94 | return { |
| 95 | "text": choice.get("message", {}).get("content", ""), |
| 96 | "tokens_generated": usage.get("completion_tokens", 0), |
| 97 | "tokens_prompt": usage.get("prompt_tokens", 0), |
| 98 | } |
| 99 | |
| 100 | |
| 101 | # Quick benchmark |
| 102 | if __name__ == "__main__": |
| 103 | import time |
| 104 | |
| 105 | backend = LlamaCppBackend() |
| 106 | print(f"Server healthy: {backend.is_healthy}") |
| 107 | |
| 108 | if backend.is_healthy: |
| 109 | # Benchmark generation |
| 110 | prompt = "The meaning of life is" |
| 111 | n_warmup = 2 |
| 112 | n_bench = 5 |
| 113 | |
| 114 | print(f"\nWarmup ({n_warmup})...") |
| 115 | for i in range(n_warmup): |
| 116 | backend.generate(prompt, max_tokens=32) |
| 117 | |
| 118 | print(f"Benchmark ({n_bench})...") |
| 119 | times = [] |
| 120 | for i in range(n_bench): |
| 121 | t0 = time.time() |
| 122 | result = backend.generate(prompt, max_tokens=128) |
| 123 | elapsed = time.time() - t0 |
| 124 | tok = result.get("tokens_generated", 0) |
| 125 | tps = tok / elapsed if elapsed > 0 else 0 |
| 126 | times.append(tps) |
| 127 | print(f" [{i+1}] {tok} tok in {elapsed:.2f}s = {tps:.1f} tok/s") |
| 128 | |
| 129 | avg_tps = sum(times) / len(times) |
| 130 | print(f"\nAverage: {avg_tps:.1f} tok/s") |
| 131 | print(f"Sample: {result['text'][:100]}...") |