@simplexai/localmodels-darwin-arm64 0.1.0-dev.39 → 0.1.0-dev.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +70 -69
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/auth_proxy.py +74 -16
- package/modules/localmodels/budget.py +27 -18
- package/modules/localmodels/catalog.json +4 -130
- package/modules/localmodels/catalog.py +10 -0
- package/modules/localmodels/chat_template.py +35 -0
- package/modules/localmodels/debug_mode.py +8 -0
- package/modules/localmodels/deploy.py +7 -1
- package/modules/localmodels/download-mirrors.json +0 -8
- package/modules/localmodels/gateway.py +2 -0
- package/modules/localmodels/gateway_bifrost.py +3 -0
- package/modules/localmodels/gateway_home.py +132 -0
- package/modules/localmodels/harness.py +48 -13
- package/modules/localmodels/harness_probe.py +5 -1
- package/modules/localmodels/library_gateway.py +13 -2
- package/modules/localmodels/library_jobs.py +63 -6
- package/modules/localmodels/library_model.py +60 -15
- package/modules/localmodels/library_pricing.py +99 -26
- package/modules/localmodels/library_serve.py +69 -14
- package/modules/localmodels/library_state.py +33 -2
- package/modules/localmodels/library_status.py +109 -13
- package/modules/localmodels/llm_rank.py +16 -27
- package/modules/localmodels/metal.py +29 -12
- package/modules/localmodels/probe.py +4 -0
- package/modules/localmodels/recommend.py +30 -13
- package/modules/localmodels/recommend_cli.py +6 -4
- package/modules/localmodels/remote_ops_download.py +75 -14
- package/modules/localmodels/remote_ops_remove.py +15 -0
- package/modules/localmodels/remote_ops_service.py +10 -0
- package/modules/localmodels/reuse.py +31 -5
- package/modules/localmodels/runtime_cli.py +61 -40
- package/modules/localmodels/runtime_discovery.py +38 -10
- package/modules/localmodels/runtime_install.py +31 -10
- package/modules/localmodels/runtime_io.py +4 -3
- package/modules/localmodels/runtime_pi.py +71 -19
- package/modules/localmodels/runtime_process.py +4 -2
- package/modules/localmodels/service_deployment.py +5 -3
- package/modules/localmodels/service_probe.py +84 -27
- package/modules/localmodels/setup_inspection.py +104 -25
- package/modules/localmodels/setup_text.py +12 -5
- package/modules/localmodels/sizecalc.py +0 -2
- package/modules/localmodels/slot_cache.py +467 -0
- package/modules/localmodels/stack_binding.py +90 -13
- package/modules/localmodels/stack_capacity.py +3 -3
- package/modules/localmodels/stack_card.py +1 -0
- package/modules/localmodels/stack_compose.py +2 -3
- package/modules/localmodels/stack_down.py +22 -7
- package/modules/localmodels/stack_events.py +59 -0
- package/modules/localmodels/stack_hardware.py +35 -29
- package/modules/localmodels/stack_hardware_text.py +40 -35
- package/modules/localmodels/stack_lifecycle.py +12 -3
- package/modules/localmodels/stack_mlx.py +4 -1
- package/modules/localmodels/stack_picks.py +6 -1
- package/modules/localmodels/stack_plan.py +1 -0
- package/modules/localmodels/stack_rollback.py +9 -4
- package/modules/localmodels/stack_summary.py +2 -0
- package/modules/localmodels/stack_up.py +27 -20
- package/modules/localmodels/stack_update.py +3 -1
- package/modules/localmodels/stack_warm.py +21 -11
- package/modules/localmodels/stack_warm_store.py +5 -16
- package/modules/localmodels/tools.json +1 -0
- package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/RECORD +67 -66
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-b12167.json +0 -26
- /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"""Keep the prompt prefix agents send most in a llama-server, across restarts. Python 3.8+, stdlib.
|
|
2
|
+
|
|
3
|
+
Copied beside an agent-posture llama.cpp deployment, with auth_proxy.py, and run by its service:
|
|
4
|
+
``python3 slot_cache.py CMD [ARG...]``, where CMD is the llama-server launch with ``--host``,
|
|
5
|
+
``--port``, ``--api-key-file`` and ``--slot-save-path SLOT_DIR``. This wrapper serves that host
|
|
6
|
+
and port itself (auth_proxy's forwarding), starts CMD on a free loopback port instead, passes
|
|
7
|
+
SIGTERM and SIGINT on and exits with its code. Every request reaches llama-server unchanged,
|
|
8
|
+
the caller's key included: the server checks it as before. Should this process be killed
|
|
9
|
+
outright, a small sh beside the server ends it too (end_with_me).
|
|
10
|
+
|
|
11
|
+
The prefix comes from the traffic, never from a prompt written into a plan: a chat request with
|
|
12
|
+
tools is read for its leading system (or developer) messages and its tools. Each such request
|
|
13
|
+
that carries the server's key counts for its prefix (a caller llama-server refuses has no say),
|
|
14
|
+
older ones fade (half weight after HALF_LIFE requests), and the prefix
|
|
15
|
+
counted most, once seen twice and clearly ahead of the one kept, is written to
|
|
16
|
+
``SLOT_DIR/prefix.json`` as a chat request (messages and tools, the form PolyStrata's
|
|
17
|
+
``"warm_start"`` file takes as well). An agent's own room, which every turn of its chats repeats,
|
|
18
|
+
wins; a changed system prompt takes over as the old one fades.
|
|
19
|
+
|
|
20
|
+
Once the server is healthy, and again when prefix.json changes while no slot is busy, slot 0 is
|
|
21
|
+
brought to that prefix:
|
|
22
|
+
|
|
23
|
+
- the prefix is the token sequence that two renderings of the request share when two different
|
|
24
|
+
user messages are appended (/apply-template, /tokenize). It ends where the user turn begins: a
|
|
25
|
+
hybrid model's recurrent state cannot be rolled back, so the cached tokens must be an exact
|
|
26
|
+
prefix of the next request;
|
|
27
|
+
- ``SLOT_DIR/prefix-<hash>.bin`` holds slot 0 after that prefix. The hash covers CMD, the model
|
|
28
|
+
file's size and modification time, and the tokens, so another model (or another file under
|
|
29
|
+
the same path), engine, window or KV type never reads an old file;
|
|
30
|
+
- an existing file is restored; otherwise the other prefix files are removed and the prefix is
|
|
31
|
+
prefilled (/completion, n_predict 0) and saved. A pass that fails is tried again.
|
|
32
|
+
|
|
33
|
+
Files under SLOT_DIR hold prompt text and its KV state, so they are the owner's only. One line
|
|
34
|
+
per action goes to stderr (the service log); prompt text never does.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import contextlib
|
|
40
|
+
import hashlib
|
|
41
|
+
import hmac
|
|
42
|
+
import http.server
|
|
43
|
+
import json
|
|
44
|
+
import os
|
|
45
|
+
import signal
|
|
46
|
+
import subprocess
|
|
47
|
+
import sys
|
|
48
|
+
import threading
|
|
49
|
+
import time
|
|
50
|
+
import urllib.error
|
|
51
|
+
import urllib.request
|
|
52
|
+
from pathlib import Path
|
|
53
|
+
from typing import Any
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
from localmodels import auth_proxy
|
|
57
|
+
except ImportError: # run as a bare file beside the deployment's copy of auth_proxy.py
|
|
58
|
+
import auth_proxy # type: ignore[import-not-found,no-redef]
|
|
59
|
+
|
|
60
|
+
PREFIX_FILE = "prefix.json"
|
|
61
|
+
TALLY_FILE = "prefix-tally.json"
|
|
62
|
+
CHECK_EVERY_S = 30.0
|
|
63
|
+
HEALTH_WAIT_S = 1800.0 # a large model loading from a cold disk
|
|
64
|
+
REQUEST_TIMEOUT_S = 900.0 # prefilling a long prefix on a small Mac
|
|
65
|
+
HALF_LIFE = 500 # requests after which an unrepeated prefix counts half
|
|
66
|
+
SEEN_TWICE = 1.5 # two counts, however far apart within a half-life
|
|
67
|
+
LEAD = 1.5 # a new prefix replaces the kept one once it counts this much more
|
|
68
|
+
KEPT_PREFIXES = 16 # the counts kept when the table of prefixes is thinned
|
|
69
|
+
RETRIES = 3 # passes that may fail on one prefix.json before it is left until it changes
|
|
70
|
+
# Two user messages in different scripts: their renderings part before the first user token.
|
|
71
|
+
PLACEHOLDERS = ("A", "\u4e00")
|
|
72
|
+
# sh run beside llama-server: its stdin is a pipe only this process can write to, so the read
|
|
73
|
+
# returns when this process is gone, however it went. "$0" is llama-server's pid.
|
|
74
|
+
GUARD = (
|
|
75
|
+
'read _; kill -TERM "$0" 2>/dev/null; n=0; '
|
|
76
|
+
'while kill -0 "$0" 2>/dev/null && [ "$n" -lt 10 ]; do sleep 1; n=$((n+1)); done; '
|
|
77
|
+
'kill -KILL "$0" 2>/dev/null'
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def log(message: str) -> None:
|
|
82
|
+
print(f"slot_cache: {message}", file=sys.stderr, flush=True)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def flag(cmd: list[str], name: str) -> str | None:
|
|
86
|
+
for i, arg in enumerate(cmd[:-1]):
|
|
87
|
+
if arg == name:
|
|
88
|
+
return cmd[i + 1]
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def with_flag(cmd: list[str], name: str, value: str) -> list[str]:
|
|
93
|
+
out = list(cmd)
|
|
94
|
+
for i, arg in enumerate(out[:-1]):
|
|
95
|
+
if arg == name:
|
|
96
|
+
out[i + 1] = value
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def prefix_of(body: object) -> dict[str, Any] | None:
|
|
101
|
+
"""A chat request's leading system or developer messages and its tools, or None."""
|
|
102
|
+
if not isinstance(body, dict) or not body.get("tools"):
|
|
103
|
+
return None
|
|
104
|
+
messages = body.get("messages")
|
|
105
|
+
if not isinstance(messages, list):
|
|
106
|
+
return None
|
|
107
|
+
head = []
|
|
108
|
+
for message in messages:
|
|
109
|
+
if not isinstance(message, dict) or message.get("role") not in ("system", "developer"):
|
|
110
|
+
break
|
|
111
|
+
head.append(message)
|
|
112
|
+
return {"messages": head, "tools": body["tools"]} if head else None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class Tally:
|
|
116
|
+
"""Which prefix the traffic repeats most lately, and when that is a new one to keep."""
|
|
117
|
+
|
|
118
|
+
def __init__(self, slot_dir: Path) -> None:
|
|
119
|
+
self.path = slot_dir / TALLY_FILE
|
|
120
|
+
self.lock = threading.Lock()
|
|
121
|
+
self.seq = 0
|
|
122
|
+
self.scores: dict[str, tuple[float, int]] = {} # digest -> (score, seq of its last count)
|
|
123
|
+
self.kept: str | None = None
|
|
124
|
+
self.dirty = False
|
|
125
|
+
try:
|
|
126
|
+
saved = json.loads(self.path.read_text(encoding="utf-8"))
|
|
127
|
+
self.seq = int(saved["seq"])
|
|
128
|
+
self.scores = {k: (float(v[0]), int(v[1])) for k, v in saved["scores"].items()}
|
|
129
|
+
self.kept = saved.get("kept")
|
|
130
|
+
except (OSError, ValueError, KeyError, TypeError, IndexError):
|
|
131
|
+
pass
|
|
132
|
+
|
|
133
|
+
def score(self, digest: str) -> float:
|
|
134
|
+
value, seq = self.scores.get(digest, (0.0, self.seq))
|
|
135
|
+
return float(value * 0.5 ** ((self.seq - seq) / HALF_LIFE))
|
|
136
|
+
|
|
137
|
+
def count(self, prefix: dict[str, Any]) -> bytes | None:
|
|
138
|
+
"""Count one request's prefix; the prefix.json body when it becomes the one to keep."""
|
|
139
|
+
# The client's own key order: the template renders the tools as written, so a reordered
|
|
140
|
+
# copy would part from the client's requests inside the tool list.
|
|
141
|
+
body = json.dumps(prefix, ensure_ascii=False).encode()
|
|
142
|
+
digest = hashlib.sha256(body).hexdigest()[:16]
|
|
143
|
+
with self.lock:
|
|
144
|
+
self.scores[digest] = (self.score(digest) + 1.0, self.seq)
|
|
145
|
+
self.seq += 1
|
|
146
|
+
if len(self.scores) > 4 * KEPT_PREFIXES:
|
|
147
|
+
for old in sorted(self.scores, key=self.score)[: len(self.scores) - KEPT_PREFIXES]:
|
|
148
|
+
del self.scores[old]
|
|
149
|
+
self.dirty = True
|
|
150
|
+
mine = self.score(digest)
|
|
151
|
+
if digest == self.kept or mine < SEEN_TWICE:
|
|
152
|
+
return None
|
|
153
|
+
if self.kept is not None and mine < LEAD * self.score(self.kept):
|
|
154
|
+
return None
|
|
155
|
+
self.kept = digest
|
|
156
|
+
return body
|
|
157
|
+
|
|
158
|
+
def unkeep(self) -> None:
|
|
159
|
+
"""prefix.json could not be written: the next request with the leading prefix writes it."""
|
|
160
|
+
with self.lock:
|
|
161
|
+
self.kept = None
|
|
162
|
+
self.dirty = True
|
|
163
|
+
|
|
164
|
+
def save(self) -> None:
|
|
165
|
+
with self.lock:
|
|
166
|
+
if not self.dirty:
|
|
167
|
+
return
|
|
168
|
+
# A copy: requests go on counting while this one is written out.
|
|
169
|
+
saved = {"seq": self.seq, "scores": dict(self.scores), "kept": self.kept}
|
|
170
|
+
self.dirty = False
|
|
171
|
+
try:
|
|
172
|
+
write(self.path, json.dumps(saved).encode())
|
|
173
|
+
except OSError:
|
|
174
|
+
with self.lock:
|
|
175
|
+
self.dirty = True
|
|
176
|
+
raise
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def write(path: Path, data: bytes) -> None:
|
|
180
|
+
tmp = path.with_name(f"{path.name}.{threading.get_ident()}.tmp")
|
|
181
|
+
try:
|
|
182
|
+
tmp.write_bytes(data)
|
|
183
|
+
os.replace(tmp, path)
|
|
184
|
+
except OSError:
|
|
185
|
+
with contextlib.suppress(OSError):
|
|
186
|
+
tmp.unlink() # a full disk leaves no half-written file behind
|
|
187
|
+
raise
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Server:
|
|
191
|
+
def __init__(self, port: int, key: str) -> None:
|
|
192
|
+
self.base = f"http://127.0.0.1:{port}"
|
|
193
|
+
self.key = key
|
|
194
|
+
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
195
|
+
|
|
196
|
+
def call(self, path: str, body: object = None) -> dict[str, Any]:
|
|
197
|
+
data = None if body is None else json.dumps(body).encode()
|
|
198
|
+
req = urllib.request.Request(
|
|
199
|
+
self.base + path,
|
|
200
|
+
data=data,
|
|
201
|
+
headers={"Authorization": "Bearer " + self.key, "Content-Type": "application/json"},
|
|
202
|
+
)
|
|
203
|
+
with self.opener.open(req, timeout=REQUEST_TIMEOUT_S) as r:
|
|
204
|
+
value = json.loads(r.read() or b"{}")
|
|
205
|
+
return value if isinstance(value, dict) else {"value": value}
|
|
206
|
+
|
|
207
|
+
def healthy(self) -> bool:
|
|
208
|
+
try:
|
|
209
|
+
return self.call("/health").get("status") == "ok"
|
|
210
|
+
except (OSError, ValueError):
|
|
211
|
+
return False
|
|
212
|
+
|
|
213
|
+
def idle(self) -> bool:
|
|
214
|
+
with self.opener.open(
|
|
215
|
+
urllib.request.Request(
|
|
216
|
+
self.base + "/slots", headers={"Authorization": "Bearer " + self.key}
|
|
217
|
+
),
|
|
218
|
+
timeout=REQUEST_TIMEOUT_S,
|
|
219
|
+
) as r:
|
|
220
|
+
slots: list[dict[str, Any]] = json.loads(r.read() or b"[]")
|
|
221
|
+
return not any(s.get("is_processing") for s in slots)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def prefix_tokens(server: Server, request: dict[str, Any]) -> list[int]:
|
|
225
|
+
rendered: list[list[int]] = []
|
|
226
|
+
for text in PLACEHOLDERS:
|
|
227
|
+
body = dict(request, messages=[*request["messages"], {"role": "user", "content": text}])
|
|
228
|
+
prompt = server.call("/apply-template", body)["prompt"]
|
|
229
|
+
rendered.append(
|
|
230
|
+
server.call(
|
|
231
|
+
"/tokenize", {"content": prompt, "add_special": True, "parse_special": True}
|
|
232
|
+
)["tokens"]
|
|
233
|
+
)
|
|
234
|
+
first, second = rendered
|
|
235
|
+
n = 0
|
|
236
|
+
while n < min(len(first), len(second)) and first[n] == second[n]:
|
|
237
|
+
n += 1
|
|
238
|
+
return first[:n]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def model_identity(cmd: list[str]) -> list[int]:
|
|
242
|
+
"""Size and modification time of the model file CMD loads: a file replaced under the same
|
|
243
|
+
path must not be given the state saved from the old one."""
|
|
244
|
+
path = flag(cmd, "-m") or flag(cmd, "--model")
|
|
245
|
+
try:
|
|
246
|
+
info = os.stat(path) if path else None
|
|
247
|
+
except OSError:
|
|
248
|
+
info = None
|
|
249
|
+
return [info.st_size, info.st_mtime_ns] if info is not None else []
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def sync(server: Server, slot_dir: Path, cmd: list[str], raw: bytes) -> None:
|
|
253
|
+
"""Bring slot 0 to the prefix ``raw`` describes: restore its file, or prefill and save it."""
|
|
254
|
+
request = json.loads(raw)
|
|
255
|
+
if not isinstance(request, dict) or not request.get("messages"):
|
|
256
|
+
raise ValueError(f"{PREFIX_FILE} has no messages")
|
|
257
|
+
tokens = prefix_tokens(server, request)
|
|
258
|
+
if not tokens:
|
|
259
|
+
raise ValueError("the request and a user turn share no tokens")
|
|
260
|
+
identity = json.dumps([cmd, model_identity(cmd), tokens]).encode()
|
|
261
|
+
name = f"prefix-{hashlib.sha256(identity).hexdigest()[:16]}.bin"
|
|
262
|
+
started = time.monotonic()
|
|
263
|
+
if (slot_dir / name).exists():
|
|
264
|
+
try:
|
|
265
|
+
restored = server.call("/slots/0?action=restore", {"filename": name})
|
|
266
|
+
except urllib.error.HTTPError as error: # a truncated or foreign file
|
|
267
|
+
restored = {"n_restored": f"none (HTTP {error.code})"}
|
|
268
|
+
if restored.get("n_restored") == len(tokens):
|
|
269
|
+
ms = round((time.monotonic() - started) * 1000)
|
|
270
|
+
log(f"restored {len(tokens)} prefix tokens from {name} in {ms} ms")
|
|
271
|
+
return
|
|
272
|
+
log(f"{name} restored {restored.get('n_restored')} of {len(tokens)} tokens; prefilling")
|
|
273
|
+
# No saved state is this prefix's now. Removed first, they leave their room to the new one.
|
|
274
|
+
for old in slot_dir.glob("prefix-*.bin"):
|
|
275
|
+
old.unlink()
|
|
276
|
+
server.call(
|
|
277
|
+
"/completion", {"prompt": tokens, "n_predict": 0, "cache_prompt": True, "id_slot": 0}
|
|
278
|
+
)
|
|
279
|
+
try:
|
|
280
|
+
saved = server.call("/slots/0?action=save", {"filename": name})
|
|
281
|
+
except (OSError, ValueError):
|
|
282
|
+
with contextlib.suppress(OSError):
|
|
283
|
+
(slot_dir / name).unlink() # a file cut short would only fail the next restore
|
|
284
|
+
raise
|
|
285
|
+
ms = round((time.monotonic() - started) * 1000)
|
|
286
|
+
log(
|
|
287
|
+
f"prefilled {len(tokens)} prefix tokens and saved {saved.get('n_written')} bytes "
|
|
288
|
+
f"to {name} in {ms} ms"
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def attempt(server: Server, slot_dir: Path, cmd: list[str], raw: bytes, first: bool) -> str:
|
|
293
|
+
"""One try at bringing slot 0 to ``raw``: "" when it holds the prefix now, "busy" while a
|
|
294
|
+
request runs (right after start none can, so ``first`` does not ask), else what failed."""
|
|
295
|
+
try:
|
|
296
|
+
if not (first or server.idle()):
|
|
297
|
+
return "busy"
|
|
298
|
+
sync(server, slot_dir, cmd, raw)
|
|
299
|
+
return ""
|
|
300
|
+
except urllib.error.HTTPError as error:
|
|
301
|
+
return f"HTTP {error.code}"
|
|
302
|
+
except Exception as error: # noqa: BLE001 - a failed pass must not end the loop
|
|
303
|
+
return type(error).__name__
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def keep_warm(
|
|
307
|
+
server: Server, slot_dir: Path, cmd: list[str], tally: Tally, child: subprocess.Popen[bytes]
|
|
308
|
+
) -> None:
|
|
309
|
+
deadline = time.monotonic() + HEALTH_WAIT_S
|
|
310
|
+
while not server.healthy():
|
|
311
|
+
if child.poll() is not None or time.monotonic() > deadline:
|
|
312
|
+
return
|
|
313
|
+
time.sleep(0.5)
|
|
314
|
+
seen: bytes | None = None
|
|
315
|
+
failed = 0
|
|
316
|
+
first = True
|
|
317
|
+
while child.poll() is None:
|
|
318
|
+
try:
|
|
319
|
+
tally.save()
|
|
320
|
+
except OSError as error:
|
|
321
|
+
log(f"prefix counts not saved: {type(error).__name__}")
|
|
322
|
+
try:
|
|
323
|
+
raw: bytes | None = (slot_dir / PREFIX_FILE).read_bytes()
|
|
324
|
+
except FileNotFoundError:
|
|
325
|
+
raw = None
|
|
326
|
+
except OSError as error:
|
|
327
|
+
log(f"cannot read {PREFIX_FILE}: {type(error).__name__}")
|
|
328
|
+
raw = seen
|
|
329
|
+
if raw is None:
|
|
330
|
+
seen, failed = None, 0
|
|
331
|
+
elif raw != seen:
|
|
332
|
+
problem = attempt(server, slot_dir, cmd, raw, first)
|
|
333
|
+
if not problem:
|
|
334
|
+
seen, failed = raw, 0
|
|
335
|
+
elif problem != "busy":
|
|
336
|
+
failed += 1
|
|
337
|
+
if failed < RETRIES:
|
|
338
|
+
log(f"prefix not applied ({problem}); trying again")
|
|
339
|
+
else:
|
|
340
|
+
log(f"prefix not applied ({problem}); left until {PREFIX_FILE} changes")
|
|
341
|
+
seen, failed = raw, 0
|
|
342
|
+
first = False
|
|
343
|
+
if child.poll() is None:
|
|
344
|
+
time.sleep(CHECK_EVERY_S)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def count(body: bytes, slot_dir: Path, tally: Tally) -> None:
|
|
348
|
+
"""Count a chat request's prefix; write prefix.json when that makes it the one to keep."""
|
|
349
|
+
try:
|
|
350
|
+
prefix = prefix_of(json.loads(body))
|
|
351
|
+
except ValueError as error:
|
|
352
|
+
log(f"prefix not counted: {type(error).__name__}")
|
|
353
|
+
return
|
|
354
|
+
keep = tally.count(prefix) if prefix is not None else None
|
|
355
|
+
if keep is None:
|
|
356
|
+
return
|
|
357
|
+
try:
|
|
358
|
+
write(slot_dir / PREFIX_FILE, keep)
|
|
359
|
+
except OSError as error:
|
|
360
|
+
tally.unkeep()
|
|
361
|
+
log(f"{PREFIX_FILE} not written: {type(error).__name__}")
|
|
362
|
+
return
|
|
363
|
+
log("a new prompt prefix leads the traffic; prefix.json rewritten")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def handler(
|
|
367
|
+
upstream: int, slot_dir: Path, tally: Tally, key: str
|
|
368
|
+
) -> type[http.server.BaseHTTPRequestHandler]:
|
|
369
|
+
"""auth_proxy's forwarding, with no key check of its own: llama-server checks the caller's
|
|
370
|
+
key as before (and leaves /health open). A chat request's body is counted on the way when it
|
|
371
|
+
carries that key: a caller the server will refuse has no say in which prefix is kept."""
|
|
372
|
+
forward: Any = auth_proxy.handler(None, upstream, pass_auth=True)
|
|
373
|
+
bearer = ("Bearer " + key).encode()
|
|
374
|
+
|
|
375
|
+
class Counting(forward): # type: ignore[misc]
|
|
376
|
+
def _read_body(self) -> bytes | None:
|
|
377
|
+
body: bytes | None = super()._read_body()
|
|
378
|
+
chat = self.command == "POST" and self.path.split("?")[0].endswith("/completions")
|
|
379
|
+
given = (self.headers.get("Authorization") or "").encode()
|
|
380
|
+
if body and chat and (not key or hmac.compare_digest(given, bearer)):
|
|
381
|
+
count(body, slot_dir, tally)
|
|
382
|
+
return body
|
|
383
|
+
|
|
384
|
+
return Counting
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def end_with_me(server_pid: int) -> subprocess.Popen[bytes] | None:
|
|
388
|
+
"""llama-server must not outlive this process. Killed outright (SIGKILL, a crash), it would
|
|
389
|
+
leave the server holding the model with no recorded process, and the next load would start a
|
|
390
|
+
second one beside it. The guard ends the server when this process's pipe closes; a normal
|
|
391
|
+
exit ends the guard first."""
|
|
392
|
+
if os.name != "posix":
|
|
393
|
+
return None
|
|
394
|
+
read_end, _held_open = os.pipe() # never written, never closed: it closes with this process
|
|
395
|
+
try:
|
|
396
|
+
return subprocess.Popen(
|
|
397
|
+
["/bin/sh", "-c", GUARD, str(server_pid)],
|
|
398
|
+
stdin=read_end,
|
|
399
|
+
stdout=subprocess.DEVNULL,
|
|
400
|
+
stderr=subprocess.DEVNULL,
|
|
401
|
+
)
|
|
402
|
+
finally:
|
|
403
|
+
os.close(read_end)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def main(argv: list[str]) -> int:
|
|
407
|
+
cmd = argv
|
|
408
|
+
host, port = flag(cmd, "--host") or "127.0.0.1", flag(cmd, "--port")
|
|
409
|
+
key_file, slots = flag(cmd, "--api-key-file"), flag(cmd, "--slot-save-path")
|
|
410
|
+
if not cmd or port is None or key_file is None or slots is None:
|
|
411
|
+
print(
|
|
412
|
+
"usage: slot_cache.py LLAMA_SERVER [ARG...] (with --port, --api-key-file and "
|
|
413
|
+
"--slot-save-path)",
|
|
414
|
+
file=sys.stderr,
|
|
415
|
+
)
|
|
416
|
+
return 2
|
|
417
|
+
os.umask(0o077) # the prefix, the tally and the saved slots hold prompt text
|
|
418
|
+
with open(key_file, encoding="utf-8") as f:
|
|
419
|
+
key = f.read().strip()
|
|
420
|
+
slot_dir = Path(slots)
|
|
421
|
+
slot_dir.mkdir(parents=True, exist_ok=True)
|
|
422
|
+
upstream = auth_proxy.free_port()
|
|
423
|
+
inner = with_flag(with_flag(cmd, "--host", "127.0.0.1"), "--port", str(upstream))
|
|
424
|
+
tally = Tally(slot_dir)
|
|
425
|
+
if not (slot_dir / PREFIX_FILE).exists():
|
|
426
|
+
tally.kept = None # write the leading prefix again
|
|
427
|
+
proxy = http.server.ThreadingHTTPServer(
|
|
428
|
+
(host, int(port)), handler(upstream, slot_dir, tally, key)
|
|
429
|
+
)
|
|
430
|
+
proxy.daemon_threads = True
|
|
431
|
+
child = subprocess.Popen(inner)
|
|
432
|
+
guard = end_with_me(child.pid)
|
|
433
|
+
|
|
434
|
+
def stop(signum: int, _frame: object) -> None:
|
|
435
|
+
if child.poll() is None:
|
|
436
|
+
child.send_signal(signum)
|
|
437
|
+
|
|
438
|
+
signal.signal(signal.SIGTERM, stop)
|
|
439
|
+
signal.signal(signal.SIGINT, stop)
|
|
440
|
+
|
|
441
|
+
def watch() -> None:
|
|
442
|
+
child.wait()
|
|
443
|
+
proxy.shutdown()
|
|
444
|
+
|
|
445
|
+
threading.Thread(target=watch, daemon=True).start()
|
|
446
|
+
threading.Thread(
|
|
447
|
+
target=keep_warm,
|
|
448
|
+
args=(Server(upstream, key), slot_dir, cmd, tally, child),
|
|
449
|
+
daemon=True,
|
|
450
|
+
).start()
|
|
451
|
+
try:
|
|
452
|
+
proxy.serve_forever()
|
|
453
|
+
finally:
|
|
454
|
+
proxy.server_close()
|
|
455
|
+
if child.poll() is None:
|
|
456
|
+
child.terminate()
|
|
457
|
+
code = child.wait()
|
|
458
|
+
if guard is not None:
|
|
459
|
+
guard.kill()
|
|
460
|
+
guard.wait()
|
|
461
|
+
with contextlib.suppress(OSError):
|
|
462
|
+
tally.save()
|
|
463
|
+
return code if code >= 0 else 128 - code
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
if __name__ == "__main__":
|
|
467
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -8,7 +8,7 @@ import os
|
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
from typing import TypedDict, cast
|
|
10
10
|
|
|
11
|
-
from localmodels import harness, hosts, stack, stack_run
|
|
11
|
+
from localmodels import harness, hosts, runtime_discovery, stack, stack_run
|
|
12
12
|
from localmodels import stack_lifecycle as lifecycle
|
|
13
13
|
from localmodels.setup_text import Lang, text
|
|
14
14
|
from localmodels.stack_plan import StackPlan, deployments
|
|
@@ -67,9 +67,13 @@ def _acceptance_ready(plan: StackPlan) -> bool:
|
|
|
67
67
|
|
|
68
68
|
def _adopted(plan: StackPlan) -> set[str]:
|
|
69
69
|
"""The plan's LLM components the library adopted (``library_convert``): from then on the
|
|
70
|
-
library loads, unloads and
|
|
71
|
-
are no longer the stack's to check.
|
|
70
|
+
library loads, unloads, wires and may remove them, so their deployments, gateway route and
|
|
71
|
+
pi selection are no longer the stack's to check. The conversion marker names them, and
|
|
72
|
+
stays when ``library remove`` deletes the model's record; a converted record (an earlier
|
|
73
|
+
one may lack ``stack_provider``: the main LLM's) names them too. Read only; it never
|
|
74
|
+
converts."""
|
|
72
75
|
from localmodels import library_convert, library_state, stack_verify
|
|
76
|
+
from localmodels.library_model import library_id
|
|
73
77
|
|
|
74
78
|
try:
|
|
75
79
|
marker = json.loads((library_state.root() / library_convert.MARKER).read_text("utf-8"))
|
|
@@ -77,11 +81,20 @@ def _adopted(plan: StackPlan) -> set[str]:
|
|
|
77
81
|
return set()
|
|
78
82
|
if not isinstance(marker, dict) or marker.get("plan_id") != plan["plan_id"]:
|
|
79
83
|
return set()
|
|
80
|
-
|
|
84
|
+
ids = set(marker.get("adopted") or [])
|
|
85
|
+
providers = {
|
|
86
|
+
r.get("stack_provider") or harness.LLM_PROVIDER
|
|
87
|
+
for r in library_state.records()
|
|
88
|
+
if r.get("converted")
|
|
89
|
+
}
|
|
81
90
|
return {
|
|
82
91
|
component
|
|
83
|
-
for component,
|
|
84
|
-
if
|
|
92
|
+
for component, part in stack_verify.parts(plan)
|
|
93
|
+
if component in library_convert.STACK_LLMS
|
|
94
|
+
and (
|
|
95
|
+
library_id(part["model"]["id"], part["model"]["quant"]) in ids
|
|
96
|
+
or library_convert.STACK_LLMS[component] in providers
|
|
97
|
+
)
|
|
85
98
|
}
|
|
86
99
|
|
|
87
100
|
|
|
@@ -237,19 +250,75 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
|
|
|
237
250
|
}
|
|
238
251
|
|
|
239
252
|
|
|
240
|
-
def
|
|
241
|
-
"""The
|
|
242
|
-
|
|
243
|
-
|
|
253
|
+
def _stack_installed(plan: StackPlan, owned: hosts.Owned) -> bool:
|
|
254
|
+
"""The Node.js and pi the plan installed are still in the manifest: ``stack remove``
|
|
255
|
+
deletes them and drops them from it. A tool the plan reused is no anchor."""
|
|
256
|
+
paths = [Path(t["path"]) for t in owned["tools"]]
|
|
257
|
+
for tool in plan["harness"]["tools"]:
|
|
258
|
+
if tool["action"] != "install" or tool["tool"] not in ("node", "pi"):
|
|
259
|
+
continue
|
|
260
|
+
wanted = Path(os.path.expanduser(tool["path"]))
|
|
261
|
+
if not any(wanted == path or path in wanted.parents for path in paths):
|
|
262
|
+
return False
|
|
263
|
+
return True
|
|
244
264
|
|
|
265
|
+
|
|
266
|
+
def _library_binding(
|
|
267
|
+
plan: StackPlan, owned: hosts.Owned, adopted: set[str], lang: Lang = "zh"
|
|
268
|
+
) -> PiBinding | Reason:
|
|
269
|
+
"""The stack's pi once the library adopted an LLM: the library unwires that LLM's route and
|
|
270
|
+
unpoints pi when the last stack LLM leaves, so pi's selection is not checked. The gateway
|
|
271
|
+
still is while anything the library did not adopt (the decision model, foundation
|
|
272
|
+
services, the other LLM) routes through it."""
|
|
273
|
+
from localmodels import bifrost_pi, gateway_bifrost, stack_verify
|
|
274
|
+
|
|
275
|
+
if not _stack_installed(plan, owned):
|
|
276
|
+
return _reason("deployment-unavailable", lang)
|
|
277
|
+
gateway = plan["harness"]["gateway"]
|
|
245
278
|
executable = Path(harness.tool_path(plan["harness"], "pi"))
|
|
246
|
-
|
|
279
|
+
environment = harness.gateway_environment(plan["harness"])
|
|
280
|
+
# The profile the stack's own binding reads: a Magpie plan on a shared daemon has none
|
|
281
|
+
# (KeyError, unavailable), never the user's ~/.pi/agent.
|
|
282
|
+
profile = (
|
|
283
|
+
bifrost_pi.pi_profile(environment)
|
|
284
|
+
if harness.gateway_kind(gateway) == "bifrost"
|
|
285
|
+
else Path(environment["PI_CODING_AGENT_DIR"]).expanduser()
|
|
286
|
+
)
|
|
247
287
|
if not executable.is_absolute() or not profile.is_absolute():
|
|
248
288
|
raise ValueError("Pi paths must be absolute")
|
|
289
|
+
fingerprint = _profile_fingerprint(executable, profile)
|
|
290
|
+
if any(component not in adopted for component, _ in stack_verify.parts(plan)):
|
|
291
|
+
if harness.gateway_kind(gateway) == "bifrost":
|
|
292
|
+
record = owned["gateway"].get("bifrost")
|
|
293
|
+
if not record or record["addr"] != gateway["addr"]:
|
|
294
|
+
return _reason("gateway-ownership", lang)
|
|
295
|
+
if not gateway_bifrost.owned_listener(record) or not gateway_bifrost.healthy(
|
|
296
|
+
gateway["addr"]
|
|
297
|
+
):
|
|
298
|
+
return _reason("gateway-unavailable", lang)
|
|
299
|
+
else:
|
|
300
|
+
if owned["gateway"]["group"] != gateway["group"]:
|
|
301
|
+
return _reason("gateway-ownership", lang)
|
|
302
|
+
magpie = harness.tool_path(plan["harness"], "magpie")
|
|
303
|
+
env = {
|
|
304
|
+
**harness.checked_gateway_environment(plan["harness"]),
|
|
305
|
+
"PATH": os.pathsep.join([str(Path(magpie).parent), os.environ.get("PATH", "")]),
|
|
306
|
+
"MAGPIE_ADDR": gateway["addr"],
|
|
307
|
+
}
|
|
308
|
+
state = harness.inspect(
|
|
309
|
+
env=env,
|
|
310
|
+
tools_dir=plan["harness"]["tools_dir"],
|
|
311
|
+
approved=plan["harness"],
|
|
312
|
+
private_clients=True,
|
|
313
|
+
)
|
|
314
|
+
if not state["gateway_up"] or state.get("gateway_other_user"):
|
|
315
|
+
return _reason("gateway-unavailable", lang)
|
|
316
|
+
if _profile_fingerprint(executable, profile) != fingerprint:
|
|
317
|
+
return _reason("pi-config-changed", lang)
|
|
249
318
|
return {
|
|
250
319
|
"executable": str(executable),
|
|
251
320
|
"environment": {"PI_CODING_AGENT_DIR": str(profile)},
|
|
252
|
-
"configFingerprint":
|
|
321
|
+
"configFingerprint": fingerprint,
|
|
253
322
|
}
|
|
254
323
|
|
|
255
324
|
|
|
@@ -280,9 +349,17 @@ def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
|
|
|
280
349
|
if not _deployments_ready(plan, owned, adopted):
|
|
281
350
|
report["reasons"] = [_reason("deployment-unavailable", lang)]
|
|
282
351
|
return report
|
|
283
|
-
binding =
|
|
352
|
+
binding = (
|
|
353
|
+
_library_binding(plan, owned, adopted, lang)
|
|
354
|
+
if adopted
|
|
355
|
+
else _pi_binding(plan, owned, lang)
|
|
356
|
+
)
|
|
284
357
|
if "code" in binding:
|
|
285
358
|
report["reasons"] = [cast(Reason, binding)]
|
|
359
|
+
elif not runtime_discovery.pi_loads_extensions([cast(PiBinding, binding)["executable"]]):
|
|
360
|
+
# localmodels before 0.1.0.dev39 installed pi without jiti; Linger starts pi with an
|
|
361
|
+
# extension on every run. stack apply replaces an owned one.
|
|
362
|
+
report["reasons"] = [_reason("pi-extensions-unavailable", lang)]
|
|
286
363
|
else:
|
|
287
364
|
report["ready"] = True
|
|
288
365
|
report["pi"] = binding
|
|
@@ -18,9 +18,9 @@ from localmodels.probe import HostFacts
|
|
|
18
18
|
from localmodels.stack_plan import CapacityFit, Hardware, StackOptions
|
|
19
19
|
|
|
20
20
|
WDDM_NOTE = (
|
|
21
|
-
"Windows WDDM GPU contexts
|
|
22
|
-
"
|
|
23
|
-
"
|
|
21
|
+
"Windows WDDM GPU contexts of the desktop, games and other apps do not block a plan; only "
|
|
22
|
+
"an inference server's needs --share-gpu, and per-process VRAM may be unavailable. Plans "
|
|
23
|
+
"use the current free VRAM."
|
|
24
24
|
)
|
|
25
25
|
|
|
26
26
|
|
|
@@ -42,6 +42,7 @@ def warm_speed(path: Path, plan: StackPlan) -> float | None:
|
|
|
42
42
|
not isinstance(llm, dict)
|
|
43
43
|
or llm.get("name") != plan["llm"]["name"]
|
|
44
44
|
or llm.get("ok") is not True
|
|
45
|
+
or llm.get("decode_basis") != stack_warm.DECODE_TIMING
|
|
45
46
|
):
|
|
46
47
|
return None
|
|
47
48
|
speed = llm.get("decode_tok_s")
|
|
@@ -415,7 +415,7 @@ def _llm_warnings(
|
|
|
415
415
|
llm: Plan, llm_id: str, running: bool, facts: HostFacts, options: StackOptions
|
|
416
416
|
) -> list[str]:
|
|
417
417
|
"""What a catalog llama.cpp LLM's plan says about itself: its own warnings, an ignored
|
|
418
|
-
--conversation-cache, and a running one kept as is or a new one's GPU conflicts
|
|
418
|
+
--conversation-cache, and a running one kept as is or a new one's GPU conflicts."""
|
|
419
419
|
warnings = [f"LLM: {w}" for w in llm["warnings"]]
|
|
420
420
|
if (
|
|
421
421
|
llm_id == llm_rank.WINDOWS_FALLBACK_ID
|
|
@@ -439,7 +439,6 @@ def _llm_warnings(
|
|
|
439
439
|
)
|
|
440
440
|
else:
|
|
441
441
|
warnings += _gpu_conflicts(llm, facts, options.get("share_gpu", False))
|
|
442
|
-
warnings += hardware.slow_warning(facts, llm)
|
|
443
442
|
return warnings
|
|
444
443
|
|
|
445
444
|
|
|
@@ -741,7 +740,7 @@ def assemble(
|
|
|
741
740
|
"harness": tools_plan,
|
|
742
741
|
"budget": budget,
|
|
743
742
|
"warnings": warnings,
|
|
744
|
-
"hardware": hardware.snapshot(facts, options),
|
|
743
|
+
"hardware": hardware.snapshot(facts, options, llm),
|
|
745
744
|
"plan_id": "",
|
|
746
745
|
}
|
|
747
746
|
if fast is not None:
|