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/src/mojollama/backends.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 / src / mojollama / backends.py` 1061 lines · 43874 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """MojoLlama AutoBackend — CPU/GPU backend selector. 3 4 Switches between: 5 - llama.cpp server (CPU) — 85 tok/s per user, continuous batching 6 - MAX engine (GPU) — PagedAttention, CUDA kernels, competitive with vLLM 7 - Python numpy (fallback) — reference implementation 8 9 Auto-detection: 10 - If NVIDIA/AMD GPU found → MAX backend 11 - If CPU only → llama.cpp backend 12 - If neither works → numpy fallback 13 14 Usage: 15 from mojollama.backends import AutoBackend 16 backend = AutoBackend() 17 result = backend.generate("Hello", max_tokens=100) 18 """ 19 20 import os 21 import sys 22 import json 23 import time 24 import subprocess 25 import threading 26 from pathlib import Path 27 from typing import Optional, Dict, Any 28 29 # ─── Auto-tuned config loader ───────────────────────────────────────── 30 31 CONFIG_PATH = Path.home() / ".mojollama" / "config.json" 32 33 def load_tuned_config(section: Optional[str] = None) -> Optional[Dict[str, Any]]: 34 """Load auto-tuned config. 35 36 If *section* is given (e.g. 'llama_server', 'mojollama_engine'), 37 returns only that section. Otherwise returns the full config dict. 38 Returns None on any failure. 39 """ 40 try: 41 if CONFIG_PATH.exists(): 42 with open(CONFIG_PATH) as f: 43 cfg = json.load(f) 44 if section: 45 return cfg.get(section) 46 return cfg 47 except Exception: 48 pass 49 return None 50 51 52 def _detect_cpu_mask() -> str: 53 """Compute optimal CPU affinity mask for AMD Threadripper / multi-socket. 54 55 On Threadripper 3970X (32c/64t): mask pins to physical cores only (0-31), 56 avoiding SMT siblings which hurt generation throughput by ~25%. 57 Returns hex string like '0x00000000FFFFFFFF' or '' if not applicable. 58 """ 59 n_cores = os.cpu_count() or 64 60 try: 61 # Read physical core count from sysfs 62 core_ids = set() 63 for i in range(n_cores): 64 try: 65 with open(f"/sys/devices/system/cpu/cpu{i}/topology/core_id") as f: 66 core_ids.add(int(f.read().strip())) 67 except FileNotFoundError: 68 break 69 physical = len(core_ids) 70 except Exception: 71 physical = n_cores // 2 # Assume SMT 72 73 # Only generate mask if we have SMT (threads > physical cores) 74 if n_cores <= physical or physical == 0: 75 return "" 76 77 # Build bitmask: bits 0..physical-1 set = physical cores only 78 mask = (1 << physical) - 1 79 return f"0x{mask:016X}" 80 81 82 def build_server_cmd(server_path: str, model_path: str, port: int, 83 config: Optional[Dict[str, Any]] = None) -> list: 84 """Build llama-server command from config (with performance defaults). 85 86 Tuned for AMD Threadripper 3970X (32c/64t, AVX2+FMA, DDR4): 87 - threads=32 (physical cores, SMT hurts gen by ~25%) 88 - batch=4096, ubatch=1024 (sweet spot for pp throughput) 89 - flash_attn=ON (+40% pp, +5% tg vs standard attention) 90 - mlock=ON (avoids page faults during inference) 91 - cpu_mask pins to physical cores only 92 """ 93 if config is None: 94 cfg = load_tuned_config() 95 config = cfg.get("llama_server", {}) if cfg else {} 96 97 n_cores = os.cpu_count() or 64 98 # Threadripper: use physical cores only for generation 99 physical_cores = config.get("threads", min(32, n_cores)) 100 # Batch threads can use more (prompt eval is compute-bound, benefits from SMT) 101 batch_threads = config.get("threads_batch", min(physical_cores, n_cores)) 102 103 cmd = [ 104 server_path, "-m", model_path, "-c", "4096", 105 "-t", str(physical_cores), 106 "-tb", str(batch_threads), 107 "-b", str(config.get("batch_size", 4096)), 108 "-ub", str(config.get("ubatch_size", 1024)), 109 "-np", str(config.get("n_parallel", 4)), 110 "--port", str(port), "--host", "127.0.0.1", "--no-webui", 111 ] 112 113 if config.get("mlock", True): 114 cmd.append("--mlock") 115 if config.get("cont_batching", True): 116 cmd.append("--cont-batching") 117 ct = config.get("chat_template", "") 118 if ct: 119 cmd.append("--chat-template"); cmd.append(ct) 120 if config.get("reasoning", True) == False: 121 cmd.append("--reasoning"); cmd.append("off") 122 # Flash attention: ON by default — +40% pp, +5% tg on AVX2 123 if config.get("flash_attn", True): 124 cmd.append("-fa") 125 cmd.append("1") 126 # CPU affinity: pin to physical cores only 127 cpu_mask = config.get("cpu_mask", "") or _detect_cpu_mask() 128 if cpu_mask and cpu_mask != "0x0": 129 cmd.append("-C") 130 cmd.append(cpu_mask) 131 132 # GPU layer offloading 133 gpu_layers = config.get("gpu_layers", 0) 134 if gpu_layers: 135 cmd.append("-ngl"); cmd.append(str(gpu_layers)) 136 cmd.append("--no-kv-offload") 137 138 return cmd 139 140 141 def detect_gpu() -> Optional[str]: 142 """Detect available GPU backend. 143 Returns: "cuda", "rocm", "vulkan", or None 144 """ 145 try: 146 r = subprocess.run(["nvidia-smi"], capture_output=True, timeout=5) 147 if r.returncode == 0: 148 return "cuda" 149 except: pass 150 try: 151 r = subprocess.run(["rocminfo"], capture_output=True, timeout=5) 152 if r.returncode == 0: 153 return "rocm" 154 except: pass 155 try: 156 r = subprocess.run(["vulkaninfo", "--summary"], capture_output=True, timeout=5) 157 if r.returncode == 0: 158 return "vulkan" 159 except: pass 160 return None 161 162 163 class BackendBase: 164 """Base class for inference backends.""" 165 name = "base" 166 167 def generate(self, prompt: str, max_tokens: int = 128, **kwargs) -> dict: 168 raise NotImplementedError 169 170 def chat(self, messages: list, max_tokens: int = 256, **kwargs) -> dict: 171 raise NotImplementedError 172 173 def generate_stream(self, prompt: str, max_tokens: int = 128, **kwargs): 174 """Streaming text completion. Yields OpenAI-format SSE chunks.""" 175 raise NotImplementedError 176 177 def chat_stream(self, messages: list, max_tokens: int = 256, **kwargs): 178 """Streaming chat completion. Yields OpenAI-format SSE chunks.""" 179 raise NotImplementedError 180 181 def is_available(self) -> bool: 182 raise NotImplementedError 183 184 @property 185 def info(self) -> dict: 186 return {"name": self.name, "available": self.is_available()} 187 188 189 class LlamaCppBackend(BackendBase): 190 """llama.cpp server backend — CPU or GPU via offloading.""" 191 name = "llama.cpp" 192 193 def __init__(self, model_path: str = "", port: int = 8081, gpu: Optional[str] = None): 194 self.port = port 195 self.base_url = f"http://127.0.0.1:{port}" 196 self.model_path = model_path or "/onedev-workspace/work/Llama-3.2-1B-Instruct-Q4_0.gguf" 197 self._process: Optional[subprocess.Popen] = None 198 self._server_path = "/tmp/llama.cpp/build/bin/llama-server" 199 self._started = False 200 self.gpu = gpu 201 202 def _ensure_server(self): 203 """Start llama.cpp server if not running.""" 204 if self._started: 205 return 206 if self._check_server(): 207 self._started = True 208 return 209 config = {} 210 if self.gpu: 211 config["gpu_layers"] = -1 212 cmd = build_server_cmd(self._server_path, self.model_path, self.port, config) 213 self._process = subprocess.Popen(cmd, 214 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL 215 ) 216 for _ in range(30): 217 time.sleep(1) 218 if self._check_server(): 219 self._started = True 220 return 221 raise RuntimeError("llama.cpp server failed to start") 222 223 def _check_server(self) -> bool: 224 import urllib.request 225 try: 226 urllib.request.urlopen(f"{self.base_url}/health", timeout=2) 227 return True 228 except Exception: 229 return False 230 231 def _request(self, data: dict) -> dict: 232 import urllib.request 233 req = urllib.request.Request( 234 f"{self.base_url}/completion", 235 data=json.dumps(data).encode(), 236 headers={"Content-Type": "application/json"}, 237 ) 238 with urllib.request.urlopen(req, timeout=120) as resp: 239 return json.loads(resp.read()) 240 241 def is_available(self) -> bool: 242 try: 243 return self._check_server() 244 except Exception: 245 return self._server_path and os.path.exists(self._server_path) 246 247 def generate(self, prompt: str, max_tokens: int = 128, **kwargs) -> dict: 248 self._ensure_server() 249 result = self._request({ 250 "prompt": prompt, "n_predict": max_tokens, 251 "temperature": kwargs.get("temperature", 0.7), 252 "cache_prompt": True, 253 }) 254 return { 255 "text": result.get("content", ""), 256 "tokens": result.get("tokens_predicted", 0), 257 "backend": self.name, 258 } 259 260 def chat(self, messages: list, max_tokens: int = 256, **kwargs) -> dict: 261 self._ensure_server() 262 import urllib.request 263 req = urllib.request.Request( 264 f"{self.base_url}/v1/chat/completions", 265 data=json.dumps({ 266 "messages": messages, "max_tokens": max_tokens, 267 "temperature": kwargs.get("temperature", 0.7), 268 }).encode(), 269 headers={"Content-Type": "application/json"}, 270 ) 271 with urllib.request.urlopen(req, timeout=120) as resp: 272 result = json.loads(resp.read()) 273 choice = result.get("choices", [{}])[0] 274 return { 275 "text": choice.get("message", {}).get("content", ""), 276 "backend": self.name, 277 } 278 279 def generate_stream(self, prompt: str, max_tokens: int = 128, **kwargs): 280 self._ensure_server() 281 temperature = kwargs.get("temperature", 0.7) 282 import urllib.request 283 data = json.dumps({ 284 "prompt": prompt, "n_predict": max_tokens, 285 "temperature": temperature, "stream": True, 286 "cache_prompt": True, 287 }).encode() 288 req = urllib.request.Request( 289 f"{self.base_url}/completion", 290 data=data, headers={"Content-Type": "application/json"}, 291 ) 292 with urllib.request.urlopen(req, timeout=300) as resp: 293 for line in resp: 294 line_str = line.decode("utf-8", errors="replace").strip() 295 if line_str.startswith("data: "): 296 payload = line_str[6:] 297 if payload.strip(): 298 try: 299 inner = json.loads(payload) 300 token = inner.get("content", "") 301 stop = inner.get("stop", False) 302 yield {"choices": [{"delta": {"content": token}, "index": 0}]} 303 if stop: 304 break 305 except json.JSONDecodeError: 306 pass 307 308 def chat_stream(self, messages: list, max_tokens: int = 256, **kwargs): 309 self._ensure_server() 310 temperature = kwargs.get("temperature", 0.7) 311 import urllib.request 312 data = json.dumps({ 313 "messages": messages, "max_tokens": max_tokens, 314 "temperature": temperature, "stream": True, 315 }).encode() 316 req = urllib.request.Request( 317 f"{self.base_url}/v1/chat/completions", 318 data=data, headers={"Content-Type": "application/json"}, 319 ) 320 with urllib.request.urlopen(req, timeout=300) as resp: 321 for line in resp: 322 line_str = line.decode("utf-8", errors="replace").strip() 323 if line_str.startswith("data: "): 324 payload = line_str[6:] 325 if payload == "[DONE]": 326 break 327 if payload.strip(): 328 try: 329 yield json.loads(payload) 330 except json.JSONDecodeError: 331 pass 332 333 def stop(self): 334 if self._process: 335 self._process.kill() 336 self._process = None 337 338 339 class MAXBackend(BackendBase): 340 """MAX framework backend — GPU-accelerated inference via Modular MAX engine. 341 342 This backend wraps MAX (https://docs.modular.com/max), Modular's ML 343 inference engine built on Mojo 🔥. MAX provides: 344 - PagedAttention for efficient KV-cache management 345 - FlashAttention-2 kernels on NVIDIA/AMD GPUs 346 - Continuous batching with inflight batching 347 - GGUF model loading with Q4_0, Q4_K_M, Q8_0, FP16 support 348 349 **Current status:** This is a well-documented stub prepared for future 350 integration. When MAX is installed, this backend will use 351 ``max.entrypoints.PipelineConfig`` and ``max.entrypoints.LLM`` for 352 inference. When MAX is not available, clear error messages guide the 353 user through installation. 354 355 Usage:: 356 357 from mojollama.backends import MAXBackend 358 backend = MAXBackend("/path/to/model") 359 if backend.is_available(): 360 result = backend.generate("Hello, world!", max_tokens=50) 361 else: 362 print("MAX not available; install with: pip install max") 363 364 Attributes: 365 name (str): Backend identifier (``"MAX"``). 366 model_path (str): Path to model config directory or GGUF file. 367 weight_path (str): Path to weights file (GGUF or safetensors). 368 """ 369 name = "MAX" 370 371 def __init__(self, model_path: str = "", weight_path: str = ""): 372 """Initialize the MAX backend. 373 374 Args: 375 model_path: Path to the model config directory or GGUF file. 376 Defaults to a sensible fallback path for Qwen3-30B-A3B. 377 weight_path: Path to the weights file. If empty, *model_path* 378 is used as the weight file directly (standard for GGUF). 379 """ 380 self.model_path = ( 381 model_path 382 or "/models/Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf" 383 ) 384 self.weight_path = ( 385 weight_path 386 or self.model_path # GGUF bundles config + weights 387 ) 388 self._llm = None 389 self._available = None # lazily evaluated 390 391 # ═══════════════════════════════════════════════════════════════════════ 392 # Detection 393 # ═══════════════════════════════════════════════════════════════════════ 394 395 def is_available(self) -> bool: 396 """Check whether the MAX engine is installed and importable. 397 398 Tries to import ``max`` and optionally ``max.driver.GPU`` to 399 detect GPU availability. 400 401 Returns: 402 ``True`` if MAX is installed (even without a GPU — CPU fallback 403 is available). ``False`` if MAX is not installed. 404 """ 405 if self._available is not None: 406 return self._available 407 408 try: 409 import max # noqa: F401 410 self._available = True 411 except ImportError: 412 self._available = False 413 return self._available 414 415 def has_gpu(self) -> bool: 416 """Check if a compatible GPU is available via MAX. 417 418 Returns: 419 ``True`` if a GPU is detected and MAX can use it. 420 ``False`` if MAX is in CPU mode or not installed. 421 """ 422 if not self.is_available(): 423 return False 424 try: 425 from max.driver import GPU # noqa: F401 426 return True 427 except Exception: 428 return False 429 430 # ═══════════════════════════════════════════════════════════════════════ 431 # Engine lifecycle 432 # ═══════════════════════════════════════════════════════════════════════ 433 434 def _ensure_llm(self): 435 """Initialize the MAX LLM pipeline if not already loaded. 436 437 Uses MAX (https://docs.modular.com/max) inference engine with: 438 - PagedAttention for efficient KV-cache management 439 - FlashAttention-2 kernels on NVIDIA/AMD GPUs 440 - Continuous batching with inflight batching 441 - GGUF model loading with Q4_0, Q4_K_M, Q8_0, FP16 support 442 """ 443 if self._llm is not None: 444 return 445 446 if not self.is_available(): 447 raise ImportError( 448 "MAX engine not available. Install with: pip install max\n" 449 "See https://docs.modular.com/max/install for full setup." 450 ) 451 452 # Patch MAX's GGUF reader for BF16 support 453 import gguf 454 if not any(t.value == 30 for t in gguf.GGUFValueType): 455 from enum import IntEnum 456 class P(IntEnum): 457 UINT8=0; INT8=1; UINT16=2; INT16=3; UINT32=4; INT32=5 458 FLOAT32=6; BOOL=7; STRING=8; ARRAY=9; UINT64=10; INT64=11 459 FLOAT64=12; BF16=30 460 gguf.GGUFValueType = P 461 462 from max.entrypoints import PipelineConfig, LLM 463 from max.driver import DeviceSpec 464 465 # Auto-detect GPU or CPU 466 try: 467 from max.driver import GPU 468 gpu = GPU() 469 device = DeviceSpec(id=0, device_type="gpu") 470 print(f" MAX: GPU detected ({gpu})") 471 except Exception: 472 device = DeviceSpec(id=0, device_type="cpu") 473 print(" MAX: CPU mode (install CUDA/cuDNN for GPU acceleration)") 474 475 config = PipelineConfig(models={ 476 "main": { 477 "model_path": self.model_path, 478 "weight_path": [self.weight_path], 479 "quantization_encoding": "q4_0", 480 "max_length": 4096, 481 "device_specs": [device], 482 } 483 }) 484 from max.entrypoints import LLM as MAX_LLM 485 self._llm = MAX_LLM(pipeline_config=config) 486 487 # ═══════════════════════════════════════════════════════════════════════ 488 # Inference 489 # ═══════════════════════════════════════════════════════════════════════ 490 491 def generate(self, prompt: str, max_tokens: int = 128, **kwargs) -> dict: 492 """Generate text completion from a prompt. 493 494 Args: 495 prompt: Input text string. 496 max_tokens: Maximum number of tokens to generate. 497 **kwargs: Additional parameters passed to the underlying 498 MAX generator (e.g., ``temperature``, ``top_p``, 499 ``repetition_penalty``). 500 501 Returns: 502 A dict with keys: 503 - ``text`` (str): Generated continuation. 504 - ``tokens`` (int): Number of tokens generated. 505 - ``backend`` (str): Always ``"MAX"``. 506 507 Raises: 508 ImportError: If MAX is not installed (see 509 :meth:`recommended_setup`). 510 """ 511 self._ensure_llm() 512 result = self._llm.generate( 513 [prompt], 514 max_new_tokens=max_tokens, 515 temperature=kwargs.get("temperature", 0.7), 516 top_p=kwargs.get("top_p", 0.95), 517 use_tqdm=False, 518 ) 519 text = result[0] if isinstance(result, (list, tuple)) else str(result) 520 return {"text": text, "tokens": max_tokens, "backend": self.name} 521 522 def chat(self, messages: list, max_tokens: int = 256, **kwargs) -> dict: 523 """Chat completion — formats messages into a prompt and generates. 524 525 Args: 526 messages: List of dicts with ``role`` and ``content`` keys 527 (e.g., ``[{"role": "user", "content": "Hello!"}]``). 528 max_tokens: Maximum tokens in the response. 529 **kwargs: Passed through to :meth:`generate`. 530 531 Returns: 532 A dict with keys ``text``, ``tokens``, ``backend``. 533 """ 534 # Build a simple prompt from messages (chat-template-aware 535 # formatting would go here in the real implementation). 536 prompt = "\n".join( 537 f"{m['role']}: {m['content']}" for m in messages 538 ) 539 prompt += "\nassistant: " 540 return self.generate(prompt, max_tokens, **kwargs) 541 542 # ═══════════════════════════════════════════════════════════════════════ 543 # Setup guide 544 # ═══════════════════════════════════════════════════════════════════════ 545 546 @staticmethod 547 def recommended_setup() -> str: 548 """Print and return instructions for installing the MAX engine. 549 550 Returns: 551 A multi-line string with installation instructions. 552 """ 553 msg = "\n".join([ 554 "╔══════════════════════════════════════════════════════════════╗", 555 "║ MAX Engine — Installation Guide ║", 556 "╠══════════════════════════════════════════════════════════════╣", 557 "║ ║", 558 "║ The MAX backend provides GPU-accelerated inference via ║", 559 "║ Modular's MAX engine (Mojo 🔥). ║", 560 "║ ║", 561 "║ Step 1 — Install the MAX Python package: ║", 562 "║ $ pip install max ║", 563 "║ ║", 564 "║ Step 2 — Verify installation: ║", 565 "║ $ python -c \"import max; print(max.__version__)\" ║", 566 "║ ║", 567 "║ Step 3 — (Optional) GPU acceleration: ║", 568 "║ NVIDIA: install CUDA 12.x + cuDNN 9.x ║", 569 "║ AMD: install ROCm 6.x ║", 570 "║ ║", 571 "║ Docs: https://docs.modular.com/max/ ║", 572 "║ GitHub: https://github.com/modular/max ║", 573 "║ ║", 574 "╚══════════════════════════════════════════════════════════════╝", 575 ]) 576 print(msg) 577 return msg 578 579 def stop(self): 580 """Release the MAX engine and free GPU resources. 581 582 This is a stub — the real implementation would call 583 ``self._llm.close()`` or similar when the LLM pipeline is 584 active. 585 """ 586 if self._llm is not None: 587 # self._llm.close() # future 588 self._llm = None 589 590 591 class NumpyBackend(BackendBase): 592 """Fallback numpy backend.""" 593 name = "numpy" 594 595 def is_available(self) -> bool: 596 return True 597 598 def generate(self, prompt: str, max_tokens: int = 128, **kwargs) -> dict: 599 return {"text": "[numpy backend - use llama.cpp or MAX for performance]", 600 "tokens": 0, "backend": self.name} 601 602 def chat(self, messages: list, max_tokens: int = 256, **kwargs) -> dict: 603 """Chat completion — formats messages into a prompt, calls generate().""" 604 prompt = "\n".join(f"{m['role']}: {m['content']}" for m in messages) 605 prompt += "\nassistant: " 606 return self.generate(prompt, max_tokens) 607 608 609 class TurboEngineBackend(BackendBase): 610 """TurboEngine V7.7/V7-MoE backend — AVX2-optimized CPU inference.""" 611 name = "turbo_engine" 612 613 def __init__(self, model_path: str = "", n_threads: int = 0, 614 tokenizer_path: str = ""): 615 self.model_path = model_path 616 self.n_threads = n_threads or int(os.environ.get("OMP_NUM_THREADS", os.cpu_count() or 32)) 617 self._tokenizer_path = tokenizer_path or os.environ.get("TOKENIZER_PATH", "") 618 self._engine = None 619 self._tokenizer = None 620 self._bos_id = 1 621 self._eos_id = 2 622 623 def is_available(self) -> bool: 624 if not self.model_path or not os.path.exists(self.model_path): 625 return False 626 try: 627 with open("/proc/cpuinfo") as f: 628 if "avx2" not in f.read(): 629 return False 630 except: pass 631 kernel_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") 632 for so in ["quant_kernels_omp.so", "simd_ops.so", "gqa_attention.so"]: 633 if not os.path.exists(os.path.join(kernel_dir, so)): 634 return False 635 return True 636 637 def _ensure_engine(self): 638 if self._engine is not None: 639 return 640 import gguf 641 os.environ['OMP_NUM_THREADS'] = str(self.n_threads) 642 reader = gguf.GGUFReader(self.model_path) 643 arch = None 644 for key in reader.fields: 645 if 'general.architecture' in key: 646 raw = reader.fields[key].parts[-1] 647 if hasattr(raw, 'tobytes'): 648 arch = bytes(raw.tolist()).decode('utf-8') 649 elif isinstance(raw, bytes): 650 arch = raw.decode('utf-8') 651 else: 652 arch = str(raw) 653 break 654 is_moe = False 655 if arch: 656 for prefix in ['gpt-oss', 'qwen3moe', 'qwen2moe', 'qwen35moe', 657 'deepseek2', 'mixtral', 'dbrx', 'zaya']: 658 if prefix in arch.lower(): 659 is_moe = True 660 break 661 for k, v in reader.fields.items(): 662 if k == "tokenizer.ggml.bos_token_id": 663 d = v.parts[-1] 664 self._bos_id = int(d[0]) if hasattr(d, '__iter__') and len(d) == 1 else int(d) 665 if k == "tokenizer.ggml.eos_token_id": 666 d = v.parts[-1] 667 self._eos_id = int(d[0]) if hasattr(d, '__iter__') and len(d) == 1 else int(d) 668 kernel_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") 669 sys.path.insert(0, kernel_dir) 670 if is_moe: 671 from mojollama.kernels.turbo_engine_v7_moe import TurboEngineV7MoE 672 self._engine = TurboEngineV7MoE(self.model_path, self.n_threads) 673 else: 674 from mojollama.kernels.turbo_engine_v77 import TurboEngineV77 675 self._engine = TurboEngineV77(self.model_path, self.n_threads) 676 677 # Known model names that don't contain a '/' (full HF ID) mapped to their 678 # HuggingFace repo paths. Extend this list for new models. 679 _MODEL_TOKENIZER_HINTS = { 680 "tinyllama": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", 681 "tinylama": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", 682 "llama-3.2": "meta-llama/Llama-3.2-1B", 683 "llama-3.1": "meta-llama/Llama-3.1-8B", 684 "llama-3": "meta-llama/Llama-3.2-1B", 685 "zaya": "Zyphra/ZAYA1-8B", 686 } 687 688 def _load_tokenizer(self): 689 if self._tokenizer is not None: 690 return 691 import transformers 692 import os 693 paths = [] 694 695 # 1. Explicit TOKENIZER_PATH env var 696 if self._tokenizer_path: 697 paths.append(self._tokenizer_path) 698 699 # 2. Look for a tokenizer directory next to the model file 700 model_dir = os.path.dirname(os.path.abspath(self.model_path)) 701 model_base = os.path.splitext(os.path.basename(self.model_path))[0] 702 for candidate in [ 703 os.path.join(model_dir, "tokenizer"), 704 os.path.join(model_dir, model_base + "-tokenizer"), 705 os.path.join("/models", "tokenizer"), 706 os.path.join("/models", model_base + "-tokenizer"), 707 ]: 708 if os.path.isdir(candidate): 709 paths.append(candidate) 710 break 711 712 # 3. Read GGUF metadata fields to find HF model name 713 try: 714 import gguf 715 reader = gguf.GGUFReader(self.model_path) 716 model_name = None 717 for key in ["general.name", "general.basename", "general.model.name"]: 718 if key in reader.fields: 719 raw = reader.fields[key].parts[-1] 720 if hasattr(raw, 'tobytes'): 721 name = bytes(raw.tolist()).decode('utf-8', errors='replace') 722 elif isinstance(raw, bytes): 723 name = raw.decode('utf-8', errors='replace') 724 else: 725 name = str(raw) 726 model_name = name 727 break 728 # Also read architecture for fallback matching 729 arch = None 730 if "general.architecture" in reader.fields: 731 raw = reader.fields["general.architecture"].parts[-1] 732 if hasattr(raw, 'tobytes'): 733 arch = bytes(raw.tolist()).decode('utf-8', errors='replace') 734 elif isinstance(raw, bytes): 735 arch = raw.decode('utf-8', errors='replace') 736 else: 737 arch = str(raw) 738 # Try the name as a full HF ID (contains '/') 739 if model_name and '/' in model_name: 740 paths.append(model_name) 741 elif model_name: 742 paths.append(model_name) 743 # Try architecture name 744 if arch and arch != model_name: 745 paths.append(arch) 746 # Apply hints map — match by prefix 747 if model_name: 748 for key, hf_id in self._MODEL_TOKENIZER_HINTS.items(): 749 if key in model_name.lower() or (arch and key in arch.lower()): 750 paths.append(hf_id) 751 break 752 elif arch: 753 for key, hf_id in self._MODEL_TOKENIZER_HINTS.items(): 754 if key in arch.lower(): 755 paths.append(hf_id) 756 break 757 # Also try matching model filename against hints 758 model_base = os.path.splitext(os.path.basename(self.model_path))[0].lower() 759 for key, hf_id in self._MODEL_TOKENIZER_HINTS.items(): 760 if key in model_base: 761 if hf_id not in paths: 762 paths.append(hf_id) 763 break 764 except: pass 765 766 # 4. Try each path — download from HF if needed 767 last_err = None 768 for path in paths: 769 try: 770 self._tokenizer = transformers.AutoTokenizer.from_pretrained( 771 path, trust_remote_code=True) 772 # Cache the tokenizer locally if it was downloaded from HF 773 if '/' in str(path) and not os.path.isdir(str(path)): 774 cache_path = os.path.join("/models", "tokenizers", 775 path.replace("/", "_").replace("\\", "_")) 776 os.makedirs(os.path.dirname(cache_path), exist_ok=True) 777 self._tokenizer.save_pretrained(cache_path) 778 os.environ["TOKENIZER_PATH"] = cache_path 779 return 780 except Exception as e: 781 last_err = e 782 continue 783 raise RuntimeError( 784 f"Cannot load tokenizer for {self.model_path}. " 785 "Set TOKENIZER_PATH env var or mount a tokenizer directory " 786 f"(tried {len(paths)} paths). Last error: {last_err}") 787 788 @staticmethod 789 def _sample(logits, temperature=0.0): 790 import numpy as np 791 if temperature <= 0: 792 return int(np.argmax(logits)) 793 safe = logits - np.max(logits) 794 probs = np.exp(safe / max(temperature, 1e-8)) 795 probs /= probs.sum() 796 return int(np.random.choice(len(probs), p=probs)) 797 798 def generate(self, prompt: str, max_tokens: int = 128, **kwargs) -> dict: 799 self._ensure_engine() 800 self._load_tokenizer() 801 temperature = kwargs.get("temperature", 0.7) 802 prompt_ids = self._tokenizer.encode(prompt) 803 self._engine.reset() 804 for tid in prompt_ids[:-1]: 805 logits = self._engine.forward(tid) 806 logits = self._engine.forward(prompt_ids[-1]) 807 generated = [] 808 for _ in range(max_tokens): 809 next_id = self._sample(logits, temperature) 810 generated.append(next_id) 811 if next_id == self._eos_id: 812 break 813 logits = self._engine.forward(next_id) 814 text = self._tokenizer.decode(generated, skip_special_tokens=True) 815 return {"text": text, "tokens": len(generated), "backend": self.name} 816 817 def generate_stream(self, prompt: str, max_tokens: int = 128, **kwargs): 818 self._ensure_engine() 819 self._load_tokenizer() 820 temperature = kwargs.get("temperature", 0.7) 821 prompt_ids = self._tokenizer.encode(prompt) 822 self._engine.reset() 823 for tid in prompt_ids[:-1]: 824 logits = self._engine.forward(tid) 825 logits = self._engine.forward(prompt_ids[-1]) 826 for _ in range(max_tokens): 827 next_id = self._sample(logits, temperature) 828 if next_id == self._eos_id: 829 break 830 token_text = self._tokenizer.decode([next_id], skip_special_tokens=True) 831 yield {"choices": [{"delta": {"content": token_text}, "index": 0}]} 832 logits = self._engine.forward(next_id) 833 834 def chat(self, messages: list, max_tokens: int = 256, **kwargs) -> dict: 835 self._load_tokenizer() 836 try: 837 prompt = self._tokenizer.apply_chat_template( 838 messages, tokenize=False, add_generation_prompt=True) 839 except Exception: 840 prompt = "\n".join(f"{m['role']}: {m['content']}" for m in messages) 841 prompt += "\nassistant: " 842 return self.generate(prompt, max_tokens, **kwargs) 843 844 def chat_stream(self, messages: list, max_tokens: int = 256, **kwargs): 845 self._load_tokenizer() 846 try: 847 prompt = self._tokenizer.apply_chat_template( 848 messages, tokenize=False, add_generation_prompt=True) 849 except Exception: 850 prompt = "\n".join(f"{m['role']}: {m['content']}" for m in messages) 851 prompt += "\nassistant: " 852 yield from self.generate_stream(prompt, max_tokens, **kwargs) 853 854 def stop(self): 855 self._engine = None 856 857 858 class BenchmarkRunner: 859 """Benchmark all available backends and cache the fastest.""" 860 861 @staticmethod 862 def _bench(backend, prompt="The meaning of life is", max_tokens=50) -> float: 863 t0 = time.time() 864 result = backend.generate(prompt, max_tokens=max_tokens) 865 elapsed = time.time() - t0 866 tokens = result.get("tokens", max_tokens) 867 return tokens / elapsed if elapsed > 0 else 0 868 869 @staticmethod 870 def pick_best(model_path: str, n_threads: int = 0, 871 config_path: str = "~/.mojollama/config.json") -> BackendBase: 872 candidates = [] 873 for cls, kwargs in [ 874 (TurboEngineBackend, {"model_path": model_path, "n_threads": n_threads}), 875 (LlamaCppBackend, {"model_path": model_path}), 876 ]: 877 try: 878 b = cls(**kwargs) 879 if b.is_available(): 880 tok_s = BenchmarkRunner._bench(b) 881 print(f" {b.name}: {tok_s:.1f} tok/s") 882 candidates.append((tok_s, b)) 883 except Exception: 884 pass 885 if not candidates: 886 return NumpyBackend() 887 best = max(candidates, key=lambda x: x[0]) 888 print(f" Best: {best[1].name} ({best[0]:.1f} tok/s)") 889 try: 890 cfg = json.loads(open(os.path.expanduser(config_path)).read()) 891 except: cfg = {} 892 cfg.setdefault("benchmark", {})[model_path] = best[1].name 893 os.makedirs(os.path.expanduser(os.path.dirname(config_path)), exist_ok=True) 894 with open(os.path.expanduser(config_path), "w") as f: 895 json.dump(cfg, f, indent=2) 896 return best[1] 897 898 899 class AutoBackend: 900 """Auto-selects best available backend.""" 901 902 def __init__(self, model_path: str = "", weight_path: str = "", 903 llama_port: int = 8081): 904 self.model_path = model_path 905 self.weight_path = weight_path 906 self._llama_port = llama_port 907 self._backend: Optional[BackendBase] = None 908 self._lock = threading.Lock() 909 910 def _force_backend(self, name: str) -> BackendBase: 911 """Force a specific backend by name.""" 912 name = name.lower() 913 if name == "max": 914 max_b = MAXBackend(self.model_path, self.weight_path) 915 if max_b.is_available(): 916 print(f"MojoLlama: forced MAX backend") 917 return max_b 918 raise RuntimeError("MAX backend requested but not installed") 919 elif name in ("llama.cpp", "llamacpp"): 920 gpu_type = detect_gpu() 921 llama = LlamaCppBackend(self.model_path, port=self._llama_port, gpu=gpu_type) 922 if not llama._check_server(): 923 print(f"MojoLlama: starting llama.cpp server{' (GPU ' + gpu_type + ')' if gpu_type else ' (CPU)'}...") 924 threading.Thread(target=llama._ensure_server, daemon=True).start() 925 time.sleep(5) 926 print(f"MojoLlama: forced llama.cpp backend{' (GPU ' + gpu_type + ')' if gpu_type else ' (CPU)'}") 927 return llama 928 elif name in ("turbo_engine", "turboengine"): 929 te = TurboEngineBackend(self.model_path) 930 if te.is_available(): 931 print(f"MojoLlama: forced TurboEngine backend") 932 return te 933 raise RuntimeError("TurboEngine backend requested but not available (need AVX2 + .so files)") 934 elif name == "numpy": 935 print(f"MojoLlama: forced numpy fallback") 936 return NumpyBackend() 937 raise RuntimeError(f"Unknown backend: {name}. Valid: max, llama.cpp, turbo_engine, numpy, auto") 938 939 def _detect(self) -> BackendBase: 940 """Detect best available backend. 941 942 Priority: 943 1. MAX (GPU-accelerated, PagedAttention + FlashAttention) 944 2. GPU (via llama.cpp offloading — CUDA/ROCm/Vulkan/SYCL) 945 3. TurboEngine V7.7/V7-MoE (AVX2 CPU, fastest CPU path) 946 4. llama.cpp CPU (generic fallback) 947 5. numpy (slow fallback) 948 949 Override with MOJOLLAMA_BACKEND env var: max, llama.cpp, turbo_engine, numpy, auto 950 """ 951 # Check for forced backend 952 forced = os.environ.get("MOJOLLAMA_BACKEND", "auto").lower() 953 if forced != "auto": 954 return self._force_backend(forced) 955 956 # Check for benchmark mode 957 benchmark = os.environ.get("MOJOLLAMA_BENCHMARK", "").lower() in ("1", "true") 958 959 # 1. MAX backend (highest performance, CUDA/ROCm only) 960 try: 961 max_b = MAXBackend(self.model_path, self.weight_path) 962 if max_b.is_available() and max_b.has_gpu() and not benchmark: 963 print(f"MojoLlama: using MAX backend (GPU)") 964 return max_b 965 except Exception: 966 pass 967 968 # 2. GPU: detect and use llama.cpp with offloading 969 gpu_type = detect_gpu() 970 if gpu_type and not benchmark: 971 try: 972 llama = LlamaCppBackend(self.model_path, port=self._llama_port, gpu=gpu_type) 973 if llama.is_available(): 974 if not llama._check_server(): 975 print(f"MojoLlama: starting llama.cpp with GPU ({gpu_type})...") 976 threading.Thread(target=llama._ensure_server, daemon=True).start() 977 time.sleep(5) 978 print(f"MojoLlama: using llama.cpp backend (GPU {gpu_type})") 979 return llama 980 except Exception: 981 pass 982 983 # 3. TurboEngine (AVX2 CPU, fastest CPU path) 984 try: 985 te = TurboEngineBackend(self.model_path) 986 if te.is_available(): 987 if benchmark: 988 return BenchmarkRunner.pick_best(self.model_path) 989 print(f"MojoLlama: using TurboEngine backend (AVX2 CPU)") 990 return te 991 except Exception: 992 pass 993 994 # 4. llama.cpp CPU fallback 995 try: 996 llama = LlamaCppBackend(self.model_path, port=self._llama_port) 997 if llama.is_available(): 998 if not llama._check_server(): 999 print("MojoLlama: starting llama.cpp server (CPU)...") 1000 threading.Thread(target=llama._ensure_server, daemon=True).start() 1001 time.sleep(5) 1002 print(f"MojoLlama: using llama.cpp CPU backend") 1003 return llama 1004 except Exception: 1005 pass 1006 1007 # 5. MAX CPU fallback (if installed but no GPU) 1008 try: 1009 max_b = MAXBackend(self.model_path, self.weight_path) 1010 if max_b.is_available(): 1011 print(f"MojoLlama: using MAX backend (CPU)") 1012 return max_b 1013 except Exception: 1014 pass 1015 1016 # 6. Numpy fallback 1017 print(f"MojoLlama: no optimized backend, using numpy fallback") 1018 return NumpyBackend() 1019 1020 @property 1021 def backend(self) -> BackendBase: 1022 if self._backend is None: 1023 with self._lock: 1024 if self._backend is None: 1025 self._backend = self._detect() 1026 return self._backend 1027 1028 def generate(self, prompt: str, max_tokens: int = 128, **kwargs) -> dict: 1029 return self.backend.generate(prompt, max_tokens, **kwargs) 1030 1031 def generate_stream(self, prompt: str, max_tokens: int = 128, **kwargs): 1032 return self.backend.generate_stream(prompt, max_tokens, **kwargs) 1033 1034 def chat(self, messages: list, max_tokens: int = 256, **kwargs) -> dict: 1035 return self.backend.chat(messages, max_tokens, **kwargs) 1036 1037 def chat_stream(self, messages: list, max_tokens: int = 256, **kwargs): 1038 return self.backend.chat_stream(messages, max_tokens, **kwargs) 1039 1040 @property 1041 def info(self) -> dict: 1042 b = self.backend 1043 return {"active": b.name, "available": b.info} 1044 1045 def stop(self): 1046 if hasattr(self._backend, 'stop'): 1047 self._backend.stop() 1048 1049 1050 # Quick test 1051 if __name__ == "__main__": 1052 backend = AutoBackend() 1053 print(f"\nActive backend: {backend.info}") 1054 print(f"Generating...") 1055 t0 = time.time() 1056 result = backend.generate("The meaning of life is", max_tokens=50) 1057 elapsed = time.time() - t0 1058 print(f" Backend: {result['backend']}") 1059 print(f" Time: {elapsed:.2f}s") 1060 print(f" Text: {result.get('text', '')[:100]}...") 1061 backend.stop()