@simplexai/localmodels-linux-x64 0.1.0-dev.38 → 0.1.0-dev.40
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 +81 -73
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +4 -0
- package/modules/localmodels/auth_proxy.py +74 -16
- package/modules/localmodels/bifrost_config.py +19 -0
- package/modules/localmodels/budget.py +27 -18
- package/modules/localmodels/catalog.json +18 -6
- package/modules/localmodels/chat_template.py +35 -0
- package/modules/localmodels/cli_parser.py +26 -3
- package/modules/localmodels/deploy.py +44 -10
- package/modules/localmodels/deploy_steps.py +6 -3
- package/modules/localmodels/download-mirrors.json +52 -4
- package/modules/localmodels/engines-b11583.json +20 -4
- package/modules/localmodels/engines-b12167.json +5 -1
- package/modules/localmodels/engines-strata-0.1.47.json +5 -1
- package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
- package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
- package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
- package/modules/localmodels/engines-whisper-b5454.json +5 -1
- package/modules/localmodels/engines.json +55 -11
- package/modules/localmodels/frontend.py +5 -2
- 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/guard.py +15 -6
- package/modules/localmodels/harness.py +104 -37
- package/modules/localmodels/harness_gateway.py +9 -3
- package/modules/localmodels/harness_probe.py +5 -1
- package/modules/localmodels/hf_repo.py +15 -8
- package/modules/localmodels/library_gateway.py +28 -15
- package/modules/localmodels/library_jobs.py +7 -1
- package/modules/localmodels/library_serve.py +5 -0
- package/modules/localmodels/metal.py +29 -12
- package/modules/localmodels/metal_probe.py +16 -6
- package/modules/localmodels/npm_signatures.py +131 -0
- package/modules/localmodels/npm_transport.py +26 -10
- package/modules/localmodels/probe.py +4 -0
- package/modules/localmodels/process_identity.py +21 -5
- package/modules/localmodels/region.py +244 -0
- package/modules/localmodels/remote_ops.py +69 -13
- package/modules/localmodels/remote_ops_download.py +217 -10
- package/modules/localmodels/remote_ops_prepare.py +61 -8
- package/modules/localmodels/remote_ops_remove.py +15 -0
- package/modules/localmodels/remote_ops_service.py +10 -0
- package/modules/localmodels/runtime-lock.json +13 -13
- package/modules/localmodels/runtime_args.py +4 -2
- package/modules/localmodels/runtime_cli.py +76 -74
- package/modules/localmodels/runtime_discovery.py +58 -0
- package/modules/localmodels/runtime_install.py +103 -7
- package/modules/localmodels/runtime_io.py +64 -7
- package/modules/localmodels/runtime_pi.py +122 -0
- package/modules/localmodels/runtime_process.py +101 -15
- package/modules/localmodels/runtime_releases.py +51 -71
- package/modules/localmodels/service_deployment.py +5 -3
- package/modules/localmodels/service_probe.py +146 -31
- package/modules/localmodels/setup_inspection.py +110 -14
- package/modules/localmodels/setup_text.py +13 -0
- package/modules/localmodels/slot_cache.py +467 -0
- package/modules/localmodels/source_byok.py +484 -0
- package/modules/localmodels/source_byok_probe.py +275 -0
- package/modules/localmodels/source_cli.py +426 -0
- package/modules/localmodels/stack_args.py +2 -1
- package/modules/localmodels/stack_binding.py +125 -5
- package/modules/localmodels/stack_capacity.py +3 -3
- package/modules/localmodels/stack_down.py +22 -7
- package/modules/localmodels/stack_events.py +62 -0
- package/modules/localmodels/stack_hardware.py +20 -17
- package/modules/localmodels/stack_lifecycle.py +12 -3
- package/modules/localmodels/stack_rollback.py +9 -4
- package/modules/localmodels/stack_up.py +27 -20
- package/modules/localmodels/stack_update.py +3 -1
- package/modules/localmodels/tools.json +1365 -14
- package/modules/localmodels/transport.py +2 -0
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/RECORD +78 -70
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.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:]))
|