@simplexai/localmodels-darwin-x64 0.1.0-dev.102 → 0.1.0-dev.103
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 +46 -27
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +3 -1
- package/modules/localmodels/catalog.json +306 -1
- package/modules/localmodels/cli_parser.py +4 -0
- package/modules/localmodels/debug_stub_server.py +280 -7
- package/modules/localmodels/download-mirrors.json +76 -0
- package/modules/localmodels/engines-speechcpp-v0.11.3.json +84 -0
- package/modules/localmodels/library_serve.py +46 -26
- package/modules/localmodels/remote_ops_common.py +12 -2
- package/modules/localmodels/sidecar_downloads.py +426 -0
- package/modules/localmodels/sidecar_http.py +396 -0
- package/modules/localmodels/sidecar_state.py +466 -0
- package/modules/localmodels/speech_admission.py +13 -0
- package/modules/localmodels/speech_jobs.py +81 -370
- package/modules/localmodels/speech_server.py +17 -8
- package/modules/localmodels/speech_state.py +87 -454
- package/modules/localmodels/speech_workers.py +41 -163
- package/modules/localmodels/stack.py +18 -0
- package/modules/localmodels/stack_down.py +19 -14
- package/modules/localmodels/stack_ports.py +1 -0
- package/modules/localmodels/stack_up.py +51 -1
- package/modules/localmodels/strata_poly_server.py +140 -3
- package/modules/localmodels/tts-moss.txt +321 -0
- package/modules/localmodels/tts_admission.py +396 -0
- package/modules/localmodels/tts_backend_speechcpp.py +487 -0
- package/modules/localmodels/tts_catalog.py +251 -0
- package/modules/localmodels/tts_cli.py +333 -0
- package/modules/localmodels/tts_http.py +617 -0
- package/modules/localmodels/tts_jobs.py +496 -0
- package/modules/localmodels/tts_model.py +591 -0
- package/modules/localmodels/tts_moss_presets.json +1 -0
- package/modules/localmodels/tts_serve.py +451 -0
- package/modules/localmodels/tts_sidecar.py +750 -0
- package/modules/localmodels/tts_state.py +395 -0
- package/modules/localmodels/tts_worker_kokoro.py +463 -0
- package/modules/localmodels/tts_worker_moss.py +748 -0
- package/modules/localmodels/tts_workers.py +696 -0
- package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/RECORD +43 -24
- package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/NOTICE +29 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -28,17 +28,43 @@ from localmodels import (
|
|
|
28
28
|
engines,
|
|
29
29
|
frontend,
|
|
30
30
|
http_local,
|
|
31
|
+
sidecar_http,
|
|
31
32
|
speech_admission,
|
|
32
33
|
speech_jobs,
|
|
33
34
|
speech_state,
|
|
34
35
|
speech_worker_sensevoice,
|
|
35
|
-
windows_job,
|
|
36
36
|
)
|
|
37
37
|
from localmodels.probe import HostFacts
|
|
38
|
+
from localmodels.sidecar_http import (
|
|
39
|
+
GPU_OOM_SIGNATURES as GPU_OOM_SIGNATURES,
|
|
40
|
+
)
|
|
41
|
+
from localmodels.sidecar_http import (
|
|
42
|
+
WINDOWS_CREATE_NO_WINDOW as WINDOWS_CREATE_NO_WINDOW,
|
|
43
|
+
)
|
|
44
|
+
from localmodels.sidecar_http import (
|
|
45
|
+
WORKER_READY_TIMEOUT_S as WORKER_READY_TIMEOUT_S,
|
|
46
|
+
)
|
|
47
|
+
from localmodels.sidecar_http import (
|
|
48
|
+
WORKER_STOP_GRACE_S as WORKER_STOP_GRACE_S,
|
|
49
|
+
)
|
|
50
|
+
from localmodels.sidecar_http import (
|
|
51
|
+
ChildWatchdog as ChildWatchdog,
|
|
52
|
+
)
|
|
53
|
+
from localmodels.sidecar_http import (
|
|
54
|
+
SidecarWorkerError,
|
|
55
|
+
)
|
|
56
|
+
from localmodels.sidecar_http import (
|
|
57
|
+
is_gpu_oom_error as is_gpu_oom_error,
|
|
58
|
+
)
|
|
59
|
+
from localmodels.sidecar_http import (
|
|
60
|
+
stop_subprocess as stop_subprocess,
|
|
61
|
+
)
|
|
38
62
|
from localmodels.speech_admission import DeviceDecision
|
|
39
63
|
from localmodels.speech_catalog import SpeechModelSpec
|
|
40
64
|
from localmodels.speech_model import EffectiveDevice, SpeechError
|
|
41
65
|
|
|
66
|
+
WorkerError = SidecarWorkerError
|
|
67
|
+
|
|
42
68
|
SENSEVOICE_REQUIREMENTS = "speech-sv.txt"
|
|
43
69
|
# Simplified-Chinese prompt injected ONLY when language == "zh" and speech is present.
|
|
44
70
|
ZH_SIMPLIFIED_PROMPT = "\u4ee5\u4e0b\u662f\u666e\u901a\u8bdd\u7684\u53e5\u5b50\u3002"
|
|
@@ -50,33 +76,7 @@ _ZH_PROMPT_LEAD_RE = re.compile(rf"^(?:\s*{re.escape(ZH_SIMPLIFIED_PROMPT)})+\s*
|
|
|
50
76
|
_ZH_PROMPT_TRAIL_RE = re.compile(rf"\s*(?:{re.escape(ZH_SIMPLIFIED_PROMPT)}\s*)+$")
|
|
51
77
|
_LINE_BREAK_RE = re.compile(r"\s*\n\s*")
|
|
52
78
|
SILENCE_RMS_THRESHOLD = 150.0 # int16 RMS noise floor (~-46.8 dBFS)
|
|
53
|
-
WORKER_STOP_GRACE_S = 3.0 # whisper-server b5454 hangs on SIGTERM -> SIGKILL after 3s
|
|
54
|
-
WORKER_READY_TIMEOUT_S = 60.0
|
|
55
79
|
WORKER_REQUEST_TIMEOUT_S = 300.0
|
|
56
|
-
WINDOWS_CREATE_NO_WINDOW = 0x08000000
|
|
57
|
-
|
|
58
|
-
_POSIX_WATCHDOG_SH = (
|
|
59
|
-
'read _; kill -TERM "$0" 2>/dev/null; n=0; '
|
|
60
|
-
'while kill -0 "$0" 2>/dev/null && [ "$n" -lt 3 ]; do sleep 1; n=$((n+1)); done; '
|
|
61
|
-
'kill -KILL "$0" 2>/dev/null'
|
|
62
|
-
)
|
|
63
|
-
GPU_OOM_SIGNATURES: tuple[str, ...] = (
|
|
64
|
-
"oom",
|
|
65
|
-
"out of memory",
|
|
66
|
-
"cuda",
|
|
67
|
-
"cublas",
|
|
68
|
-
"metal",
|
|
69
|
-
"vulkan",
|
|
70
|
-
"vkresult",
|
|
71
|
-
"directml",
|
|
72
|
-
"failed to allocate",
|
|
73
|
-
"unable to allocate",
|
|
74
|
-
"not enough memory",
|
|
75
|
-
"insufficient memory",
|
|
76
|
-
"bad_alloc",
|
|
77
|
-
"kioreturnnomemory",
|
|
78
|
-
"newbufferwithlength",
|
|
79
|
-
)
|
|
80
80
|
|
|
81
81
|
_BOUNDARY_RE = re.compile(r'boundary=(?:"([^"]+)"|([^;\s]+))', re.IGNORECASE)
|
|
82
82
|
_DISPOSITION_PARAM_RE = re.compile(r'([a-zA-Z0-9_-]+)="([^"]*)"')
|
|
@@ -207,23 +207,6 @@ def normalize_whisper_language(raw: str) -> str:
|
|
|
207
207
|
return _WHISPER_LANGUAGE_TO_ISO.get(cleaned, cleaned)
|
|
208
208
|
|
|
209
209
|
|
|
210
|
-
class WorkerError(RuntimeError):
|
|
211
|
-
"""Raised when an isolated speech engine child fails to start or process audio."""
|
|
212
|
-
|
|
213
|
-
def __init__(self, message: str, *, detail: str = "", exit_status: int | None = None) -> None:
|
|
214
|
-
super().__init__(message)
|
|
215
|
-
self.detail = detail or message
|
|
216
|
-
# Set when the child exited on its own (before readiness or mid-request); a timeout or a
|
|
217
|
-
# launch failure leaves it None. The sidecar uses it to spot deterministic crash loops.
|
|
218
|
-
self.exit_status = exit_status
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
def is_gpu_oom_error(message: str) -> bool:
|
|
222
|
-
"""Return True when ``message`` matches any known GPU or OOM failure signature."""
|
|
223
|
-
lowered = message.lower()
|
|
224
|
-
return any(sig in lowered for sig in GPU_OOM_SIGNATURES)
|
|
225
|
-
|
|
226
|
-
|
|
227
210
|
def validate_wav_and_rms(data: bytes) -> tuple[float, float]:
|
|
228
211
|
"""Validate 16-bit mono PCM WAV bytes and return ``(duration_seconds, int16_rms)``."""
|
|
229
212
|
samples, _rate, duration = speech_worker_sensevoice.read_pcm16_wav(data)
|
|
@@ -305,12 +288,7 @@ def build_multipart_body(
|
|
|
305
288
|
|
|
306
289
|
def ensure_run_dir(state_dir: Path | None) -> Path:
|
|
307
290
|
"""Ensure ``$LOCALMODELS_STATE/speech/run`` exists with 0700 permissions."""
|
|
308
|
-
|
|
309
|
-
path.mkdir(parents=True, exist_ok=True)
|
|
310
|
-
if os.name != "nt":
|
|
311
|
-
with contextlib.suppress(OSError):
|
|
312
|
-
path.chmod(0o700)
|
|
313
|
-
return path
|
|
291
|
+
return speech_state.STORE.ensure_run_dir(state_dir)
|
|
314
292
|
|
|
315
293
|
|
|
316
294
|
def whisper_argv(
|
|
@@ -424,69 +402,6 @@ def _resolve_qwen3_asr_paths(spec: SpeechModelSpec, base_dir: str) -> tuple[str,
|
|
|
424
402
|
return str(conv), str(enc), str(dec), str(vocab.parent)
|
|
425
403
|
|
|
426
404
|
|
|
427
|
-
class ChildWatchdog:
|
|
428
|
-
"""Binds a child worker's lifetime to this sidecar via POSIX pipe guard or Windows Job."""
|
|
429
|
-
|
|
430
|
-
def __init__(self, proc: subprocess.Popen[bytes]) -> None:
|
|
431
|
-
self._guard: subprocess.Popen[bytes] | None = None
|
|
432
|
-
self._write_fd: int | None = None
|
|
433
|
-
if sys.platform == "win32":
|
|
434
|
-
handle = getattr(proc, "_handle", None)
|
|
435
|
-
if isinstance(handle, int):
|
|
436
|
-
windows_job.end_with_this_process(handle)
|
|
437
|
-
return
|
|
438
|
-
if os.name == "posix":
|
|
439
|
-
read_fd, write_fd = os.pipe()
|
|
440
|
-
try:
|
|
441
|
-
self._guard = subprocess.Popen(
|
|
442
|
-
["/bin/sh", "-c", _POSIX_WATCHDOG_SH, str(proc.pid)],
|
|
443
|
-
stdin=read_fd,
|
|
444
|
-
stdout=subprocess.DEVNULL,
|
|
445
|
-
stderr=subprocess.DEVNULL,
|
|
446
|
-
)
|
|
447
|
-
self._write_fd = write_fd
|
|
448
|
-
except OSError:
|
|
449
|
-
os.close(write_fd)
|
|
450
|
-
finally:
|
|
451
|
-
os.close(read_fd)
|
|
452
|
-
|
|
453
|
-
def close(self) -> None:
|
|
454
|
-
"""Stop the POSIX watchdog before closing its pipe so it does not signal a reused PID."""
|
|
455
|
-
if self._guard is not None:
|
|
456
|
-
with contextlib.suppress(OSError):
|
|
457
|
-
self._guard.kill()
|
|
458
|
-
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
|
|
459
|
-
self._guard.wait(timeout=2.0)
|
|
460
|
-
self._guard = None
|
|
461
|
-
if self._write_fd is not None:
|
|
462
|
-
with contextlib.suppress(OSError):
|
|
463
|
-
os.close(self._write_fd)
|
|
464
|
-
self._write_fd = None
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
def stop_subprocess(
|
|
468
|
-
proc: subprocess.Popen[bytes],
|
|
469
|
-
watchdog: ChildWatchdog | None = None,
|
|
470
|
-
*,
|
|
471
|
-
grace_s: float = WORKER_STOP_GRACE_S,
|
|
472
|
-
) -> None:
|
|
473
|
-
"""Terminate ``proc`` with ``SIGTERM -> grace_s -> SIGKILL`` and release its watchdog."""
|
|
474
|
-
try:
|
|
475
|
-
if proc.poll() is None:
|
|
476
|
-
with contextlib.suppress(OSError):
|
|
477
|
-
proc.terminate()
|
|
478
|
-
try:
|
|
479
|
-
proc.wait(timeout=max(0.1, grace_s))
|
|
480
|
-
except subprocess.TimeoutExpired:
|
|
481
|
-
with contextlib.suppress(OSError):
|
|
482
|
-
proc.kill()
|
|
483
|
-
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
|
|
484
|
-
proc.wait(timeout=5.0)
|
|
485
|
-
finally:
|
|
486
|
-
if watchdog is not None:
|
|
487
|
-
watchdog.close()
|
|
488
|
-
|
|
489
|
-
|
|
490
405
|
@dataclass
|
|
491
406
|
class WorkerHandle:
|
|
492
407
|
"""Live isolated engine child subprocess owned by ``SpeechSidecar``."""
|
|
@@ -526,34 +441,10 @@ def wait_worker_ready(
|
|
|
526
441
|
timeout_s: float = WORKER_READY_TIMEOUT_S,
|
|
527
442
|
) -> None:
|
|
528
443
|
"""Wait until the child engine answers loopback HTTP 200 or exits early."""
|
|
529
|
-
deadline = time.monotonic() + timeout_s
|
|
530
444
|
paths = ("/health", "/") if engine == "whisper.cpp" else ("/health",)
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
if code is not None:
|
|
535
|
-
tail = ""
|
|
536
|
-
with contextlib.suppress(OSError):
|
|
537
|
-
tail = stderr_path.read_text(encoding="utf-8", errors="replace")[-1200:].strip()
|
|
538
|
-
raise WorkerError(
|
|
539
|
-
f"{engine} worker exited with status {code}",
|
|
540
|
-
detail=tail or f"exit code {code}",
|
|
541
|
-
exit_status=code,
|
|
542
|
-
)
|
|
543
|
-
for path in paths:
|
|
544
|
-
req = urllib.request.Request(
|
|
545
|
-
f"http://127.0.0.1:{port}{path}",
|
|
546
|
-
headers={"Connection": "close"},
|
|
547
|
-
method="GET",
|
|
548
|
-
)
|
|
549
|
-
try:
|
|
550
|
-
with opener.open(req, timeout=1.0) as resp:
|
|
551
|
-
if 200 <= getattr(resp, "status", 200) < 300:
|
|
552
|
-
return
|
|
553
|
-
except (urllib.error.URLError, OSError, http.client.HTTPException):
|
|
554
|
-
continue
|
|
555
|
-
time.sleep(0.1)
|
|
556
|
-
raise WorkerError(f"{engine} worker did not become ready within {timeout_s:.0f}s")
|
|
445
|
+
sidecar_http.wait_worker_ready(
|
|
446
|
+
proc, port, engine, stderr_path, timeout_s=timeout_s, paths=paths
|
|
447
|
+
)
|
|
557
448
|
|
|
558
449
|
|
|
559
450
|
def resolve_whisper_binary(
|
|
@@ -612,29 +503,16 @@ def _launch_worker_process(
|
|
|
612
503
|
"""Spawn, watchdog-bind, and health-check a worker child process."""
|
|
613
504
|
run_cwd = ensure_run_dir(state_dir)
|
|
614
505
|
stderr_path = run_cwd / f"worker-{spec.id}-{port}.stderr.log"
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
stderr=err_stream,
|
|
626
|
-
**kwargs,
|
|
627
|
-
)
|
|
628
|
-
except OSError as exc:
|
|
629
|
-
raise WorkerError(f"failed to launch {spec.engine} worker: {exc}") from None
|
|
630
|
-
|
|
631
|
-
watchdog = ChildWatchdog(proc)
|
|
632
|
-
try:
|
|
633
|
-
wait_worker_ready(proc, port, spec.engine, stderr_path)
|
|
634
|
-
except Exception:
|
|
635
|
-
stop_subprocess(proc, watchdog)
|
|
636
|
-
raise
|
|
637
|
-
|
|
506
|
+
paths = ("/health", "/") if spec.engine == "whisper.cpp" else ("/health",)
|
|
507
|
+
proc, watchdog = sidecar_http.launch_worker_subprocess(
|
|
508
|
+
argv,
|
|
509
|
+
env,
|
|
510
|
+
run_cwd,
|
|
511
|
+
stderr_path,
|
|
512
|
+
port,
|
|
513
|
+
spec.engine,
|
|
514
|
+
ready_paths=paths,
|
|
515
|
+
)
|
|
638
516
|
return WorkerHandle(
|
|
639
517
|
model_id=spec.id,
|
|
640
518
|
engine=spec.engine,
|
|
@@ -46,6 +46,7 @@ from localmodels.stack_plan import (
|
|
|
46
46
|
StackPlan,
|
|
47
47
|
StackRecord,
|
|
48
48
|
StackReplanError,
|
|
49
|
+
VramShortError,
|
|
49
50
|
default_options,
|
|
50
51
|
platform_error,
|
|
51
52
|
)
|
|
@@ -247,6 +248,22 @@ WRONG_CODE = "the --approve value is not this plan's approval code"
|
|
|
247
248
|
EDITED_PLAN = "the plan file was changed after it was saved: it no longer matches its approval code"
|
|
248
249
|
|
|
249
250
|
|
|
251
|
+
def _raise_if_vram_short(plan: StackPlan, replan: BaseException) -> None:
|
|
252
|
+
"""A shared card with too little free VRAM now fails planning again before it fails the
|
|
253
|
+
check before start. Name it for what it is: the check's own VramShortError
|
|
254
|
+
(STACK_VRAM_INSUFFICIENT, with the free and required bytes), not STACK_REPLAN_FAILED, whose
|
|
255
|
+
only reason was in the text (MR !781 homewin acceptance, 2026-12-01)."""
|
|
256
|
+
check = hardware.shared_start_guard(plan["llm"], plan["options"], reserve_decision=True)
|
|
257
|
+
if check is None:
|
|
258
|
+
return
|
|
259
|
+
try:
|
|
260
|
+
check()
|
|
261
|
+
except VramShortError as short:
|
|
262
|
+
raise short from replan
|
|
263
|
+
except (PlanError, StackError, OSError):
|
|
264
|
+
return # the replan's own failure stands
|
|
265
|
+
|
|
266
|
+
|
|
250
267
|
def apply(
|
|
251
268
|
plan: StackPlan,
|
|
252
269
|
approval: str,
|
|
@@ -283,6 +300,7 @@ def apply(
|
|
|
283
300
|
else build(plan["options"], approved=plan)
|
|
284
301
|
)
|
|
285
302
|
except (PlanError, StackError) as exc:
|
|
303
|
+
_raise_if_vram_short(plan, exc)
|
|
286
304
|
raise StackReplanError(
|
|
287
305
|
f"planning again from this computer's current state failed: {exc}. "
|
|
288
306
|
"This computer changed, or the plan was made on another machine or "
|
|
@@ -19,6 +19,7 @@ from localmodels import (
|
|
|
19
19
|
deployment_lifecycle,
|
|
20
20
|
hosts,
|
|
21
21
|
speech_state,
|
|
22
|
+
tts_state,
|
|
22
23
|
)
|
|
23
24
|
from localmodels import stack_lifecycle as lifecycle
|
|
24
25
|
from localmodels.stack_plan import StackError, platform_error
|
|
@@ -80,20 +81,24 @@ def _down(out: Out) -> DownReport:
|
|
|
80
81
|
f"{'✗' if failed else '…'} {plan['name']} {'failed to stop' if failed else 'stopped'}"
|
|
81
82
|
)
|
|
82
83
|
parts.append(row)
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
84
|
+
for sidecar_name, task_name, stop_fn in (
|
|
85
|
+
("speech-sidecar", "stt", speech_state.stop_sidecar_if_recorded),
|
|
86
|
+
("tts-sidecar", "tts", tts_state.stop_sidecar_if_recorded),
|
|
87
|
+
):
|
|
88
|
+
action, detail = stop_fn()
|
|
89
|
+
if action == "stopped" or action == "failed":
|
|
90
|
+
parts.append(
|
|
91
|
+
{
|
|
92
|
+
"name": sidecar_name,
|
|
93
|
+
"task": task_name,
|
|
94
|
+
"action": action,
|
|
95
|
+
"detail": detail,
|
|
96
|
+
}
|
|
97
|
+
)
|
|
98
|
+
out(
|
|
99
|
+
f"{'✗' if action == 'failed' else '…'} {sidecar_name} "
|
|
100
|
+
f"{'failed to stop' if action == 'failed' else 'stopped'}"
|
|
101
|
+
)
|
|
97
102
|
return {
|
|
98
103
|
"schema": SCHEMA,
|
|
99
104
|
"ok": all(p["action"] != "failed" for p in parts),
|
|
@@ -28,6 +28,7 @@ from localmodels import (
|
|
|
28
28
|
)
|
|
29
29
|
from localmodels import stack_lifecycle as lifecycle
|
|
30
30
|
from localmodels.contracts import decode
|
|
31
|
+
from localmodels.plan_envelope import PlanError
|
|
31
32
|
from localmodels.planning.budget import gpu_conflicts, gpu_users_unknown, unknown_services
|
|
32
33
|
from localmodels.records import Plan
|
|
33
34
|
from localmodels.stack_plan import (
|
|
@@ -54,7 +55,7 @@ class Part(TypedDict):
|
|
|
54
55
|
detail: str
|
|
55
56
|
|
|
56
57
|
|
|
57
|
-
class
|
|
58
|
+
class _UpResult(TypedDict):
|
|
58
59
|
schema: Literal["localmodels.stack-up/v1"]
|
|
59
60
|
plan_id: str
|
|
60
61
|
ok: bool
|
|
@@ -62,6 +63,42 @@ class UpReport(TypedDict):
|
|
|
62
63
|
notes: list[str]
|
|
63
64
|
|
|
64
65
|
|
|
66
|
+
class UpReport(_UpResult, total=False):
|
|
67
|
+
# A refusal (exit 2): a cause code and a fixed sentence, never the exception's text (it can
|
|
68
|
+
# name paths and plan contents), and for STACK_VRAM_INSUFFICIENT the two byte counts.
|
|
69
|
+
cause_code: str
|
|
70
|
+
message: str
|
|
71
|
+
free_bytes: int
|
|
72
|
+
required_bytes: int
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
REFUSED = (
|
|
76
|
+
"STACK_UP_REFUSED",
|
|
77
|
+
"stack up refused to start the stack; run the same command without --json to see why",
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def refusal(exc: BaseException, plan_id: str) -> UpReport:
|
|
82
|
+
"""The ``--json`` result of an ``up`` that raised ``exc`` before it could report: what
|
|
83
|
+
Linger reads instead of a line on stderr alone."""
|
|
84
|
+
code = getattr(exc, "cause_code", None)
|
|
85
|
+
cause = (code, stack_run.CAUSES[code]) if code == "STACK_VRAM_INSUFFICIENT" else REFUSED
|
|
86
|
+
report: UpReport = {
|
|
87
|
+
"schema": SCHEMA,
|
|
88
|
+
"plan_id": stack_run.safe_digest(plan_id) or "",
|
|
89
|
+
"ok": False,
|
|
90
|
+
"parts": [],
|
|
91
|
+
"notes": [],
|
|
92
|
+
"cause_code": cause[0],
|
|
93
|
+
"message": cause[1],
|
|
94
|
+
}
|
|
95
|
+
counts = stack_run.cause_counts(exc)
|
|
96
|
+
if counts:
|
|
97
|
+
report["free_bytes"] = counts["free_bytes"]
|
|
98
|
+
report["required_bytes"] = counts["required_bytes"]
|
|
99
|
+
return report
|
|
100
|
+
|
|
101
|
+
|
|
65
102
|
def accepted() -> StackPlan | None:
|
|
66
103
|
"""The plan of the last ``stack apply``, if that apply passed."""
|
|
67
104
|
return stack_run.accepted()
|
|
@@ -275,6 +312,18 @@ def print_report(report: UpReport, out: Out = print) -> int:
|
|
|
275
312
|
|
|
276
313
|
|
|
277
314
|
def cli(args: argparse.Namespace) -> int:
|
|
315
|
+
if not args.json:
|
|
316
|
+
return _cli(args)
|
|
317
|
+
plan_id: list[str] = []
|
|
318
|
+
try:
|
|
319
|
+
return _cli(args, plan_id.append)
|
|
320
|
+
except (StackError, PlanError, OSError, ValueError, KeyError) as exc:
|
|
321
|
+
print(json.dumps(refusal(exc, plan_id[-1] if plan_id else ""), indent=1))
|
|
322
|
+
print(f"stack: {exc}", file=sys.stderr)
|
|
323
|
+
return 2
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _cli(args: argparse.Namespace, chosen: Callable[[str], None] = lambda _id: None) -> int:
|
|
278
327
|
if args.plan is None:
|
|
279
328
|
plan = stack_run.accepted()
|
|
280
329
|
if plan is None:
|
|
@@ -290,6 +339,7 @@ def cli(args: argparse.Namespace) -> int:
|
|
|
290
339
|
f"plan {saved['plan_id'][:12]} has no stack apply record that passed full acceptance; "
|
|
291
340
|
f"run {command()} stack apply first"
|
|
292
341
|
)
|
|
342
|
+
chosen(plan["plan_id"])
|
|
293
343
|
report = up(
|
|
294
344
|
plan,
|
|
295
345
|
share_gpu=args.share_gpu,
|
|
@@ -12,7 +12,10 @@ the server:
|
|
|
12
12
|
2. The serve profile ``stack plan`` wrote names paths under ``~`` when the stack uses its
|
|
13
13
|
default directory, and PolyStrata takes them literally, so a copy with every such path
|
|
14
14
|
expanded (``strata-profile.resolved.json``) is what the server reads.
|
|
15
|
-
3. ``
|
|
15
|
+
3. Under Windows that copy's ``--vram-reserve-mib`` is read off the card as it is now
|
|
16
|
+
(``for_windows``): the engine sizes its VRAM from CUDA's free memory, which under WDDM does
|
|
17
|
+
not count other programs.
|
|
18
|
+
4. ``serve/server.py --engine strata --config <resolved profile>`` runs inside this process
|
|
16
19
|
(``runpy``), so the unit's signals and exit status are the server's while the command line
|
|
17
20
|
stays the one the deployment records: service discovery tells this tool's own engine from
|
|
18
21
|
someone else's by matching a GPU process's ancestors against that recorded command.
|
|
@@ -28,6 +31,7 @@ import shutil
|
|
|
28
31
|
import subprocess
|
|
29
32
|
import sys
|
|
30
33
|
from pathlib import Path
|
|
34
|
+
from typing import cast
|
|
31
35
|
|
|
32
36
|
|
|
33
37
|
def source_root(engine_dir: Path) -> Path:
|
|
@@ -97,12 +101,145 @@ def planning_home(profile: dict[str, object], deploy_dir: Path) -> str:
|
|
|
97
101
|
return os.path.expanduser("~")
|
|
98
102
|
|
|
99
103
|
|
|
104
|
+
RESERVE_FLAG = "--vram-reserve-mib"
|
|
105
|
+
BEFORE_CACHE_KEY = "vram_before_cache_mib"
|
|
106
|
+
WINDOWS = os.name == "nt"
|
|
107
|
+
|
|
108
|
+
# Run in a child Python so no CUDA context outlives it in the server's process; argv: the planned
|
|
109
|
+
# reserve and the VRAM the engine takes before its cache, in MiB. On the engine's card (CUDA
|
|
110
|
+
# device 0 under the unit's CUDA_VISIBLE_DEVICES) it reads NVML's free memory, which counts every
|
|
111
|
+
# process, then allocates as the engine does and prints the free memory CUDA reports to a process
|
|
112
|
+
# holding the second figure, or, when that is 0, holding all the engine may take (the card's free
|
|
113
|
+
# less the planned reserve).
|
|
114
|
+
CARD_PROBE = r"""
|
|
115
|
+
import ctypes, json, os, sys, time
|
|
116
|
+
planned, before = int(sys.argv[1]), int(sys.argv[2])
|
|
117
|
+
nvml = None
|
|
118
|
+
for name in ("nvml.dll", os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"),
|
|
119
|
+
"NVIDIA Corporation", "NVSMI", "nvml.dll")):
|
|
120
|
+
try:
|
|
121
|
+
nvml = ctypes.WinDLL(name)
|
|
122
|
+
break
|
|
123
|
+
except OSError:
|
|
124
|
+
pass
|
|
125
|
+
cuda = ctypes.WinDLL("nvcuda.dll")
|
|
126
|
+
dev, ctx, uuid = ctypes.c_int(), ctypes.c_void_p(), (ctypes.c_ubyte * 16)()
|
|
127
|
+
assert cuda.cuInit(0) == 0 and cuda.cuDeviceGet(ctypes.byref(dev), 0) == 0
|
|
128
|
+
assert cuda.cuDeviceGetUuid_v2(uuid, dev) == 0
|
|
129
|
+
b = bytes(uuid)
|
|
130
|
+
name = "GPU-%s-%s-%s-%s-%s" % (b[:4].hex(), b[4:6].hex(), b[6:8].hex(), b[8:10].hex(), b[10:].hex())
|
|
131
|
+
class Mem(ctypes.Structure):
|
|
132
|
+
_fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]
|
|
133
|
+
mem, card = Mem(), ctypes.c_void_p()
|
|
134
|
+
assert nvml.nvmlInit_v2() == 0
|
|
135
|
+
assert nvml.nvmlDeviceGetHandleByUUID(name.encode(), ctypes.byref(card)) == 0
|
|
136
|
+
assert nvml.nvmlDeviceGetMemoryInfo(card, ctypes.byref(mem)) == 0
|
|
137
|
+
nvml.nvmlShutdown()
|
|
138
|
+
target = (mem.free >> 20) - planned
|
|
139
|
+
assert cuda.cuDevicePrimaryCtxRetain(ctypes.byref(ctx), dev) == 0
|
|
140
|
+
out, chunks = {"card_free_mib": mem.free >> 20}, []
|
|
141
|
+
def hold(mib):
|
|
142
|
+
held = 256 * len(chunks)
|
|
143
|
+
while held + 256 <= mib:
|
|
144
|
+
ptr = ctypes.c_uint64()
|
|
145
|
+
if cuda.cuMemAlloc_v2(ctypes.byref(ptr), ctypes.c_size_t(256 << 20)) != 0:
|
|
146
|
+
break
|
|
147
|
+
chunks.append(ptr)
|
|
148
|
+
assert cuda.cuMemsetD8_v2(ptr, ctypes.c_ubyte(0), ctypes.c_size_t(256 << 20)) == 0
|
|
149
|
+
held += 256
|
|
150
|
+
assert cuda.cuCtxSynchronize() == 0
|
|
151
|
+
time.sleep(1.0)
|
|
152
|
+
free, total = ctypes.c_size_t(), ctypes.c_size_t()
|
|
153
|
+
assert cuda.cuMemGetInfo_v2(ctypes.byref(free), ctypes.byref(total)) == 0
|
|
154
|
+
return held, free.value >> 20
|
|
155
|
+
try:
|
|
156
|
+
assert cuda.cuCtxSetCurrent(ctx) == 0
|
|
157
|
+
if 0 < before < target:
|
|
158
|
+
out["before_held_mib"], out["before_cuda_free_mib"] = hold(before)
|
|
159
|
+
else:
|
|
160
|
+
out["held_mib"], out["cuda_free_mib"] = hold(target)
|
|
161
|
+
finally:
|
|
162
|
+
for ptr in chunks:
|
|
163
|
+
cuda.cuMemFree_v2(ptr)
|
|
164
|
+
cuda.cuDevicePrimaryCtxRelease(dev)
|
|
165
|
+
print(json.dumps(out))
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def windows_reserve_mib(planned: int, before: int) -> int:
|
|
170
|
+
"""``--vram-reserve-mib`` for strata-poly under Windows, so that the engine takes what the
|
|
171
|
+
card has free less ``planned``, ``before`` being the VRAM it takes ahead of its cache.
|
|
172
|
+
|
|
173
|
+
The engine fills its cache (or its ``--vram-pool``) to what CUDA reports free less the
|
|
174
|
+
reserve. Under WDDM that figure is the process's budget less its own use, not the card's
|
|
175
|
+
free memory: on homewin's RTX 4060 Ti 16 GB (2026-12-02) a process holding nothing was told
|
|
176
|
+
15,223 MiB both idle and with another program holding 8,000 MiB (NVML: 14,804 and 6,685).
|
|
177
|
+
With such a program there the budget also shrinks once the process holds about 2.5 GiB, by
|
|
178
|
+
about a MiB for each MiB more, until Windows moves one of them to system memory (decoding
|
|
179
|
+
then fell to about 5 tokens/s). So the reserve is read off that budget: what CUDA reports to
|
|
180
|
+
a process holding ``before`` (what the engine sees when it fills its cache), less the cache
|
|
181
|
+
it may have. Without ``before`` it is what CUDA reports to a process holding all the engine
|
|
182
|
+
may take, which leaves the engine ``before`` over. On a card nothing else uses, the reserve
|
|
183
|
+
stays ``planned`` (homewin: 643 MiB computed, 1,280 kept). ``planned`` also when the card
|
|
184
|
+
cannot be read: the plan's reserve stands."""
|
|
185
|
+
try:
|
|
186
|
+
done = subprocess.run(
|
|
187
|
+
[sys.executable, "-I", "-c", CARD_PROBE, str(planned), str(before)],
|
|
188
|
+
capture_output=True,
|
|
189
|
+
text=True,
|
|
190
|
+
timeout=120,
|
|
191
|
+
check=False,
|
|
192
|
+
)
|
|
193
|
+
views = json.loads(done.stdout.strip().splitlines()[-1])
|
|
194
|
+
target = int(views["card_free_mib"]) - planned
|
|
195
|
+
if "before_cuda_free_mib" in views:
|
|
196
|
+
fill = int(views["before_cuda_free_mib"]) - (target - int(views["before_held_mib"]))
|
|
197
|
+
else:
|
|
198
|
+
fill = int(views["cuda_free_mib"])
|
|
199
|
+
reserve = max(planned, fill)
|
|
200
|
+
except (OSError, subprocess.SubprocessError, ValueError, LookupError, TypeError):
|
|
201
|
+
print(
|
|
202
|
+
"strata_poly_server: could not read the card's free VRAM; keeping the planned "
|
|
203
|
+
f"{RESERVE_FLAG} {planned}",
|
|
204
|
+
file=sys.stderr,
|
|
205
|
+
)
|
|
206
|
+
return planned
|
|
207
|
+
held = views.get("before_held_mib", views.get("held_mib"))
|
|
208
|
+
cuda_free = views.get("before_cuda_free_mib", views.get("cuda_free_mib"))
|
|
209
|
+
print(
|
|
210
|
+
f"strata_poly_server: the card has {views['card_free_mib']} MiB free; CUDA reports "
|
|
211
|
+
f"{cuda_free} MiB free holding {held}; {RESERVE_FLAG} {planned} -> {reserve}",
|
|
212
|
+
file=sys.stderr,
|
|
213
|
+
)
|
|
214
|
+
return reserve
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def for_windows(profile: dict[str, object]) -> dict[str, object]:
|
|
218
|
+
"""``profile`` with the reserve ``windows_reserve_mib`` gives (when it has a numeric one)."""
|
|
219
|
+
args = profile.get("args")
|
|
220
|
+
if not isinstance(args, list) or RESERVE_FLAG not in args[:-1]:
|
|
221
|
+
return profile
|
|
222
|
+
at = args.index(RESERVE_FLAG) + 1
|
|
223
|
+
try:
|
|
224
|
+
planned = int(str(args[at]))
|
|
225
|
+
except ValueError:
|
|
226
|
+
return profile
|
|
227
|
+
before = profile.get(BEFORE_CACHE_KEY)
|
|
228
|
+
reserve = windows_reserve_mib(planned, before if isinstance(before, int) else 0)
|
|
229
|
+
return {**profile, "args": [*args[:at], str(reserve), *args[at + 1 :]]}
|
|
230
|
+
|
|
231
|
+
|
|
100
232
|
def resolve(config: Path) -> Path:
|
|
101
|
-
"""Write the profile with its home-relative paths expanded beside it
|
|
233
|
+
"""Write the profile with its home-relative paths expanded beside it, and under Windows its
|
|
234
|
+
reserve raised by what other programs hold on the card; returns that file."""
|
|
102
235
|
resolved = config.with_name(config.stem + ".resolved.json")
|
|
103
236
|
profile = json.loads(config.read_text(encoding="utf-8"))
|
|
104
237
|
home = planning_home(profile, config.parent.resolve())
|
|
105
|
-
|
|
238
|
+
profile = cast("dict[str, object]", _expanded(profile, home))
|
|
239
|
+
if WINDOWS:
|
|
240
|
+
profile = for_windows(profile)
|
|
241
|
+
profile.pop(BEFORE_CACHE_KEY, None) # this launcher's, not PolyStrata's
|
|
242
|
+
resolved.write_text(json.dumps(profile, indent=1) + "\n", encoding="utf-8")
|
|
106
243
|
return resolved
|
|
107
244
|
|
|
108
245
|
|