File size: 8,698 Bytes
f317795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""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