"""OpenJev CPU runtime — llama-cpp-python inference engine (zero GPU). Loads the official `openjev/openjev-GGUF` OpenJev-Q4_K_M.gguf (16.5 GB, ~4.8 bits, text-only, one token per letter) with llama-cpp-python's Llama class, n_gpu_layers=0, and exposes exactly the primitives the readout needs: * token_score(prompt, token_id) -> log-prob at the first output position * letter_scores(prompt) -> log-prob for every letter, aligned to LETTERS * prewarm(text) / healthy() / info() Readout protocol: this is the *text-matched top-K fallback* of openjev-server's vLLM backend (vllm.py): it requests the top-64 logprobs at the first output position and matches candidate letters by text (bare form preferred over a whitespace-padded look-alike). A letter outside the top-64 is floored at -30.0 (MISSING) by the readout layer, exactly like the official server floors it. This is precisely the protocol the GGUF README describes ("read the letter tokens at the first output position"), and it is the reason a plain llama.cpp instance can serve as the backend. Installation note (Free / CPU Basic tier): requirements.txt pins llama-cpp-python==0.3.23 (CPU wheels, no GPU dependency). On CPU basic (2 vCPU / 16 GB RAM) the 16.5 GB Q4_K_M model does NOT fit in RAM along with the runtime. For a non-PRO account, host this Space on CPU Upgrade (32 GB RAM, $0.03/hr, still zero GPU); for a PRO account, CPU basic works for Gradio compute Spaces (free accounts cannot create them at all - see README.md). Environment variables (all optional): OPENJEV_GGUF_REPO - HF repo id of the GGUF (default openjev/openjev-GGUF) OPENJEV_GGUF_FILE - file inside the repo (default OpenJev-Q4_K_M.gguf) OPENJEV_CTX - context window in tokens (default 16384) OPENJEV_THREADS - CPU threads (default: all online logical cores) """ from __future__ import annotations import os import time from typing import Optional GGUF_REPO = os.environ.get("OPENJEV_GGUF_REPO", "openjev/openjev-GGUF") GGUF_FILE = os.environ.get("OPENJEV_GGUF_FILE", "OpenJev-Q4_K_M.gguf") CTX = int(os.environ.get("OPENJEV_CTX", "16384")) THREADS = int(os.environ.get("OPENJEV_THREADS", "0")) or os.cpu_count() or 4 # The 52 single-letter option labels used by openjev-server (letters.py). LETTERS = [chr(65 + i) for i in range(26)] + [chr(97 + i) for i in range(26)] # Text-matched fallback floor from openjev-server/backends/vllm.py. MISSING_LOGPROB = -30.0 # How many top logprobs to request; mirrors max(20, len(options)) capped at 64. TOP_K = 64 class CoreEngine: """Thin wrapper over a llama-cpp-python Llama instance.""" def __init__(self) -> None: self._llm = None self._token_to_id: Optional[dict[str, int]] = None self._id_to_token: Optional[dict[int, str]] = None self._loaded_at = 0.0 self._load_error: Optional[str] = None # ------------------------------------------------------------------ lifecycle def load(self) -> None: """Import llama_cpp lazily so the requirements are only needed at load time.""" try: from llama_cpp import Llama except Exception as exc: # pragma: no cover - environment dependent self._load_error = f"llama-cpp-python import failed: {exc}" raise t0 = time.perf_counter() try: self._llm = Llama( model_path=f"{GGUF_REPO}/{GGUF_FILE}", n_ctx=CTX, n_threads=THREADS, n_gpu_layers=0, # <-- ZERO GPU. This is the whole point. verbose=False, logits_all=False, embedding=False, ) except Exception as exc: # pragma: no cover - download/runtime failure self._load_error = f"llama-cpp-python load failed: {exc}" raise self._loaded_at = time.perf_counter() self._build_letter_table() def _build_letter_table(self) -> None: """Map each single-letter label to its token id (bare first, then space-prefixed).""" tok = self._llm.tokenizer() variants: dict[str, dict[str, int]] = {} for pre in ("", " "): ids: dict[str, int] = {} ok = True for letter in LETTERS: enc = tok.encode(pre + letter, add_special_tokens=False) if len(enc) != 1: ok = False break ids[letter] = enc[0] if ok and len(set(ids.values())) == len(ids): variants[pre] = ids if not variants: raise ValueError("neither 'A' nor ' A' are single unique tokens: this model cannot serve a letter readout") pre = "" if "" in variants else " " self._id_to_token = {v: k for k, v in variants[pre].items()} self._token_to_id = variants[pre] # ------------------------------------------------------------------ scoring def _first_position_top(self, prompt: str) -> dict[str, float]: """Top-K logprobs at the first output position, keyed by token text.""" if self._llm is None: raise RuntimeError("engine not loaded") out = self._llm.create_completion( prompt, max_tokens=1, temperature=0.0, top_p=1.0, logprobs=TOP_K, echo=False, ) data = (out.get("choices") or [{}])[0] lp = data.get("logprobs") or {} tops = (lp.get("top_logprobs") or [{}])[0] normalized: dict[str, float] = {} for key, value in (tops or {}).items(): f = _parse_float(value) if f is None: continue normalized[str(key)] = f return normalized def token_score(self, prompt: str, token_id: int) -> Optional[float]: """Log-probability of `token_id` at the first output position (None if outside top-K).""" tops = self._first_position_top(prompt) return tops.get(str(token_id)) def letter_scores(self, prompt: str) -> dict[str, float]: """Log-probability for every supported letter at the first output position. A letter not in the top-K comes back absent (the readout floors it). This mirrors openjev-server's text-matched fallback behaviour exactly. """ if self._token_to_id is None: self._build_letter_table() tops = self._first_position_top(prompt) resolved: dict[str, float] = {} for letter, tid in self._token_to_id.items(): val = tops.get(str(tid)) if val is None and letter in tops: val = tops[letter] if val is None and " " + letter in tops: val = tops[" " + letter] if val is not None: resolved[letter] = val return resolved # ------------------------------------------------------------------ helpers def header_tokens(self, text: str) -> int: """Token count the model will prefill for a chat template + `text` (used by pad_prefix).""" if self._llm is None: return 0 try: return len(self._llm.tokenize(text.encode("utf-8"), add_special_tokens=True)) except Exception: try: return len(self._llm.tokenizer().encode(text, add_special_tokens=True)) except Exception: return 0 def prewarm(self, text: str) -> bool: """Preload the prompt cache with one forward pass. Returns True when ready.""" if self._llm is None: return False try: self._llm.create_completion(text, max_tokens=1, temperature=0.0, logprobs=TOP_K, echo=False) return True except Exception: return False def healthy(self) -> bool: return self._llm is not None def info(self) -> dict: return { "repo": GGUF_REPO, "file": GGUF_FILE, "quant": GGUF_FILE.split(".")[0], "n_ctx": CTX, "n_threads": THREADS, "gpu_layers": 0, "letters": len(LETTERS), "load_ms": round((time.perf_counter() - self._loaded_at) * 1000) if self._loaded_at else None, "load_error": self._load_error, } def close(self) -> None: try: if self._llm is not None: self._llm.close() except Exception: pass self._llm = None def _parse_float(x) -> Optional[float]: try: f = float(x) return f if f == f else None # NaN -> None except (TypeError, ValueError): return None