@simplexai/localmodels-win32-x64 0.1.0-dev.101 → 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 +56 -37
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +3 -1
- package/modules/localmodels/app.py +35 -7
- 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/engine_adapters/suite_plan.py +4 -2
- 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_capacity.py +37 -1
- package/modules/localmodels/stack_cli.py +1 -0
- package/modules/localmodels/stack_down.py +19 -14
- package/modules/localmodels/stack_hardware.py +18 -16
- package/modules/localmodels/stack_plan.py +21 -0
- package/modules/localmodels/stack_ports.py +1 -0
- package/modules/localmodels/stack_progress.py +15 -0
- package/modules/localmodels/stack_run.py +25 -2
- package/modules/localmodels/stack_suite.py +54 -12
- package/modules/localmodels/stack_up.py +51 -1
- package/modules/localmodels/strata_poly_server.py +140 -3
- package/modules/localmodels/suite.py +10 -1
- 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.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/RECORD +53 -34
- package/modules/{simplex_localmodels-0.1.0.dev101.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.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,750 @@
|
|
|
1
|
+
"""Standby-first local TTS sidecar controller (``RANK = 3``).
|
|
2
|
+
|
|
3
|
+
Supervises one isolated child TTS worker with single-loader mutual exclusion, idle TTL eviction,
|
|
4
|
+
crash-loop latching, GPU OOM fallback, and reverse CPU demotion for LLM (RANK 0) and STT (RANK 2).
|
|
5
|
+
Legacy ``localmodels/tts_server.py`` (used by ``stack plan --tts``) remains untouched.
|
|
6
|
+
Privacy invariant: never log synthesis input text, instructions, or audio payloads.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import functools
|
|
13
|
+
import os
|
|
14
|
+
import subprocess
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Callable, Iterator
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Literal
|
|
20
|
+
|
|
21
|
+
from localmodels import (
|
|
22
|
+
debug_mode,
|
|
23
|
+
process_identity,
|
|
24
|
+
sidecar_http,
|
|
25
|
+
tts_admission,
|
|
26
|
+
tts_catalog,
|
|
27
|
+
tts_http,
|
|
28
|
+
tts_model,
|
|
29
|
+
tts_state,
|
|
30
|
+
tts_workers,
|
|
31
|
+
)
|
|
32
|
+
from localmodels.tts_admission import TtsDeviceDecision
|
|
33
|
+
from localmodels.tts_catalog import TtsModelSpec
|
|
34
|
+
from localmodels.tts_http import make_handler as make_handler
|
|
35
|
+
from localmodels.tts_http import start_http_server as start_http_server
|
|
36
|
+
from localmodels.tts_model import (
|
|
37
|
+
DETAIL_LIMIT,
|
|
38
|
+
EffectiveDevice,
|
|
39
|
+
FallbackReason,
|
|
40
|
+
TtsError,
|
|
41
|
+
TtsRuntime,
|
|
42
|
+
)
|
|
43
|
+
from localmodels.tts_workers import TtsSynthRequest, TtsSynthResult, TtsWorkerError, TtsWorkerHandle
|
|
44
|
+
|
|
45
|
+
DEMOTE_WAIT_S = 3.0
|
|
46
|
+
DEFAULT_SWEEP_INTERVAL_S = 5.0
|
|
47
|
+
CRASH_LATCH_COUNT = 2
|
|
48
|
+
CRASH_WINDOW_S = 120.0
|
|
49
|
+
_GPU_DEVICES = frozenset(("cuda", "metal", "vulkan", "directml"))
|
|
50
|
+
|
|
51
|
+
TtsDeviceDecider = Callable[[TtsModelSpec, bool], TtsDeviceDecision]
|
|
52
|
+
_WorkerTarget = tuple[str, str]
|
|
53
|
+
_CrashStreak = tts_http.CrashStreak
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _exit_after_fail(worker: TtsWorkerHandle, wait_s: float = 0.5) -> int | None:
|
|
57
|
+
try:
|
|
58
|
+
return worker.proc.wait(timeout=wait_s)
|
|
59
|
+
except subprocess.TimeoutExpired:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class TtsSidecar:
|
|
64
|
+
"""Thread-safe standby-first TTS controller supervising one isolated child worker."""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
base_dir: str,
|
|
69
|
+
*,
|
|
70
|
+
base_url: str,
|
|
71
|
+
key_file: Path,
|
|
72
|
+
state_dir: Path | None = None,
|
|
73
|
+
worker_factory: tts_workers.TtsWorkerFactory | None = None,
|
|
74
|
+
device_decider: TtsDeviceDecider | None = None,
|
|
75
|
+
clock: Callable[[], float] | None = None,
|
|
76
|
+
sweep_interval_s: float = DEFAULT_SWEEP_INTERVAL_S,
|
|
77
|
+
stop_grace_s: float = sidecar_http.WORKER_STOP_GRACE_S,
|
|
78
|
+
) -> None:
|
|
79
|
+
self.base_dir = base_dir
|
|
80
|
+
self.base_url = base_url.rstrip("/")
|
|
81
|
+
self.key_file = key_file
|
|
82
|
+
self.state_dir = state_dir
|
|
83
|
+
is_sim = debug_mode.current().mode == "simulate"
|
|
84
|
+
self._worker_factory: tts_workers.TtsWorkerFactory = worker_factory or (
|
|
85
|
+
tts_workers.spawn_simulated_worker if is_sim else tts_workers.spawn_real_worker
|
|
86
|
+
)
|
|
87
|
+
self._device_decider: TtsDeviceDecider = device_decider or (
|
|
88
|
+
tts_workers.decide_simulated_device
|
|
89
|
+
if is_sim
|
|
90
|
+
else functools.partial(tts_admission.decide_tts_device, state_dir=state_dir)
|
|
91
|
+
)
|
|
92
|
+
self._clock: Callable[[], float] = clock or time.time
|
|
93
|
+
self._sweep_interval_s = max(0.02, float(sweep_interval_s))
|
|
94
|
+
self._stop_grace_s = max(0.1, float(stop_grace_s))
|
|
95
|
+
self._identity = process_identity.inspect(os.getpid())
|
|
96
|
+
|
|
97
|
+
self._cond = threading.Condition(threading.RLock())
|
|
98
|
+
self._config: tts_model.TtsConfig = tts_state.load_config(state_dir)
|
|
99
|
+
self._state: tts_model.TtsRuntimeState = "standby"
|
|
100
|
+
self._worker: TtsWorkerHandle | None = None
|
|
101
|
+
self._loading = False
|
|
102
|
+
self._load_generation = 0
|
|
103
|
+
self._loading_spec: TtsModelSpec | None = None
|
|
104
|
+
self._loading_decision: TtsDeviceDecision | None = None
|
|
105
|
+
self._pending_demote: tuple[FallbackReason, str | None] | None = None
|
|
106
|
+
self._demoted_target: tuple[str, FallbackReason, dict[str, object]] | None = None
|
|
107
|
+
self._active_sessions = 0
|
|
108
|
+
self._last_used = self._clock()
|
|
109
|
+
self._last_fallback_reason: FallbackReason | None = None
|
|
110
|
+
self._last_fallback_detail: dict[str, object] | None = None
|
|
111
|
+
self._last_error: tts_model.TtsModelError | None = None
|
|
112
|
+
self._crash_streak: _CrashStreak | None = None
|
|
113
|
+
self._latched_target: _WorkerTarget | None = None
|
|
114
|
+
self._stop_event = threading.Event()
|
|
115
|
+
self._sweeper: threading.Thread | None = None
|
|
116
|
+
|
|
117
|
+
def start_sweeper(self) -> None:
|
|
118
|
+
if self._sweeper is not None:
|
|
119
|
+
return
|
|
120
|
+
self._stop_event.clear()
|
|
121
|
+
self._sweeper = threading.Thread(target=self._sweep_loop, name="tts-sweeper", daemon=True)
|
|
122
|
+
self._sweeper.start()
|
|
123
|
+
|
|
124
|
+
def _sweep_loop(self) -> None:
|
|
125
|
+
while True:
|
|
126
|
+
with self._cond:
|
|
127
|
+
wait_s = sidecar_http.sweep_wait_seconds(
|
|
128
|
+
self._config["keep_loaded_seconds"], self._sweep_interval_s
|
|
129
|
+
)
|
|
130
|
+
if self._stop_event.wait(wait_s):
|
|
131
|
+
return
|
|
132
|
+
with contextlib.suppress(Exception):
|
|
133
|
+
self.sweep_once()
|
|
134
|
+
|
|
135
|
+
def _idle_remaining_locked(self) -> int | None:
|
|
136
|
+
return sidecar_http.idle_remaining_seconds(
|
|
137
|
+
loaded=self._state == "loaded" and self._worker is not None,
|
|
138
|
+
ttl=self._config["keep_loaded_seconds"],
|
|
139
|
+
active_sessions=self._active_sessions,
|
|
140
|
+
now=self._clock(),
|
|
141
|
+
last_used=self._last_used,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
def _active_meta_locked(
|
|
145
|
+
self,
|
|
146
|
+
) -> tuple[str | None, str | None, TtsDeviceDecision | None, int, int]:
|
|
147
|
+
w = self._worker
|
|
148
|
+
if w is not None:
|
|
149
|
+
vram = w.vram_estimate_bytes if w.decision.effective_device in _GPU_DEVICES else 0
|
|
150
|
+
return w.model_id, w.engine, w.decision, vram, w.ram_estimate_bytes
|
|
151
|
+
if self._loading and self._loading_spec is not None and self._loading_decision is not None:
|
|
152
|
+
spec, dec = self._loading_spec, self._loading_decision
|
|
153
|
+
vram = spec.vram_estimate_bytes if dec.effective_device in _GPU_DEVICES else 0
|
|
154
|
+
return spec.id, spec.engine, dec, vram, spec.ram_estimate_bytes
|
|
155
|
+
return None, None, None, 0, 0
|
|
156
|
+
|
|
157
|
+
def health_payload(self) -> dict[str, object]:
|
|
158
|
+
with self._cond:
|
|
159
|
+
mid, _eng, dec, _vram, _ram = self._active_meta_locked()
|
|
160
|
+
return {
|
|
161
|
+
"status": "ok",
|
|
162
|
+
"state": self._state,
|
|
163
|
+
"active_model": mid,
|
|
164
|
+
"effective_device": dec.effective_device if dec is not None else None,
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
def runtime_payload(self) -> TtsRuntime:
|
|
168
|
+
with self._cond:
|
|
169
|
+
return tts_http.build_runtime_payload(
|
|
170
|
+
state=self._state,
|
|
171
|
+
base_url=self.base_url,
|
|
172
|
+
key_file=self.key_file,
|
|
173
|
+
config=self._config,
|
|
174
|
+
meta=self._active_meta_locked(),
|
|
175
|
+
last_fallback=(self._last_fallback_reason, self._last_fallback_detail),
|
|
176
|
+
idle_remaining=self._idle_remaining_locked(),
|
|
177
|
+
active_sessions=self._active_sessions,
|
|
178
|
+
last_error=self._last_error,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def persist_runtime(self) -> None:
|
|
182
|
+
with self._cond:
|
|
183
|
+
rt = self.runtime_payload()
|
|
184
|
+
_mid, _eng, dec, _vram, _ram = self._active_meta_locked()
|
|
185
|
+
record: dict[str, Any] = {
|
|
186
|
+
**rt,
|
|
187
|
+
"pid": os.getpid(),
|
|
188
|
+
"process_identity": self._identity,
|
|
189
|
+
"pool": dec.pool if dec is not None else None,
|
|
190
|
+
}
|
|
191
|
+
tts_state.save_runtime_record(record, self.state_dir)
|
|
192
|
+
|
|
193
|
+
def _wait_idle_locked(self, timeout_s: float = DEMOTE_WAIT_S) -> None:
|
|
194
|
+
tts_http.wait_until(self._cond, lambda: self._active_sessions == 0, timeout_s)
|
|
195
|
+
|
|
196
|
+
def _wait_not_loading_locked(self, timeout_s: float | None = None) -> bool:
|
|
197
|
+
return tts_http.wait_until(self._cond, lambda: not self._loading, timeout_s)
|
|
198
|
+
|
|
199
|
+
def _stop_worker_locked(self, *, keep_fallback: bool = False) -> None:
|
|
200
|
+
old, self._worker, self._state = self._worker, None, "standby"
|
|
201
|
+
if not keep_fallback:
|
|
202
|
+
self._last_fallback_reason, self._last_fallback_detail = None, None
|
|
203
|
+
if old is not None:
|
|
204
|
+
old.stop(grace_s=self._stop_grace_s)
|
|
205
|
+
|
|
206
|
+
def _clear_failure_locked(self) -> None:
|
|
207
|
+
self._last_error, self._crash_streak, self._latched_target = None, None, None
|
|
208
|
+
if self._state == "error" and self._worker is None:
|
|
209
|
+
self._state = "standby"
|
|
210
|
+
|
|
211
|
+
def _record_crash_locked(
|
|
212
|
+
self, target: _WorkerTarget, exc: TtsWorkerError, exit_status: int | None
|
|
213
|
+
) -> TtsWorkerError:
|
|
214
|
+
tail = sidecar_http.stderr_tail(exc.detail, DETAIL_LIMIT)
|
|
215
|
+
if exit_status is not None:
|
|
216
|
+
streak, latched, msg = tts_http.next_crash_streak(
|
|
217
|
+
self._crash_streak,
|
|
218
|
+
target,
|
|
219
|
+
exit_status,
|
|
220
|
+
self._clock(),
|
|
221
|
+
window_s=CRASH_WINDOW_S,
|
|
222
|
+
latch_count=CRASH_LATCH_COUNT,
|
|
223
|
+
tail=tail,
|
|
224
|
+
exc_text=str(exc),
|
|
225
|
+
)
|
|
226
|
+
self._crash_streak = streak
|
|
227
|
+
if latched:
|
|
228
|
+
self._latched_target = target
|
|
229
|
+
else:
|
|
230
|
+
msg = (f"{target[0]}: {exc}" + (f": {tail}" if tail and tail != str(exc) else ""))[
|
|
231
|
+
-DETAIL_LIMIT:
|
|
232
|
+
]
|
|
233
|
+
self._state = "error"
|
|
234
|
+
self._last_error = {"code": "RUNTIME_ERROR", "message": msg}
|
|
235
|
+
return TtsWorkerError(msg, detail=exc.detail)
|
|
236
|
+
|
|
237
|
+
def _record_load_error_locked(
|
|
238
|
+
self, target: _WorkerTarget, spawn_exc: Exception | None
|
|
239
|
+
) -> Exception:
|
|
240
|
+
if isinstance(spawn_exc, TtsWorkerError):
|
|
241
|
+
wrapped = self._record_crash_locked(target, spawn_exc, spawn_exc.exit_status)
|
|
242
|
+
return TtsError("RUNTIME_ERROR", str(wrapped), failed=True)
|
|
243
|
+
self._state = "error"
|
|
244
|
+
code = spawn_exc.code if isinstance(spawn_exc, TtsError) else "RUNTIME_ERROR"
|
|
245
|
+
msg = (
|
|
246
|
+
spawn_exc.message
|
|
247
|
+
if isinstance(spawn_exc, TtsError)
|
|
248
|
+
else (str(spawn_exc) if spawn_exc else "tts worker failed to start")
|
|
249
|
+
)
|
|
250
|
+
self._last_error = {"code": code, "message": msg[-DETAIL_LIMIT:]}
|
|
251
|
+
return spawn_exc or TtsError("RUNTIME_ERROR", msg, failed=True)
|
|
252
|
+
|
|
253
|
+
def _spawn_with_fallback(
|
|
254
|
+
self, spec: TtsModelSpec, decision: TtsDeviceDecision
|
|
255
|
+
) -> TtsWorkerHandle:
|
|
256
|
+
try:
|
|
257
|
+
return self._worker_factory(spec, decision, self.base_dir, self.state_dir)
|
|
258
|
+
except TtsWorkerError as exc:
|
|
259
|
+
if decision.effective_device == "cpu":
|
|
260
|
+
raise
|
|
261
|
+
detail: dict[str, object] = {
|
|
262
|
+
"failed_device": decision.effective_device,
|
|
263
|
+
"detail": str(exc)[-240:],
|
|
264
|
+
}
|
|
265
|
+
cpu_dec = tts_http.cpu_fallback_decision(
|
|
266
|
+
decision.requested_device, "gpu_init_failed", detail
|
|
267
|
+
)
|
|
268
|
+
return self._worker_factory(spec, cpu_dec, self.base_dir, self.state_dir)
|
|
269
|
+
|
|
270
|
+
def _prepare_load_locked(
|
|
271
|
+
self,
|
|
272
|
+
model_id: str | None,
|
|
273
|
+
use_gpu: bool | None,
|
|
274
|
+
*,
|
|
275
|
+
explicit_load: bool,
|
|
276
|
+
claim_session: bool,
|
|
277
|
+
) -> tuple[
|
|
278
|
+
TtsWorkerHandle | None, TtsModelSpec | None, TtsDeviceDecision | None, _WorkerTarget, int
|
|
279
|
+
]:
|
|
280
|
+
while True:
|
|
281
|
+
self._wait_not_loading_locked()
|
|
282
|
+
if self._stop_event.is_set():
|
|
283
|
+
raise TtsError("RUNTIME_ERROR", "tts sidecar is shutting down", failed=True)
|
|
284
|
+
target_id = model_id or self._config["model_id"]
|
|
285
|
+
want_gpu = self._config["use_gpu"] if use_gpu is None else use_gpu
|
|
286
|
+
try:
|
|
287
|
+
spec = tts_catalog.tts_model(target_id)
|
|
288
|
+
except KeyError:
|
|
289
|
+
raise TtsError("MODEL_UNKNOWN", f"unknown tts model: {target_id}") from None
|
|
290
|
+
req_dev: tts_model.RequestedDevice = "gpu" if want_gpu else "cpu"
|
|
291
|
+
target: _WorkerTarget = (spec.id, req_dev)
|
|
292
|
+
if explicit_load:
|
|
293
|
+
self._clear_failure_locked()
|
|
294
|
+
self._demoted_target = None
|
|
295
|
+
elif self._latched_target == target and self._last_error is not None:
|
|
296
|
+
raise TtsError("RUNTIME_ERROR", self._last_error["message"], failed=True)
|
|
297
|
+
|
|
298
|
+
cur = self._worker
|
|
299
|
+
if (
|
|
300
|
+
cur is not None
|
|
301
|
+
and cur.is_alive()
|
|
302
|
+
and cur.model_id == spec.id
|
|
303
|
+
and cur.decision.requested_device == req_dev
|
|
304
|
+
):
|
|
305
|
+
self._last_used = self._clock()
|
|
306
|
+
if claim_session:
|
|
307
|
+
self._active_sessions += 1
|
|
308
|
+
self.persist_runtime()
|
|
309
|
+
return cur, None, None, target, self._load_generation
|
|
310
|
+
|
|
311
|
+
if cur is not None:
|
|
312
|
+
if self._active_sessions > 0:
|
|
313
|
+
self._wait_idle_locked()
|
|
314
|
+
continue
|
|
315
|
+
self._stop_worker_locked()
|
|
316
|
+
break
|
|
317
|
+
|
|
318
|
+
demoted = self._demoted_target
|
|
319
|
+
if not explicit_load and want_gpu and demoted is not None and demoted[0] == spec.id:
|
|
320
|
+
decision = tts_http.cpu_fallback_decision("gpu", demoted[1], dict(demoted[2]))
|
|
321
|
+
else:
|
|
322
|
+
decision = self._device_decider(spec, want_gpu)
|
|
323
|
+
self._loading, self._state = True, "loading"
|
|
324
|
+
self._loading_spec, self._loading_decision, self._pending_demote = spec, decision, None
|
|
325
|
+
load_gen = self._load_generation
|
|
326
|
+
self.persist_runtime()
|
|
327
|
+
return None, spec, decision, target, load_gen
|
|
328
|
+
|
|
329
|
+
def _record_demote_locked(
|
|
330
|
+
self, model_id: str, decision: TtsDeviceDecision, reason: FallbackReason
|
|
331
|
+
) -> None:
|
|
332
|
+
detail: dict[str, object] = {
|
|
333
|
+
"previous_device": decision.effective_device,
|
|
334
|
+
"pool": decision.pool,
|
|
335
|
+
}
|
|
336
|
+
self._demoted_target = (model_id, reason, detail)
|
|
337
|
+
self._last_fallback_reason, self._last_fallback_detail = reason, detail
|
|
338
|
+
|
|
339
|
+
def _matches_demote_pool(self, decision: TtsDeviceDecision, pool: str | None) -> bool:
|
|
340
|
+
return decision.effective_device in _GPU_DEVICES and (
|
|
341
|
+
not pool or not decision.pool or decision.pool == pool
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
def _finish_load_locked(
|
|
345
|
+
self,
|
|
346
|
+
target: _WorkerTarget,
|
|
347
|
+
load_gen: int,
|
|
348
|
+
worker: TtsWorkerHandle | None,
|
|
349
|
+
spawn_exc: Exception | None,
|
|
350
|
+
*,
|
|
351
|
+
claim_session: bool,
|
|
352
|
+
) -> TtsWorkerHandle:
|
|
353
|
+
self._loading = False
|
|
354
|
+
self._loading_spec, self._loading_decision, self._pending_demote = None, None, None
|
|
355
|
+
|
|
356
|
+
if self._stop_event.is_set():
|
|
357
|
+
if worker is not None:
|
|
358
|
+
worker.stop(grace_s=self._stop_grace_s)
|
|
359
|
+
self._state = "stopped"
|
|
360
|
+
self._cond.notify_all()
|
|
361
|
+
raise TtsError("RUNTIME_ERROR", "tts sidecar is shutting down", failed=True)
|
|
362
|
+
|
|
363
|
+
if self._load_generation != load_gen:
|
|
364
|
+
if worker is not None:
|
|
365
|
+
worker.stop(grace_s=self._stop_grace_s)
|
|
366
|
+
if self._worker is None:
|
|
367
|
+
self._state = "standby"
|
|
368
|
+
self.persist_runtime()
|
|
369
|
+
self._cond.notify_all()
|
|
370
|
+
raise TtsError("RUNTIME_ERROR", "tts model load superseded", failed=True)
|
|
371
|
+
|
|
372
|
+
if spawn_exc is not None or worker is None:
|
|
373
|
+
self._worker = None
|
|
374
|
+
err = self._record_load_error_locked(target, spawn_exc)
|
|
375
|
+
self.persist_runtime()
|
|
376
|
+
self._cond.notify_all()
|
|
377
|
+
raise err from None
|
|
378
|
+
|
|
379
|
+
if self._worker is not None and self._worker is not worker:
|
|
380
|
+
self._worker.stop(grace_s=self._stop_grace_s)
|
|
381
|
+
self._worker, self._state, self._last_used = worker, "loaded", self._clock()
|
|
382
|
+
self._last_fallback_reason = worker.decision.fallback_reason
|
|
383
|
+
self._last_fallback_detail = (
|
|
384
|
+
dict(worker.decision.fallback_detail) if worker.decision.fallback_detail else None
|
|
385
|
+
)
|
|
386
|
+
self._latched_target, self._last_error = None, None
|
|
387
|
+
if claim_session:
|
|
388
|
+
self._active_sessions += 1
|
|
389
|
+
self.persist_runtime()
|
|
390
|
+
self._cond.notify_all()
|
|
391
|
+
return worker
|
|
392
|
+
|
|
393
|
+
def _ensure_worker(
|
|
394
|
+
self,
|
|
395
|
+
model_id: str | None = None,
|
|
396
|
+
*,
|
|
397
|
+
use_gpu: bool | None = None,
|
|
398
|
+
explicit_load: bool = False,
|
|
399
|
+
claim_session: bool = False,
|
|
400
|
+
) -> TtsWorkerHandle:
|
|
401
|
+
while True:
|
|
402
|
+
with self._cond:
|
|
403
|
+
existing, spec, decision, target, load_gen = self._prepare_load_locked(
|
|
404
|
+
model_id, use_gpu, explicit_load=explicit_load, claim_session=claim_session
|
|
405
|
+
)
|
|
406
|
+
if existing is not None:
|
|
407
|
+
return existing
|
|
408
|
+
assert spec is not None and decision is not None
|
|
409
|
+
spawn_exc: Exception | None = None
|
|
410
|
+
worker: TtsWorkerHandle | None = None
|
|
411
|
+
try:
|
|
412
|
+
worker = self._spawn_with_fallback(spec, decision)
|
|
413
|
+
except Exception as exc:
|
|
414
|
+
spawn_exc = exc
|
|
415
|
+
demote_worker: TtsWorkerHandle | None = None
|
|
416
|
+
with self._cond:
|
|
417
|
+
pending = self._pending_demote
|
|
418
|
+
if (
|
|
419
|
+
pending is not None
|
|
420
|
+
and worker is not None
|
|
421
|
+
and spawn_exc is None
|
|
422
|
+
and not self._stop_event.is_set()
|
|
423
|
+
and self._load_generation == load_gen
|
|
424
|
+
and self._matches_demote_pool(worker.decision, pending[1])
|
|
425
|
+
):
|
|
426
|
+
self._pending_demote = None
|
|
427
|
+
self._record_demote_locked(worker.model_id, worker.decision, pending[0])
|
|
428
|
+
demote_worker = worker
|
|
429
|
+
else:
|
|
430
|
+
return self._finish_load_locked(
|
|
431
|
+
target, load_gen, worker, spawn_exc, claim_session=claim_session
|
|
432
|
+
)
|
|
433
|
+
demote_worker.stop(grace_s=self._stop_grace_s)
|
|
434
|
+
with self._cond:
|
|
435
|
+
self._loading, self._loading_spec, self._loading_decision = False, None, None
|
|
436
|
+
self._state = "standby"
|
|
437
|
+
if not self._stop_event.is_set():
|
|
438
|
+
self.persist_runtime()
|
|
439
|
+
self._cond.notify_all()
|
|
440
|
+
explicit_load = False
|
|
441
|
+
|
|
442
|
+
def load_model(self, model_id: str | None = None, *, use_gpu: bool | None = None) -> TtsRuntime:
|
|
443
|
+
self._ensure_worker(model_id, use_gpu=use_gpu, explicit_load=True)
|
|
444
|
+
return self.runtime_payload()
|
|
445
|
+
|
|
446
|
+
def unload(self) -> TtsRuntime:
|
|
447
|
+
with self._cond:
|
|
448
|
+
self._load_generation += 1
|
|
449
|
+
self._demoted_target = None
|
|
450
|
+
if self._loading:
|
|
451
|
+
self._wait_not_loading_locked(DEMOTE_WAIT_S)
|
|
452
|
+
if self._loading:
|
|
453
|
+
self._clear_failure_locked()
|
|
454
|
+
return self.runtime_payload()
|
|
455
|
+
self._wait_idle_locked()
|
|
456
|
+
if self._stop_event.is_set():
|
|
457
|
+
return self.runtime_payload()
|
|
458
|
+
self._stop_worker_locked()
|
|
459
|
+
self._clear_failure_locked()
|
|
460
|
+
self.persist_runtime()
|
|
461
|
+
return self.runtime_payload()
|
|
462
|
+
|
|
463
|
+
def apply_config(self, raw_update: dict[str, object]) -> TtsRuntime:
|
|
464
|
+
with self._cond:
|
|
465
|
+
validated = tts_state.merge_config_update(self._config, raw_update)
|
|
466
|
+
prev = self._config
|
|
467
|
+
invalidates = (
|
|
468
|
+
prev["model_id"] != validated["model_id"] or prev["use_gpu"] != validated["use_gpu"]
|
|
469
|
+
)
|
|
470
|
+
unload_zero = validated["keep_loaded_seconds"] == 0
|
|
471
|
+
self._config = validated
|
|
472
|
+
tts_state.save_config(validated, self.state_dir)
|
|
473
|
+
if invalidates or unload_zero:
|
|
474
|
+
self._load_generation += 1
|
|
475
|
+
if invalidates:
|
|
476
|
+
self._demoted_target = None
|
|
477
|
+
if self._loading:
|
|
478
|
+
if invalidates or unload_zero:
|
|
479
|
+
self._wait_not_loading_locked(DEMOTE_WAIT_S)
|
|
480
|
+
if self._loading:
|
|
481
|
+
if invalidates:
|
|
482
|
+
self._clear_failure_locked()
|
|
483
|
+
if not self._stop_event.is_set():
|
|
484
|
+
self.persist_runtime()
|
|
485
|
+
return self.runtime_payload()
|
|
486
|
+
if invalidates:
|
|
487
|
+
self._clear_failure_locked()
|
|
488
|
+
if self._worker is not None:
|
|
489
|
+
self._wait_idle_locked()
|
|
490
|
+
if self._stop_event.is_set():
|
|
491
|
+
return self.runtime_payload()
|
|
492
|
+
self._stop_worker_locked()
|
|
493
|
+
elif self._worker is not None and unload_zero and self._active_sessions == 0:
|
|
494
|
+
self._stop_worker_locked()
|
|
495
|
+
if not self._stop_event.is_set():
|
|
496
|
+
self.persist_runtime()
|
|
497
|
+
return self.runtime_payload()
|
|
498
|
+
|
|
499
|
+
def demote_to_cpu(
|
|
500
|
+
self, *, reason: FallbackReason = "yielded_to_llm", pool: str | None = None
|
|
501
|
+
) -> TtsRuntime:
|
|
502
|
+
with self._cond:
|
|
503
|
+
if self._stop_event.is_set():
|
|
504
|
+
return self.runtime_payload()
|
|
505
|
+
if self._loading and self._loading_decision is not None:
|
|
506
|
+
if self._matches_demote_pool(self._loading_decision, pool):
|
|
507
|
+
self._pending_demote = (reason, pool)
|
|
508
|
+
self._wait_not_loading_locked(DEMOTE_WAIT_S)
|
|
509
|
+
return self.runtime_payload()
|
|
510
|
+
worker = self._worker
|
|
511
|
+
if worker is None or not self._matches_demote_pool(worker.decision, pool):
|
|
512
|
+
return self.runtime_payload()
|
|
513
|
+
self._wait_idle_locked(DEMOTE_WAIT_S)
|
|
514
|
+
if self._stop_event.is_set() or self._worker is not worker:
|
|
515
|
+
return self.runtime_payload()
|
|
516
|
+
self._worker, self._state = None, "standby"
|
|
517
|
+
self._record_demote_locked(worker.model_id, worker.decision, reason)
|
|
518
|
+
self._load_generation += 1
|
|
519
|
+
self._cond.notify_all()
|
|
520
|
+
worker.stop(grace_s=self._stop_grace_s)
|
|
521
|
+
with self._cond:
|
|
522
|
+
if not self._stop_event.is_set():
|
|
523
|
+
self.persist_runtime()
|
|
524
|
+
return self.runtime_payload()
|
|
525
|
+
|
|
526
|
+
def sweep_once(self) -> bool:
|
|
527
|
+
with self._cond:
|
|
528
|
+
if self._stop_event.is_set() or self._worker is None:
|
|
529
|
+
return False
|
|
530
|
+
if not self._worker.is_alive():
|
|
531
|
+
self._stop_worker_locked()
|
|
532
|
+
self.persist_runtime()
|
|
533
|
+
return True
|
|
534
|
+
ttl = self._config["keep_loaded_seconds"]
|
|
535
|
+
if ttl <= 0 or self._active_sessions > 0:
|
|
536
|
+
return False
|
|
537
|
+
if (self._clock() - self._last_used) >= ttl:
|
|
538
|
+
self._stop_worker_locked()
|
|
539
|
+
self.persist_runtime()
|
|
540
|
+
return True
|
|
541
|
+
return False
|
|
542
|
+
|
|
543
|
+
def voices(
|
|
544
|
+
self, model_id: str | None = None
|
|
545
|
+
) -> tuple[str, Literal["worker", "catalog"], list[tts_model.TtsVoiceInfo]]:
|
|
546
|
+
with self._cond:
|
|
547
|
+
target_id = model_id or self._config["model_id"]
|
|
548
|
+
worker = self._worker
|
|
549
|
+
use_live = worker is not None and worker.is_alive() and worker.model_id == target_id
|
|
550
|
+
if use_live and worker is not None:
|
|
551
|
+
try:
|
|
552
|
+
return (
|
|
553
|
+
target_id,
|
|
554
|
+
"worker",
|
|
555
|
+
tts_workers.get_backend(worker.engine).list_voices(worker),
|
|
556
|
+
)
|
|
557
|
+
except TtsWorkerError:
|
|
558
|
+
pass
|
|
559
|
+
try:
|
|
560
|
+
return target_id, "catalog", tts_catalog.static_voices(target_id)
|
|
561
|
+
except KeyError:
|
|
562
|
+
raise TtsError("MODEL_UNKNOWN", f"unknown tts model: {target_id}") from None
|
|
563
|
+
|
|
564
|
+
def _respawn_cpu_after_oom(self, worker: TtsWorkerHandle) -> TtsWorkerHandle:
|
|
565
|
+
with self._cond:
|
|
566
|
+
if self._stop_event.is_set():
|
|
567
|
+
raise TtsError("RUNTIME_ERROR", "tts sidecar is shutting down", failed=True)
|
|
568
|
+
if self._worker is not worker:
|
|
569
|
+
cur = self._worker
|
|
570
|
+
if (
|
|
571
|
+
cur is not None
|
|
572
|
+
and cur.is_alive()
|
|
573
|
+
and cur.model_id == worker.model_id
|
|
574
|
+
and cur.decision.effective_device == "cpu"
|
|
575
|
+
):
|
|
576
|
+
return cur
|
|
577
|
+
raise TtsError(
|
|
578
|
+
"RUNTIME_ERROR", "tts worker replaced during OOM recovery", failed=True
|
|
579
|
+
)
|
|
580
|
+
self._stop_worker_locked(keep_fallback=True)
|
|
581
|
+
spec = tts_catalog.tts_model(worker.model_id)
|
|
582
|
+
detail: dict[str, object] = {"failed_device": worker.decision.effective_device}
|
|
583
|
+
cpu_dec = tts_http.cpu_fallback_decision(
|
|
584
|
+
worker.decision.requested_device, "runtime_oom_fallback", detail
|
|
585
|
+
)
|
|
586
|
+
try:
|
|
587
|
+
new_worker = self._worker_factory(spec, cpu_dec, self.base_dir, self.state_dir)
|
|
588
|
+
except TtsWorkerError as cpu_exc:
|
|
589
|
+
wrapped = self._record_crash_locked(
|
|
590
|
+
(worker.model_id, worker.decision.requested_device),
|
|
591
|
+
cpu_exc,
|
|
592
|
+
cpu_exc.exit_status,
|
|
593
|
+
)
|
|
594
|
+
self.persist_runtime()
|
|
595
|
+
raise TtsError("RUNTIME_ERROR", str(wrapped), failed=True) from None
|
|
596
|
+
self._worker, self._state = new_worker, "loaded"
|
|
597
|
+
self._last_fallback_reason, self._last_fallback_detail = "runtime_oom_fallback", detail
|
|
598
|
+
self.persist_runtime()
|
|
599
|
+
return new_worker
|
|
600
|
+
|
|
601
|
+
def _handle_worker_failure(
|
|
602
|
+
self, worker: TtsWorkerHandle, exc: TtsWorkerError, *, allow_oom_fallback: bool = True
|
|
603
|
+
) -> TtsWorkerHandle | None:
|
|
604
|
+
"""Attempt OOM fallback on GPU workers, else record crash only if worker exited."""
|
|
605
|
+
if (
|
|
606
|
+
allow_oom_fallback
|
|
607
|
+
and worker.decision.effective_device in _GPU_DEVICES
|
|
608
|
+
and sidecar_http.is_gpu_oom_error(f"{exc}\n{exc.detail}\n{worker.stderr_tail()}")
|
|
609
|
+
):
|
|
610
|
+
return self._respawn_cpu_after_oom(worker)
|
|
611
|
+
exit_status = _exit_after_fail(worker)
|
|
612
|
+
if exit_status is None:
|
|
613
|
+
raise TtsError("RUNTIME_ERROR", str(exc), failed=True) from None
|
|
614
|
+
detail = worker.stderr_tail() or exc.detail
|
|
615
|
+
with self._cond:
|
|
616
|
+
if self._worker is worker:
|
|
617
|
+
self._stop_worker_locked()
|
|
618
|
+
wrapped = self._record_crash_locked(
|
|
619
|
+
(worker.model_id, worker.decision.requested_device),
|
|
620
|
+
TtsWorkerError(str(exc), detail=detail, exit_status=exit_status),
|
|
621
|
+
exit_status,
|
|
622
|
+
)
|
|
623
|
+
if not self._stop_event.is_set():
|
|
624
|
+
self.persist_runtime()
|
|
625
|
+
raise TtsError("RUNTIME_ERROR", str(wrapped), failed=True) from None
|
|
626
|
+
|
|
627
|
+
def _begin_session(self, model_id: str | None) -> TtsWorkerHandle:
|
|
628
|
+
return self._ensure_worker(model_id, claim_session=True)
|
|
629
|
+
|
|
630
|
+
def _end_session(self) -> None:
|
|
631
|
+
with self._cond:
|
|
632
|
+
self._active_sessions = max(0, self._active_sessions - 1)
|
|
633
|
+
self._last_used = self._clock()
|
|
634
|
+
if self._active_sessions == 0:
|
|
635
|
+
self._cond.notify_all()
|
|
636
|
+
if self._config["keep_loaded_seconds"] == 0 and self._worker is not None:
|
|
637
|
+
self._stop_worker_locked()
|
|
638
|
+
if not self._stop_event.is_set():
|
|
639
|
+
self.persist_runtime()
|
|
640
|
+
|
|
641
|
+
def synthesize(
|
|
642
|
+
self, req: TtsSynthRequest, *, model_id: str | None = None
|
|
643
|
+
) -> tuple[TtsSynthResult, str, EffectiveDevice, FallbackReason | None]:
|
|
644
|
+
worker = self._begin_session(model_id)
|
|
645
|
+
try:
|
|
646
|
+
for attempt in range(2):
|
|
647
|
+
try:
|
|
648
|
+
result = tts_workers.get_backend(worker.engine).synthesize(worker, req)
|
|
649
|
+
break
|
|
650
|
+
except TtsWorkerError as exc:
|
|
651
|
+
recovered = self._handle_worker_failure(
|
|
652
|
+
worker, exc, allow_oom_fallback=(attempt == 0)
|
|
653
|
+
)
|
|
654
|
+
if recovered is None:
|
|
655
|
+
raise
|
|
656
|
+
worker = recovered
|
|
657
|
+
else:
|
|
658
|
+
raise TtsError("RUNTIME_ERROR", "tts synthesis recovery failed", failed=True)
|
|
659
|
+
with self._cond:
|
|
660
|
+
self._crash_streak = None
|
|
661
|
+
dec = worker.decision
|
|
662
|
+
return result, worker.model_id, dec.effective_device, dec.fallback_reason
|
|
663
|
+
finally:
|
|
664
|
+
self._end_session()
|
|
665
|
+
|
|
666
|
+
def _pull_first_stream_chunk(
|
|
667
|
+
self, worker: TtsWorkerHandle, req: TtsSynthRequest
|
|
668
|
+
) -> tuple[TtsWorkerHandle, bytes | None, int, Iterator[tuple[bytes, int]]]:
|
|
669
|
+
for attempt in range(2):
|
|
670
|
+
stream_iter = iter(
|
|
671
|
+
tts_workers.get_backend(worker.engine).synthesize_stream(worker, req)
|
|
672
|
+
)
|
|
673
|
+
try:
|
|
674
|
+
for pcm_chunk, chunk_rate in stream_iter:
|
|
675
|
+
if pcm_chunk:
|
|
676
|
+
return worker, pcm_chunk, chunk_rate or worker.sample_rate, stream_iter
|
|
677
|
+
return worker, None, worker.sample_rate, stream_iter
|
|
678
|
+
except TtsWorkerError as exc:
|
|
679
|
+
tts_http.close_stream(stream_iter)
|
|
680
|
+
recovered = self._handle_worker_failure(
|
|
681
|
+
worker, exc, allow_oom_fallback=(attempt == 0)
|
|
682
|
+
)
|
|
683
|
+
if recovered is None:
|
|
684
|
+
raise
|
|
685
|
+
worker = recovered
|
|
686
|
+
raise TtsError("RUNTIME_ERROR", "tts stream recovery failed", failed=True)
|
|
687
|
+
|
|
688
|
+
def synthesize_stream(
|
|
689
|
+
self, req: TtsSynthRequest, *, model_id: str | None = None
|
|
690
|
+
) -> tuple[str, EffectiveDevice, FallbackReason | None, int, Iterator[bytes]]:
|
|
691
|
+
worker = self._begin_session(model_id)
|
|
692
|
+
try:
|
|
693
|
+
worker, first_chunk, rate, rest = self._pull_first_stream_chunk(worker, req)
|
|
694
|
+
except Exception:
|
|
695
|
+
self._end_session()
|
|
696
|
+
raise
|
|
697
|
+
with self._cond:
|
|
698
|
+
self._crash_streak = None
|
|
699
|
+
dec = worker.decision
|
|
700
|
+
if first_chunk is None:
|
|
701
|
+
tts_http.close_stream(rest)
|
|
702
|
+
self._end_session()
|
|
703
|
+
return worker.model_id, dec.effective_device, dec.fallback_reason, rate, iter(())
|
|
704
|
+
|
|
705
|
+
def _on_mid_stream_error(exc: TtsWorkerError) -> None:
|
|
706
|
+
self._handle_worker_failure(worker, exc, allow_oom_fallback=False)
|
|
707
|
+
|
|
708
|
+
session = tts_http.StreamSession(first_chunk, rest, _on_mid_stream_error, self._end_session)
|
|
709
|
+
return worker.model_id, dec.effective_device, dec.fallback_reason, rate, session
|
|
710
|
+
|
|
711
|
+
def shutdown(self) -> None:
|
|
712
|
+
self._stop_event.set()
|
|
713
|
+
if self._sweeper is not None and self._sweeper.is_alive():
|
|
714
|
+
self._sweeper.join(timeout=2.0)
|
|
715
|
+
with self._cond:
|
|
716
|
+
self._load_generation += 1
|
|
717
|
+
self._wait_idle_locked(1.0)
|
|
718
|
+
self._stop_worker_locked()
|
|
719
|
+
self._state = "stopped"
|
|
720
|
+
self._cond.notify_all()
|
|
721
|
+
tts_state.clear_runtime_record(self.state_dir)
|
|
722
|
+
tts_state.clear_server_pid(self.state_dir)
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def main(argv: list[str] | None = None) -> int:
|
|
726
|
+
args = tts_http.parse_sidecar_args(argv)
|
|
727
|
+
state_dir = Path(args.state_dir) if args.state_dir else None
|
|
728
|
+
if state_dir is not None:
|
|
729
|
+
os.environ["LOCALMODELS_STATE"] = str(state_dir)
|
|
730
|
+
debug_mode.activate()
|
|
731
|
+
key_file, api_key = tts_state.ensure_api_key(state_dir)
|
|
732
|
+
controller = TtsSidecar(
|
|
733
|
+
args.base_dir,
|
|
734
|
+
base_url=f"http://{args.host}:{args.port}",
|
|
735
|
+
key_file=key_file,
|
|
736
|
+
state_dir=state_dir,
|
|
737
|
+
)
|
|
738
|
+
tts_http.serve_sidecar(
|
|
739
|
+
controller,
|
|
740
|
+
host=args.host,
|
|
741
|
+
port=args.port,
|
|
742
|
+
api_key=api_key,
|
|
743
|
+
state_dir=state_dir,
|
|
744
|
+
preload_model=args.model,
|
|
745
|
+
)
|
|
746
|
+
return 0
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
if __name__ == "__main__":
|
|
750
|
+
raise SystemExit(main())
|