@simplexai/localmodels-darwin-arm64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.35
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 +138 -97
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +4 -0
- package/modules/localmodels/app.py +7 -2
- package/modules/localmodels/approval.py +4 -4
- package/modules/localmodels/bifrost_checks.py +121 -3
- package/modules/localmodels/bifrost_provider.py +53 -0
- package/modules/localmodels/bifrost_unit.py +32 -1
- package/modules/localmodels/budget.py +5 -1
- package/modules/localmodels/catalog.json +51 -10
- package/modules/localmodels/catalog.py +30 -29
- package/modules/localmodels/catalog_add.py +1 -0
- package/modules/localmodels/cli_parser.py +10 -2
- package/modules/localmodels/component.py +7 -1
- package/modules/localmodels/decode_calibration.json +6 -0
- package/modules/localmodels/decode_calibration.py +104 -0
- package/modules/localmodels/deploy.py +44 -7
- package/modules/localmodels/deploy_steps.py +10 -1
- package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
- package/modules/localmodels/engines.json +57 -1
- package/modules/localmodels/engines.py +6 -2
- package/modules/localmodels/estimator.py +21 -7
- package/modules/localmodels/frontend.py +4 -4
- package/modules/localmodels/gateway.py +14 -4
- package/modules/localmodels/gateway_app_bifrost.py +4 -3
- package/modules/localmodels/gateway_bifrost.py +70 -57
- package/modules/localmodels/gateway_probe.py +3 -4
- package/modules/localmodels/gguf.py +7 -0
- package/modules/localmodels/harness.py +24 -25
- package/modules/localmodels/harness_gateway.py +19 -10
- package/modules/localmodels/harness_probe.py +33 -6
- package/modules/localmodels/hosts.py +73 -9
- package/modules/localmodels/install.py +36 -6
- package/modules/localmodels/library_cli.py +179 -0
- package/modules/localmodels/library_convert.py +132 -0
- package/modules/localmodels/library_gateway.py +471 -0
- package/modules/localmodels/library_jobs.py +314 -0
- package/modules/localmodels/library_model.py +246 -0
- package/modules/localmodels/library_pricing.py +347 -0
- package/modules/localmodels/library_serve.py +348 -0
- package/modules/localmodels/library_state.py +373 -0
- package/modules/localmodels/library_status.py +349 -0
- package/modules/localmodels/llm_rank.py +16 -2
- package/modules/localmodels/memcalc.py +7 -30
- package/modules/localmodels/metal.py +26 -0
- package/modules/localmodels/plan_envelope.py +4 -1
- package/modules/localmodels/preparation.py +49 -0
- package/modules/localmodels/probe.py +8 -8
- package/modules/localmodels/process_identity.py +536 -9
- package/modules/localmodels/quant_formats.py +123 -0
- package/modules/localmodels/recommend_cli.py +8 -4
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +104 -6
- package/modules/localmodels/remote_ops_download.py +17 -2
- package/modules/localmodels/remote_ops_prepare.py +406 -0
- package/modules/localmodels/remote_ops_remove.py +40 -7
- package/modules/localmodels/remote_ops_service.py +110 -8
- package/modules/localmodels/remote_ops_verify.py +15 -2
- package/modules/localmodels/runtime_auth.py +31 -1
- package/modules/localmodels/runtime_cli.py +3 -4
- package/modules/localmodels/runtime_io.py +50 -6
- package/modules/localmodels/service_autostart.py +45 -1
- package/modules/localmodels/service_control.py +13 -0
- package/modules/localmodels/service_deployment.py +12 -3
- package/modules/localmodels/service_jobs.py +33 -4
- package/modules/localmodels/service_probe.py +67 -13
- package/modules/localmodels/service_stop.py +152 -0
- package/modules/localmodels/service_worker.py +9 -1
- package/modules/localmodels/services_cli.py +50 -6
- package/modules/localmodels/setup_inspection.py +34 -25
- package/modules/localmodels/setup_text.py +118 -0
- package/modules/localmodels/sizecalc.py +625 -0
- package/modules/localmodels/sizecalc_cli.py +249 -0
- package/modules/localmodels/stack.py +69 -17
- package/modules/localmodels/stack_args.py +91 -19
- package/modules/localmodels/stack_auto.py +78 -0
- package/modules/localmodels/stack_binding.py +23 -35
- package/modules/localmodels/stack_card.py +195 -0
- package/modules/localmodels/stack_cleanup.py +379 -0
- package/modules/localmodels/stack_clients.py +4 -1
- package/modules/localmodels/stack_compose.py +150 -194
- package/modules/localmodels/stack_console.py +2 -0
- package/modules/localmodels/stack_decision.py +3 -2
- package/modules/localmodels/stack_down.py +189 -0
- package/modules/localmodels/stack_events.py +54 -0
- package/modules/localmodels/stack_hardware.py +22 -23
- package/modules/localmodels/stack_journal.py +29 -8
- package/modules/localmodels/stack_ledger.py +411 -0
- package/modules/localmodels/stack_lifecycle.py +162 -167
- package/modules/localmodels/stack_llm_ram.py +57 -5
- package/modules/localmodels/stack_memory.py +721 -0
- package/modules/localmodels/stack_picks.py +139 -0
- package/modules/localmodels/stack_plan.py +140 -22
- package/modules/localmodels/stack_ports.py +22 -0
- package/modules/localmodels/stack_preflight.py +699 -0
- package/modules/localmodels/stack_review.py +123 -5
- package/modules/localmodels/stack_rollback.py +2 -0
- package/modules/localmodels/stack_route.py +256 -0
- package/modules/localmodels/stack_run.py +11 -0
- package/modules/localmodels/stack_suite.py +102 -17
- package/modules/localmodels/stack_summary.py +65 -4
- package/modules/localmodels/stack_try.py +354 -0
- package/modules/localmodels/stack_try_client.py +194 -0
- package/modules/localmodels/stack_try_docs.py +139 -0
- package/modules/localmodels/stack_up.py +8 -1
- package/modules/localmodels/stack_update.py +29 -4
- package/modules/localmodels/stack_verify.py +3 -1
- package/modules/localmodels/stack_view.py +10 -11
- package/modules/localmodels/stack_view_apply.py +4 -2
- package/modules/localmodels/stack_view_events.py +2 -1
- package/modules/localmodels/stack_view_serve.py +3 -0
- package/modules/localmodels/stack_view_text.py +1 -1
- package/modules/localmodels/stack_view_words.py +4 -1
- package/modules/localmodels/stack_warm.py +574 -0
- package/modules/localmodels/stack_whatif.py +558 -0
- package/modules/localmodels/suite.py +48 -39
- package/modules/localmodels/tool_archive.py +40 -0
- package/modules/localmodels/tools.json +8 -0
- package/modules/localmodels/transport.py +1 -0
- package/modules/localmodels/vision.py +8 -1
- package/modules/localmodels/web/sizecalc/app.js +431 -0
- package/modules/localmodels/web/sizecalc/calc.js +269 -0
- package/modules/localmodels/web/sizecalc/page.html +362 -0
- package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
- package/modules/localmodels/web/view/i18n.js +1 -1
- package/modules/localmodels/web/view/logo-claude.svg +3 -0
- package/modules/localmodels/web/view/logo-codex.png +0 -0
- package/modules/localmodels/web/view/logo-pi.svg +6 -0
- package/modules/localmodels/web/view/view.css +4 -0
- package/modules/localmodels/web/view/view.js +15 -6
- package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/METADATA +1 -1
- package/modules/simplex_localmodels-0.1.0.dev35.dist-info/RECORD +241 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
- /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
"""``stack warm``: get this computer, and the stack installed on it, ready to run at full speed.
|
|
2
|
+
|
|
3
|
+
Host, at any time and also before an install: read the memory that is available, name what
|
|
4
|
+
holds the rest, and free what an ordinary user may free. What needs an administrator is printed
|
|
5
|
+
as a command to run; ``--sudo`` lets this tool run the one such step it knows (macOS ``purge``,
|
|
6
|
+
which flushes the file cache). Stack, when an accepted stack is installed: start nothing, send
|
|
7
|
+
each running LLM two short requests so the first real one does not pay for a cold start, and
|
|
8
|
+
report each first-request time and decode speed separately.
|
|
9
|
+
|
|
10
|
+
What each system gets (research/2026-11-12-stack-warm.md):
|
|
11
|
+
|
|
12
|
+
- macOS: memory is unified, so the file cache and other apps compete with the model. ``purge``
|
|
13
|
+
needs root; oMLX frees no system memory either, it only budgets around what is in use. The
|
|
14
|
+
Metal residency keep-alive every llama.cpp service already gets (metal.SERVICE_ENV) keeps the
|
|
15
|
+
weights wired; the warm requests take the first-command stall.
|
|
16
|
+
- Windows: the model is in VRAM. A service started as background work (from a scheduled task,
|
|
17
|
+
for one) has its host memory taken while it idles, 32 MiB resident within minutes; services
|
|
18
|
+
start at normal priority (process_identity.spawn_detached) and warm sets a server an older
|
|
19
|
+
version started to normal. warm also prints the driver setting that keeps CUDA out of
|
|
20
|
+
system memory.
|
|
21
|
+
- The first request after a pause is slower because the GPU has gone to its idle power state,
|
|
22
|
+
not because of host memory (CYC3, RTX 4060 Ti on Windows: P8 at 210 MHz after 90 idle
|
|
23
|
+
seconds; the next request spent 361 ms on 5 prompt tokens against 45 ms, with the server's
|
|
24
|
+
memory fully resident). The warm requests take that wait; it returns after the next pause.
|
|
25
|
+
- Linux: the page cache already counts as available and a fully offloaded model lives in VRAM;
|
|
26
|
+
warm reads the host and sends the warm requests.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import argparse
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import re
|
|
35
|
+
import shutil
|
|
36
|
+
import socket
|
|
37
|
+
import subprocess
|
|
38
|
+
import sys
|
|
39
|
+
import time
|
|
40
|
+
import urllib.error
|
|
41
|
+
import urllib.request
|
|
42
|
+
from collections.abc import Callable
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
from typing import Literal, TypedDict
|
|
45
|
+
|
|
46
|
+
from localmodels import (
|
|
47
|
+
cli_help,
|
|
48
|
+
metal,
|
|
49
|
+
metal_probe,
|
|
50
|
+
probe,
|
|
51
|
+
process_identity,
|
|
52
|
+
stack_up,
|
|
53
|
+
stack_verify,
|
|
54
|
+
)
|
|
55
|
+
from localmodels.budget import gib
|
|
56
|
+
from localmodels.records import Plan
|
|
57
|
+
from localmodels.stack_plan import StackPlan, command
|
|
58
|
+
|
|
59
|
+
SCHEMA: Literal["localmodels.stack-warm/v1"] = "localmodels.stack-warm/v1"
|
|
60
|
+
HOLDERS_SHOWN = 5
|
|
61
|
+
HOLDER_FLOOR_BYTES = 200 << 20 # smaller processes are noise next to a model
|
|
62
|
+
REQUEST_TIMEOUT_S = 180 # a cold first request on a large model
|
|
63
|
+
WARM_TOKENS = 64
|
|
64
|
+
# Ordinary prose, so the speed is the one a user sees. A counting prompt is so predictable that
|
|
65
|
+
# speculative decoding (MTP) accepts nearly every draft: Qwen3.8-27B read 118-126 tok/s on it
|
|
66
|
+
# (CYC2, local-118), well above the same server's speed on prose.
|
|
67
|
+
WARM_PROMPT = "In a few sentences, explain why the sky looks blue during the day."
|
|
68
|
+
|
|
69
|
+
Out = Callable[[str], None]
|
|
70
|
+
Run = Callable[[list[str]], tuple[int | None, str]]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _MemoryMac(TypedDict, total=False):
|
|
74
|
+
file_cache_bytes: int # file-backed pages; what macOS ``purge`` flushes
|
|
75
|
+
compressed_bytes: int # RAM the compressor occupies
|
|
76
|
+
swap_used_bytes: int
|
|
77
|
+
pressure_level: int # 1 normal, 2 warning, 4 critical
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Memory(_MemoryMac):
|
|
81
|
+
total_bytes: int
|
|
82
|
+
available_bytes: int
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Holder(TypedDict):
|
|
86
|
+
name: str
|
|
87
|
+
rss_bytes: int
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Step(TypedDict):
|
|
91
|
+
step: str # a stable id: reclaim.file-cache, pin.memory, gpu.sysmem-fallback, ...
|
|
92
|
+
ok: bool | None # None: nothing was done here, read ``detail`` and ``hint``
|
|
93
|
+
detail: str
|
|
94
|
+
hint: str | None # a command for an administrator; this tool runs it only under --sudo
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class LlmWarm(TypedDict):
|
|
98
|
+
name: str
|
|
99
|
+
ok: bool
|
|
100
|
+
detail: str
|
|
101
|
+
first_s: float | None # wall time of the first request
|
|
102
|
+
second_s: float | None # and of the one after it
|
|
103
|
+
# The server's own decode speed on the second request. No prefill speed: the prompt is a
|
|
104
|
+
# few dozen tokens and cached by then, so the server's figure for it means nothing.
|
|
105
|
+
decode_tok_s: float | None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _RoutedReport(TypedDict, total=False):
|
|
109
|
+
llm_fast: LlmWarm
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class Report(_RoutedReport):
|
|
113
|
+
schema: Literal["localmodels.stack-warm/v1"]
|
|
114
|
+
hostname: str
|
|
115
|
+
platform: str
|
|
116
|
+
memory_before: Memory
|
|
117
|
+
memory_after: Memory
|
|
118
|
+
holders: list[Holder]
|
|
119
|
+
steps: list[Step]
|
|
120
|
+
llm: LlmWarm | None # None: no accepted stack on this computer
|
|
121
|
+
ok: bool
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _run(argv: list[str]) -> tuple[int | None, str]:
|
|
125
|
+
"""(exit status, stdout) of a short host command; (None, "") when it cannot run."""
|
|
126
|
+
try:
|
|
127
|
+
done = subprocess.run(
|
|
128
|
+
argv,
|
|
129
|
+
capture_output=True,
|
|
130
|
+
text=True,
|
|
131
|
+
encoding="utf-8",
|
|
132
|
+
errors="replace",
|
|
133
|
+
timeout=60,
|
|
134
|
+
check=False,
|
|
135
|
+
stdin=subprocess.DEVNULL,
|
|
136
|
+
env={**os.environ, "LC_ALL": "C"},
|
|
137
|
+
)
|
|
138
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
139
|
+
return None, ""
|
|
140
|
+
return done.returncode, done.stdout
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _pages(vm_stat: str, name: str) -> int:
|
|
144
|
+
page = re.search(r"page size of (\d+)", vm_stat)
|
|
145
|
+
count = re.search(rf"{re.escape(name)}:\s+(\d+)\.", vm_stat)
|
|
146
|
+
return int(count[1]) * int(page[1]) if page and count else 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def memory(platform: str = sys.platform, run: Run = _run) -> Memory:
|
|
150
|
+
"""What this computer has and what is available now, as the planner counts it."""
|
|
151
|
+
total, available = probe.ram()
|
|
152
|
+
seen: Memory = {"total_bytes": total, "available_bytes": available}
|
|
153
|
+
if platform == "darwin":
|
|
154
|
+
_, vm_stat = run(["/usr/bin/vm_stat"])
|
|
155
|
+
seen["file_cache_bytes"] = _pages(vm_stat, "File-backed pages")
|
|
156
|
+
seen["compressed_bytes"] = _pages(vm_stat, "Pages occupied by compressor")
|
|
157
|
+
status = metal_probe.memory_status()
|
|
158
|
+
if "swap_used_bytes" in status:
|
|
159
|
+
seen["swap_used_bytes"] = status["swap_used_bytes"]
|
|
160
|
+
if "pressure_level" in status:
|
|
161
|
+
seen["pressure_level"] = status["pressure_level"]
|
|
162
|
+
return seen
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _app_name(path: str) -> str:
|
|
166
|
+
"""The app a process belongs to: its .app bundle when it has one, else the program name."""
|
|
167
|
+
bundle = re.search(r"/([^/]+)\.app/", path)
|
|
168
|
+
name = bundle[1] if bundle else path.replace("\\", "/").rsplit("/", 1)[-1]
|
|
169
|
+
return name.removesuffix(".exe") or path
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def parse_ps(text: str) -> dict[str, int]:
|
|
173
|
+
"""``ps -axo rss=,comm=`` lines summed per app, in bytes (ps reports KiB)."""
|
|
174
|
+
sums: dict[str, int] = {}
|
|
175
|
+
for line in text.splitlines():
|
|
176
|
+
size, _, path = line.strip().partition(" ")
|
|
177
|
+
if size.isdigit() and path.strip():
|
|
178
|
+
name = _app_name(path.strip())
|
|
179
|
+
sums[name] = sums.get(name, 0) + int(size) * 1024
|
|
180
|
+
return sums
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def parse_tasklist(text: str) -> dict[str, int]:
|
|
184
|
+
"""``tasklist /fo csv /nh`` rows summed per image: "name","pid","session","n","12,345 K"."""
|
|
185
|
+
sums: dict[str, int] = {}
|
|
186
|
+
for line in text.splitlines():
|
|
187
|
+
cells = [c.strip('"') for c in line.strip().split('","')]
|
|
188
|
+
digits = re.sub(r"\D", "", cells[-1]) if len(cells) >= 5 else ""
|
|
189
|
+
if digits:
|
|
190
|
+
name = _app_name(cells[0])
|
|
191
|
+
sums[name] = sums.get(name, 0) + int(digits) * 1024
|
|
192
|
+
return sums
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def holders(platform: str = sys.platform, run: Run = _run) -> list[Holder]:
|
|
196
|
+
"""The apps holding the most memory, largest first: what to quit before a large install.
|
|
197
|
+
Resident sizes count shared pages once per process, so each figure is an upper bound."""
|
|
198
|
+
if platform == "win32":
|
|
199
|
+
sums = parse_tasklist(run(["tasklist", "/fo", "csv", "/nh"])[1])
|
|
200
|
+
else:
|
|
201
|
+
sums = parse_ps(run(["ps", "-axo", "rss=,comm="])[1])
|
|
202
|
+
ranked = sorted(sums.items(), key=lambda item: (-item[1], item[0]))
|
|
203
|
+
return [
|
|
204
|
+
{"name": name, "rss_bytes": size}
|
|
205
|
+
for name, size in ranked[:HOLDERS_SHOWN]
|
|
206
|
+
if size >= HOLDER_FLOOR_BYTES
|
|
207
|
+
]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _purge(allow_sudo: bool, run: Run) -> Step:
|
|
211
|
+
"""macOS: flush the file cache. Only root may; without --sudo the command is the hint."""
|
|
212
|
+
step: Step = {"step": "reclaim.file-cache", "ok": None, "detail": "", "hint": None}
|
|
213
|
+
root = hasattr(os, "geteuid") and os.geteuid() == 0
|
|
214
|
+
if not (root or allow_sudo):
|
|
215
|
+
step["detail"] = (
|
|
216
|
+
"flushing the file cache needs an administrator; it frees file-backed memory, "
|
|
217
|
+
"never an app's own"
|
|
218
|
+
)
|
|
219
|
+
step["hint"] = "sudo purge"
|
|
220
|
+
return step
|
|
221
|
+
argv = ["/usr/sbin/purge"] if root else ["sudo", "/usr/sbin/purge"]
|
|
222
|
+
try: # sudo may ask for the password on this terminal, so it keeps stdin
|
|
223
|
+
code: int | None = subprocess.run(argv, check=False, timeout=300).returncode
|
|
224
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
225
|
+
code = None
|
|
226
|
+
step["ok"] = code == 0
|
|
227
|
+
step["detail"] = "flushed the file cache" if code == 0 else "purge did not run"
|
|
228
|
+
return step
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _mac_steps(allow_sudo: bool, run: Run) -> list[Step]:
|
|
232
|
+
steps = [_purge(allow_sudo, run)]
|
|
233
|
+
code, limit = run(["/usr/sbin/sysctl", "-n", "iogpu.wired_limit_mb"])
|
|
234
|
+
total, available = probe.ram()
|
|
235
|
+
raised = metal.raised_working_set(total) >> 20 # 95%, oMLX's field-stable margin
|
|
236
|
+
capped = available - metal.HOST_KEEP_BYTES > metal.default_working_set(total)
|
|
237
|
+
if code == 0 and limit.strip() == "0" and capped: # the cap, not the memory, is the bound
|
|
238
|
+
steps.append(
|
|
239
|
+
{
|
|
240
|
+
"step": "gpu.wired-limit",
|
|
241
|
+
"ok": None,
|
|
242
|
+
"detail": "the Metal GPU keeps Apple's default share of the memory; raising it "
|
|
243
|
+
"lets a larger model stay on the GPU until the next reboot",
|
|
244
|
+
"hint": f"sudo sysctl iogpu.wired_limit_mb={raised}",
|
|
245
|
+
}
|
|
246
|
+
)
|
|
247
|
+
steps.append(
|
|
248
|
+
{
|
|
249
|
+
"step": "pin.memory",
|
|
250
|
+
"ok": True,
|
|
251
|
+
"detail": "llama.cpp services installed by this tool keep their weights wired "
|
|
252
|
+
"while idle (GGML_METAL_RESIDENCY_KEEP_ALIVE_S)",
|
|
253
|
+
"hint": None,
|
|
254
|
+
}
|
|
255
|
+
)
|
|
256
|
+
return steps
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _windows_steps(run: Run) -> list[Step]:
|
|
260
|
+
steps: list[Step] = [
|
|
261
|
+
{
|
|
262
|
+
"step": "gpu.sysmem-fallback",
|
|
263
|
+
"ok": None,
|
|
264
|
+
"detail": "NVIDIA drivers from 546.01 spill CUDA memory into system RAM when VRAM "
|
|
265
|
+
"runs out, which is many times slower; set the server's program to refuse instead",
|
|
266
|
+
"hint": "NVIDIA Control Panel > Manage 3D settings > CUDA - Sysmem Fallback Policy "
|
|
267
|
+
"> Prefer No Sysmem Fallback",
|
|
268
|
+
},
|
|
269
|
+
]
|
|
270
|
+
code, scheme = run(["powercfg", "/getactivescheme"])
|
|
271
|
+
if code == 0 and scheme.strip():
|
|
272
|
+
name = re.search(r"\(([^)]*)\)\s*$", scheme.strip())
|
|
273
|
+
steps.append(
|
|
274
|
+
{
|
|
275
|
+
"step": "power.plan",
|
|
276
|
+
"ok": None,
|
|
277
|
+
"detail": f"active power plan: {name[1] if name else scheme.strip()}",
|
|
278
|
+
"hint": "powercfg /setactive SCHEME_MIN (High performance)",
|
|
279
|
+
}
|
|
280
|
+
)
|
|
281
|
+
return steps
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _linux_steps(run: Run) -> list[Step]:
|
|
285
|
+
steps: list[Step] = [
|
|
286
|
+
{
|
|
287
|
+
"step": "reclaim.page-cache",
|
|
288
|
+
"ok": True,
|
|
289
|
+
"detail": "nothing to free: the page cache already counts as available memory",
|
|
290
|
+
"hint": None,
|
|
291
|
+
}
|
|
292
|
+
]
|
|
293
|
+
if shutil.which("nvidia-smi"):
|
|
294
|
+
query = "--query-compute-apps=pid,used_memory"
|
|
295
|
+
code, apps = run(["nvidia-smi", query, "--format=csv,noheader,nounits"])
|
|
296
|
+
busy = [line for line in apps.splitlines() if line.strip()] if code == 0 else []
|
|
297
|
+
steps.append(
|
|
298
|
+
{
|
|
299
|
+
"step": "gpu.holders",
|
|
300
|
+
"ok": None if busy else True,
|
|
301
|
+
"detail": f"{len(busy)} compute process(es) hold GPU memory now; "
|
|
302
|
+
f"{command()} stack hardware names them"
|
|
303
|
+
if busy
|
|
304
|
+
else "no compute process holds GPU memory",
|
|
305
|
+
"hint": None,
|
|
306
|
+
}
|
|
307
|
+
)
|
|
308
|
+
return steps
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def host_steps(platform: str, allow_sudo: bool, run: Run = _run) -> list[Step]:
|
|
312
|
+
if platform == "darwin":
|
|
313
|
+
return _mac_steps(allow_sudo, run)
|
|
314
|
+
if platform == "win32":
|
|
315
|
+
return _windows_steps(run)
|
|
316
|
+
return _linux_steps(run)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _chat(url: str, model: str, secret: str) -> tuple[float, dict[str, object]]:
|
|
320
|
+
"""One short completion straight at the LLM: (wall seconds, the response document)."""
|
|
321
|
+
body = {
|
|
322
|
+
"model": model,
|
|
323
|
+
"messages": [{"role": "user", "content": WARM_PROMPT}],
|
|
324
|
+
"max_tokens": WARM_TOKENS,
|
|
325
|
+
"stream": False,
|
|
326
|
+
}
|
|
327
|
+
request = urllib.request.Request(
|
|
328
|
+
url.rstrip("/") + "/chat/completions",
|
|
329
|
+
data=json.dumps(body).encode(),
|
|
330
|
+
headers={"Content-Type": "application/json", "Authorization": f"Bearer {secret}"},
|
|
331
|
+
)
|
|
332
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback, no proxy
|
|
333
|
+
started = time.monotonic()
|
|
334
|
+
with opener.open(request, timeout=REQUEST_TIMEOUT_S) as response:
|
|
335
|
+
doc = json.loads(response.read())
|
|
336
|
+
return time.monotonic() - started, doc if isinstance(doc, dict) else {}
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _decode_speed(doc: dict[str, object], seconds: float) -> float | None:
|
|
340
|
+
"""Decode tok/s: llama-server's own ``timings``; else completion tokens over the wall time,
|
|
341
|
+
which includes the prefill and so reads low."""
|
|
342
|
+
timings = doc.get("timings")
|
|
343
|
+
decode = timings.get("predicted_per_second") if isinstance(timings, dict) else None
|
|
344
|
+
if isinstance(decode, int | float) and decode > 0:
|
|
345
|
+
return float(decode)
|
|
346
|
+
usage = doc.get("usage")
|
|
347
|
+
tokens = usage.get("completion_tokens") if isinstance(usage, dict) else None
|
|
348
|
+
if isinstance(tokens, int) and tokens > 0 and seconds > 0:
|
|
349
|
+
return tokens / seconds
|
|
350
|
+
return None
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
Chat = Callable[[str, str, str], tuple[float, dict[str, object]]]
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def warm_llm(part: Plan, chat: Chat = _chat) -> LlmWarm:
|
|
357
|
+
"""Two short requests at the stack's LLM. The first takes whatever is cold; the second is
|
|
358
|
+
the speed a user gets."""
|
|
359
|
+
seen: LlmWarm = {
|
|
360
|
+
"name": part["name"],
|
|
361
|
+
"ok": False,
|
|
362
|
+
"detail": "",
|
|
363
|
+
"first_s": None,
|
|
364
|
+
"second_s": None,
|
|
365
|
+
"decode_tok_s": None,
|
|
366
|
+
}
|
|
367
|
+
secret = stack_verify.key(part)
|
|
368
|
+
if secret is None:
|
|
369
|
+
seen["detail"] = f"no api-key in its deployment directory; run {command()} stack up"
|
|
370
|
+
return seen
|
|
371
|
+
url, model = str(part["endpoint"]["base_url"]), str(part["model"]["model_id"])
|
|
372
|
+
try:
|
|
373
|
+
first, _ = chat(url, model, secret)
|
|
374
|
+
second, doc = chat(url, model, secret)
|
|
375
|
+
except (OSError, ValueError) as exc: # URLError and timeouts are OSErrors
|
|
376
|
+
seen["detail"] = f"no answer from {url}: {exc}; run {command()} stack up"
|
|
377
|
+
return seen
|
|
378
|
+
seen["first_s"], seen["second_s"] = first, second
|
|
379
|
+
seen["decode_tok_s"] = _decode_speed(doc, second)
|
|
380
|
+
seen["ok"] = True
|
|
381
|
+
seen["detail"] = "loaded and answering"
|
|
382
|
+
return seen
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
Probe = Callable[[int], "process_identity.Priority | None"]
|
|
386
|
+
Raise = Callable[[int], process_identity.Priority]
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def pin_step(
|
|
390
|
+
part: Plan | None,
|
|
391
|
+
probe: Probe = process_identity.priority,
|
|
392
|
+
normal: Raise = process_identity.run_at_normal_priority,
|
|
393
|
+
) -> Step:
|
|
394
|
+
"""Windows: the stack's model server keeps its memory while it idles. It does at normal
|
|
395
|
+
priority, which this tool gives every service it starts; a server an older version
|
|
396
|
+
started from a background task is set to normal here. ``part`` None: no stack."""
|
|
397
|
+
step: Step = {"step": "pin.memory", "ok": None, "detail": "", "hint": None}
|
|
398
|
+
if part is None:
|
|
399
|
+
step["detail"] = (
|
|
400
|
+
"Windows takes the memory of an idle service that runs as background work; this "
|
|
401
|
+
"tool starts its services at normal priority, and sets a running model server to "
|
|
402
|
+
"normal here once a stack is installed"
|
|
403
|
+
)
|
|
404
|
+
return step
|
|
405
|
+
state, pid = process_identity.status(
|
|
406
|
+
Path(os.path.expanduser(part["service"]["deploy_dir"]), "server.pid")
|
|
407
|
+
)
|
|
408
|
+
seen = probe(pid) if state == "active" and pid else None
|
|
409
|
+
if pid is None or seen is None:
|
|
410
|
+
step["detail"] = f"{part['name']} is not running; {command()} stack up starts it"
|
|
411
|
+
return step
|
|
412
|
+
try:
|
|
413
|
+
now = normal(pid) if seen["background"] else seen
|
|
414
|
+
except OSError as exc:
|
|
415
|
+
step["ok"] = False
|
|
416
|
+
step["detail"] = f"{part['name']} is left running as background work: {exc}"
|
|
417
|
+
return step
|
|
418
|
+
step["ok"] = not now["background"]
|
|
419
|
+
step["detail"] = (
|
|
420
|
+
f"{part['name']} runs at normal priority, so Windows leaves an idle server its memory "
|
|
421
|
+
f"({now['resident_bytes'] >> 20} MiB resident now"
|
|
422
|
+
+ (
|
|
423
|
+
f"; it ran as background work before, memory priority {seen['memory_priority']} of 5)"
|
|
424
|
+
if seen["background"]
|
|
425
|
+
else ")"
|
|
426
|
+
)
|
|
427
|
+
)
|
|
428
|
+
return step
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def warm(
|
|
432
|
+
*,
|
|
433
|
+
allow_sudo: bool = False,
|
|
434
|
+
host_only: bool = False,
|
|
435
|
+
platform: str = sys.platform,
|
|
436
|
+
run: Run = _run,
|
|
437
|
+
plan: StackPlan | None = None,
|
|
438
|
+
chat: Chat = _chat,
|
|
439
|
+
) -> Report:
|
|
440
|
+
"""Read the host, free what may be freed, then warm and measure each installed LLM."""
|
|
441
|
+
before = memory(platform, run)
|
|
442
|
+
held = holders(platform, run)
|
|
443
|
+
steps = host_steps(platform, allow_sudo, run)
|
|
444
|
+
after = memory(platform, run)
|
|
445
|
+
parts = (
|
|
446
|
+
[]
|
|
447
|
+
if host_only or plan is None
|
|
448
|
+
else [
|
|
449
|
+
(role, part)
|
|
450
|
+
for role, part in (("llm", plan["llm"]), ("llm_fast", plan.get("llm_fast")))
|
|
451
|
+
if part is not None
|
|
452
|
+
]
|
|
453
|
+
)
|
|
454
|
+
warmed = {role: warm_llm(part, chat) for role, part in parts}
|
|
455
|
+
if platform == "win32": # after the requests: the step reports what they left resident
|
|
456
|
+
steps[0:0] = [pin_step(part) for _, part in parts] if parts else [pin_step(None)]
|
|
457
|
+
report: Report = {
|
|
458
|
+
"schema": SCHEMA,
|
|
459
|
+
"hostname": socket.gethostname(),
|
|
460
|
+
"platform": platform,
|
|
461
|
+
"memory_before": before,
|
|
462
|
+
"memory_after": after,
|
|
463
|
+
"holders": held,
|
|
464
|
+
"steps": steps,
|
|
465
|
+
"llm": warmed.get("llm"),
|
|
466
|
+
"ok": all(s["ok"] is not False for s in steps) and all(p["ok"] for p in warmed.values()),
|
|
467
|
+
}
|
|
468
|
+
if "llm_fast" in warmed:
|
|
469
|
+
report["llm_fast"] = warmed["llm_fast"]
|
|
470
|
+
return report
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
_PRESSURE = {1: "normal", 2: "warning", 4: "critical"}
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _memory_line(seen: Memory) -> str:
|
|
477
|
+
parts = [f"{gib(seen['total_bytes'])}, available {gib(seen['available_bytes'])}"]
|
|
478
|
+
if "file_cache_bytes" in seen:
|
|
479
|
+
parts.append(f"file cache {gib(seen['file_cache_bytes'])}")
|
|
480
|
+
if seen.get("compressed_bytes"):
|
|
481
|
+
parts.append(f"compressed {gib(seen['compressed_bytes'])}")
|
|
482
|
+
if seen.get("swap_used_bytes"):
|
|
483
|
+
parts.append(f"swap used {gib(seen['swap_used_bytes'])}")
|
|
484
|
+
if "pressure_level" in seen:
|
|
485
|
+
parts.append(f"pressure {_PRESSURE.get(seen['pressure_level'], 'unknown')}")
|
|
486
|
+
return "; ".join(parts)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def lines(report: Report) -> list[str]:
|
|
490
|
+
"""What ``stack warm`` prints."""
|
|
491
|
+
out = [f"Warm {report['hostname']} ({report['platform']})"]
|
|
492
|
+
out.append(f" memory {_memory_line(report['memory_before'])}")
|
|
493
|
+
if report["holders"]:
|
|
494
|
+
named = ", ".join(f"{h['name']} {gib(h['rss_bytes'])}" for h in report["holders"])
|
|
495
|
+
out.append(f" holders {named} (resident size; quit what you can before a large install)")
|
|
496
|
+
for step in report["steps"]:
|
|
497
|
+
mark = {True: "✓", False: "✗", None: "-"}[step["ok"]]
|
|
498
|
+
out.append(f" {mark} {step['step']}: {step['detail']}")
|
|
499
|
+
if step["hint"]:
|
|
500
|
+
out.append(f" run: {step['hint']}")
|
|
501
|
+
gained = report["memory_after"]["available_bytes"] - report["memory_before"]["available_bytes"]
|
|
502
|
+
if any(s["step"] == "reclaim.file-cache" and s["ok"] for s in report["steps"]):
|
|
503
|
+
out.append(
|
|
504
|
+
f" memory now available {gib(report['memory_after']['available_bytes'])} "
|
|
505
|
+
f"({'+' if gained >= 0 else '-'}{gib(abs(gained))})"
|
|
506
|
+
)
|
|
507
|
+
if report["llm"] is None:
|
|
508
|
+
out.append(
|
|
509
|
+
f" stack no accepted stack to warm; {command()} install plans against the "
|
|
510
|
+
"memory available now"
|
|
511
|
+
)
|
|
512
|
+
for role, llm in (("llm", report["llm"]), ("llm_fast", report.get("llm_fast"))):
|
|
513
|
+
if llm is None:
|
|
514
|
+
continue
|
|
515
|
+
if not llm["ok"]:
|
|
516
|
+
out.append(f" ✗ {role} {llm['name']}: {llm['detail']}")
|
|
517
|
+
continue
|
|
518
|
+
speed = (
|
|
519
|
+
f"decode {llm['decode_tok_s']:.1f} tok/s"
|
|
520
|
+
if llm["decode_tok_s"]
|
|
521
|
+
else "decode speed not reported"
|
|
522
|
+
)
|
|
523
|
+
out.append(
|
|
524
|
+
f" ✓ {role} {llm['name']}: first request {llm['first_s']:.2f} s, next "
|
|
525
|
+
f"{llm['second_s']:.2f} s; {speed} (measured now, {WARM_TOKENS} tokens at most)"
|
|
526
|
+
)
|
|
527
|
+
return out
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def add_parser(actions: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
|
|
531
|
+
parser = actions.add_parser(
|
|
532
|
+
"warm", help="free memory and warm each installed LLM; prints measured speeds"
|
|
533
|
+
)
|
|
534
|
+
parser.add_argument("--json", action="store_true", help=f"the report as {SCHEMA}")
|
|
535
|
+
parser.add_argument(
|
|
536
|
+
"--host-only",
|
|
537
|
+
action="store_true",
|
|
538
|
+
help="read and prepare the computer only; send the LLM nothing",
|
|
539
|
+
)
|
|
540
|
+
parser.add_argument(
|
|
541
|
+
"--sudo",
|
|
542
|
+
action="store_true",
|
|
543
|
+
help="also run the step that needs an administrator (macOS: sudo purge, which may ask "
|
|
544
|
+
"for the password); without it the command is only printed",
|
|
545
|
+
)
|
|
546
|
+
cli_help.document(
|
|
547
|
+
parser,
|
|
548
|
+
"Get this computer and its installed stack ready to run at full speed. Host: the "
|
|
549
|
+
"memory available, the apps holding the rest, what can be freed, and the commands "
|
|
550
|
+
"that need an administrator (printed, run only with --sudo). Stack: two short "
|
|
551
|
+
"requests at each running LLM, so the first real request is not a cold start, with "
|
|
552
|
+
"each first-request time and decode speed measured now. Starts and installs nothing; "
|
|
553
|
+
"run it before `install` to free memory for a larger model, and after it to warm up.",
|
|
554
|
+
examples=[
|
|
555
|
+
("%(prog)s", "prepare the computer, warm the LLM, print measured speed"),
|
|
556
|
+
("%(prog)s --host-only", "before an install: memory and hints only"),
|
|
557
|
+
("%(prog)s --sudo", "macOS: also flush the file cache with sudo purge"),
|
|
558
|
+
("%(prog)s --json", f"{SCHEMA}"),
|
|
559
|
+
],
|
|
560
|
+
sections=[
|
|
561
|
+
("exit status", "0 ready · 1 a step or the LLM request failed"),
|
|
562
|
+
],
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def cli(args: argparse.Namespace) -> int:
|
|
567
|
+
plan = None if args.host_only else stack_up._accepted()
|
|
568
|
+
report = warm(allow_sudo=args.sudo, host_only=args.host_only, plan=plan)
|
|
569
|
+
if args.json:
|
|
570
|
+
json.dump(report, sys.stdout, ensure_ascii=False, indent=1)
|
|
571
|
+
sys.stdout.write("\n")
|
|
572
|
+
else:
|
|
573
|
+
print("\n".join(lines(report)))
|
|
574
|
+
return 0 if report["ok"] else 1
|