@simplexai/localmodels-linux-arm64 0.1.0-dev.64 → 0.1.0-dev.66

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.
Files changed (127) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +125 -121
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/approval.py +5 -3
  6. package/modules/localmodels/auth_proxy.py +34 -2
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +504 -18
  9. package/modules/localmodels/catalog.py +2 -1
  10. package/modules/localmodels/catalog_recipes.py +3 -0
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +1 -1
  13. package/modules/localmodels/custom_hub.py +54 -6
  14. package/modules/localmodels/custom_probe.py +33 -5
  15. package/modules/localmodels/debug_stub_server.py +34 -1
  16. package/modules/localmodels/deploy.py +45 -285
  17. package/modules/localmodels/deployment_lifecycle.py +167 -0
  18. package/modules/localmodels/download-mirrors.json +43 -3
  19. package/modules/localmodels/draft_spec.py +43 -1
  20. package/modules/localmodels/engine_adapters/__init__.py +4 -2
  21. package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
  22. package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
  23. package/modules/localmodels/engines-b11583.json +9 -5
  24. package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
  25. package/modules/localmodels/engines.json +9 -5
  26. package/modules/localmodels/gateway.py +124 -13
  27. package/modules/localmodels/gateway_accept.py +1 -6
  28. package/modules/localmodels/gateway_cli.py +13 -24
  29. package/modules/localmodels/gateway_ops.py +185 -0
  30. package/modules/localmodels/gateway_server.py +3 -2
  31. package/modules/localmodels/harness.py +13 -16
  32. package/modules/localmodels/harness_core.py +4 -9
  33. package/modules/localmodels/harness_gateway.py +18 -6
  34. package/modules/localmodels/harness_probe.py +64 -3
  35. package/modules/localmodels/hosts.py +22 -34
  36. package/modules/localmodels/library_convert.py +3 -3
  37. package/modules/localmodels/library_custom.py +15 -13
  38. package/modules/localmodels/library_elastic.py +27 -13
  39. package/modules/localmodels/library_jobs.py +151 -28
  40. package/modules/localmodels/library_model.py +22 -2
  41. package/modules/localmodels/library_order.py +5 -4
  42. package/modules/localmodels/library_poly.py +2 -2
  43. package/modules/localmodels/library_pricing.py +34 -318
  44. package/modules/localmodels/library_serve.py +20 -12
  45. package/modules/localmodels/library_smoke.py +8 -1
  46. package/modules/localmodels/library_state.py +12 -0
  47. package/modules/localmodels/library_status.py +26 -16
  48. package/modules/localmodels/llm_rank.py +1 -1
  49. package/modules/localmodels/magpie_legacy.py +160 -0
  50. package/modules/localmodels/magpie_setup.py +6 -1
  51. package/modules/localmodels/pi_profile.py +3 -7
  52. package/modules/localmodels/plan_envelope.py +1 -1
  53. package/modules/localmodels/{budget.py → planning/budget.py} +56 -33
  54. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/recommend.py +1 -1
  57. package/modules/localmodels/recommend_cli.py +3 -4
  58. package/modules/localmodels/remote_ops_mirrors.py +55 -19
  59. package/modules/localmodels/residency_host.py +1 -1
  60. package/modules/localmodels/service_control.py +4 -4
  61. package/modules/localmodels/service_deployment.py +4 -4
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +29 -2
  64. package/modules/localmodels/setup_inspection_harness.py +5 -2
  65. package/modules/localmodels/setup_text.py +6 -0
  66. package/modules/localmodels/setup_upgrade.py +3 -12
  67. package/modules/localmodels/slot_cache.py +1 -3
  68. package/modules/localmodels/speech_admission.py +17 -5
  69. package/modules/localmodels/speech_catalog.py +5 -1
  70. package/modules/localmodels/speech_cli.py +5 -5
  71. package/modules/localmodels/speech_jobs.py +103 -20
  72. package/modules/localmodels/speech_model.py +2 -0
  73. package/modules/localmodels/speech_server.py +132 -9
  74. package/modules/localmodels/speech_state.py +11 -0
  75. package/modules/localmodels/speech_worker_sensevoice.py +215 -19
  76. package/modules/localmodels/speech_workers.py +79 -7
  77. package/modules/localmodels/stack.py +15 -6
  78. package/modules/localmodels/stack_auto.py +10 -4
  79. package/modules/localmodels/stack_aux_gpu.py +1 -1
  80. package/modules/localmodels/stack_binding.py +24 -143
  81. package/modules/localmodels/stack_capacity.py +4 -4
  82. package/modules/localmodels/stack_card.py +1 -1
  83. package/modules/localmodels/stack_cleanup.py +3 -3
  84. package/modules/localmodels/stack_cli.py +3 -0
  85. package/modules/localmodels/stack_client_settings.py +9 -2
  86. package/modules/localmodels/stack_compose.py +42 -9
  87. package/modules/localmodels/stack_console.py +2 -2
  88. package/modules/localmodels/stack_debug.py +1 -1
  89. package/modules/localmodels/stack_decision.py +1 -1
  90. package/modules/localmodels/stack_doctor.py +10 -7
  91. package/modules/localmodels/stack_down.py +3 -3
  92. package/modules/localmodels/stack_gpu_memory.py +1 -1
  93. package/modules/localmodels/stack_hardware.py +3 -3
  94. package/modules/localmodels/stack_hardware_text.py +1 -1
  95. package/modules/localmodels/stack_lifecycle.py +7 -7
  96. package/modules/localmodels/stack_memory.py +1 -1
  97. package/modules/localmodels/stack_mlx.py +1 -1
  98. package/modules/localmodels/stack_plan.py +18 -13
  99. package/modules/localmodels/stack_ports.py +60 -29
  100. package/modules/localmodels/stack_preflight.py +4 -3
  101. package/modules/localmodels/stack_remove.py +13 -6
  102. package/modules/localmodels/stack_review.py +3 -5
  103. package/modules/localmodels/stack_rollback.py +1 -1
  104. package/modules/localmodels/stack_route.py +5 -4
  105. package/modules/localmodels/stack_suite.py +17 -4
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +8 -13
  108. package/modules/localmodels/stack_up.py +10 -9
  109. package/modules/localmodels/stack_update.py +2 -1
  110. package/modules/localmodels/stack_verify.py +4 -30
  111. package/modules/localmodels/stack_view.py +6 -4
  112. package/modules/localmodels/stack_view_apply.py +2 -2
  113. package/modules/localmodels/stack_view_text.py +2 -6
  114. package/modules/localmodels/stack_view_tick.py +2 -2
  115. package/modules/localmodels/stack_view_words.py +5 -2
  116. package/modules/localmodels/stack_warm.py +1 -1
  117. package/modules/localmodels/suite.py +1 -1
  118. package/modules/localmodels/tui_views.py +11 -5
  119. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/METADATA +1 -1
  120. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/RECORD +122 -118
  121. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/NOTICE +3 -0
  122. package/package.json +1 -1
  123. package/tool.json +1 -1
  124. package/modules/localmodels/library_vram.py +0 -123
  125. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/WHEEL +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/entry_points.txt +0 -0
  127. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -13,6 +13,7 @@ from urllib.parse import urlsplit
13
13
 
14
14
  from localmodels import (
15
15
  bifrost_config,
16
+ deployment_lifecycle,
16
17
  gateway,
17
18
  gateway_bifrost,
18
19
  gateway_keys,
@@ -24,6 +25,7 @@ from localmodels import (
24
25
  library_model,
25
26
  library_serve,
26
27
  library_state,
28
+ magpie_legacy,
27
29
  source_byok,
28
30
  stack,
29
31
  )
@@ -70,13 +72,8 @@ def prepare_gateway(root: Path, binding: dict[str, str] | None = None) -> harnes
70
72
  return plan
71
73
 
72
74
 
73
- def set_gateway_binding(jobs: ServiceJobs, addr: str, kind: str = "magpie") -> None:
74
- # Magpie's documented local client key is an app identity, not a remote gateway secret;
75
- # this tool's Bifrost checks no key on loopback inference.
76
- binding = {"baseUrl": f"http://{addr}/v1", "key": "magpie-simplex"}
77
- if kind == "bifrost":
78
- binding = {"baseUrl": f"http://{addr}/v1", "key": gateway_keys.CALLER_KEY, "kind": kind}
79
- jobs.set_gateway(binding)
75
+ def set_gateway_binding(jobs: ServiceJobs, addr: str, kind: str = magpie_legacy.MAGPIE) -> None:
76
+ jobs.set_gateway(magpie_legacy.for_kind(kind).binding(addr, gateway_keys.CALLER_KEY))
80
77
 
81
78
 
82
79
  def auxiliary_endpoints(bindings: dict[str, dict[str, str]]) -> list[AuxEndpoint]:
@@ -134,7 +131,7 @@ def _stack_llm_active(plan: StackPlan) -> bool:
134
131
  owned = None
135
132
  if owned is not None:
136
133
  entry = owned["deployments"].get(plan["llm"]["name"])
137
- if entry is not None and entry.get("removed"):
134
+ if deployment_lifecycle.is_removed(entry):
138
135
  return False
139
136
  key_file = Path(os.path.expanduser(plan["llm"]["service"]["deploy_dir"]), "api-key")
140
137
  if entry is None and not key_file.is_file():
@@ -238,14 +235,13 @@ class Wiring:
238
235
  if addr is None:
239
236
  jobs.set_gateway(None)
240
237
  else:
241
- set_gateway_binding(jobs, addr, "bifrost")
238
+ set_gateway_binding(jobs, addr, magpie_legacy.BIFROST)
242
239
  self.last = copy.deepcopy(signature)
243
240
 
244
241
  def _sync_inactive_magpie(
245
242
  self,
246
243
  signature: object,
247
244
  tools_plan: harness.HarnessPlan,
248
- kind: str,
249
245
  bindings: dict[str, dict[str, str]],
250
246
  had_bindings: bool,
251
247
  jobs: ServiceJobs,
@@ -266,7 +262,7 @@ class Wiring:
266
262
  decision_provider=decision_pid,
267
263
  )
268
264
  if bindings:
269
- set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
265
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"])
270
266
  else:
271
267
  jobs.set_gateway(None)
272
268
  self.last = copy.deepcopy(signature)
@@ -276,7 +272,7 @@ class Wiring:
276
272
  main_plan: Path,
277
273
  plan_id: str,
278
274
  tools_plan: harness.HarnessPlan,
279
- kind: str,
275
+ adapter: magpie_legacy.GatewayAdapter,
280
276
  bindings: dict[str, dict[str, str]],
281
277
  jobs: ServiceJobs,
282
278
  ) -> None:
@@ -290,12 +286,13 @@ class Wiring:
290
286
  if bifrost_record is not None
291
287
  else {}
292
288
  )
293
- if kind == "bifrost" or bifrost_doc:
289
+ # A Magpie plan still syncs the foundations into a Bifrost config this tool keeps.
290
+ if not adapter.legacy or bifrost_doc:
294
291
  self._sync_inactive_bifrost(
295
292
  signature, bifrost_record, bifrost_doc, tools_plan, bindings, had_bindings, jobs
296
293
  )
297
294
  return
298
- self._sync_inactive_magpie(signature, tools_plan, kind, bindings, had_bindings, jobs)
295
+ self._sync_inactive_magpie(signature, tools_plan, bindings, had_bindings, jobs)
299
296
 
300
297
  def sync(self, main_plan: Path | None, jobs: ServiceJobs) -> None:
301
298
  bindings = jobs.bindings()
@@ -335,9 +332,9 @@ class Wiring:
335
332
  if not ready.get("ready") or ready.get("planId") != plan["plan_id"]:
336
333
  return
337
334
  tools_plan = copy.deepcopy(plan["harness"])
338
- kind = harness.gateway_kind(tools_plan["gateway"])
335
+ adapter = magpie_legacy.of(tools_plan["gateway"])
339
336
  if not _stack_llm_active(plan):
340
- self._sync_inactive(main_plan, plan["plan_id"], tools_plan, kind, bindings, jobs)
337
+ self._sync_inactive(main_plan, plan["plan_id"], tools_plan, adapter, bindings, jobs)
341
338
  return
342
339
  signature = (str(main_plan), plan["plan_id"], receipt.stat().st_mtime_ns, bindings)
343
340
  if self.last == signature:
@@ -348,8 +345,9 @@ class Wiring:
348
345
  )
349
346
  aux = auxiliary_endpoints(bindings)
350
347
  # Only update the owned routing group. Never replace a user's current Pi selection.
351
- with library_gateway.gateway_locked() if kind == "bifrost" else contextlib.nullcontext():
352
- if kind == "bifrost" and not _stack_llm_active(plan):
348
+ shared = adapter.shares_config
349
+ with library_gateway.gateway_locked() if shared else contextlib.nullcontext():
350
+ if shared and not _stack_llm_active(plan):
353
351
  return
354
352
  gateway.wire(
355
353
  tools_plan,
@@ -358,5 +356,5 @@ class Wiring:
358
356
  aux,
359
357
  select_pi=False,
360
358
  )
361
- set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
359
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"], adapter.kind)
362
360
  self.last = copy.deepcopy(signature)
@@ -12,7 +12,6 @@ from typing import Any, Literal, TypedDict
12
12
 
13
13
  from localmodels import (
14
14
  app,
15
- budget,
16
15
  cli_help,
17
16
  harness,
18
17
  metal,
@@ -24,12 +23,14 @@ from localmodels import (
24
23
  stack,
25
24
  stack_binding,
26
25
  stack_hardware,
26
+ stack_ports,
27
27
  stack_review,
28
28
  )
29
29
  from localmodels.contracts import decode
30
30
  from localmodels.engines import CudaDriverError
31
31
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
32
32
  from localmodels.plan_envelope import PlanError
33
+ from localmodels.planning import budget
33
34
  from localmodels.probe import HostFacts, Services
34
35
  from localmodels.runtime_cli import inspect_runtimes
35
36
  from localmodels.setup_inspection_harness import Reason as Reason
@@ -237,12 +238,35 @@ def _harness_availability(
237
238
  }
238
239
 
239
240
 
241
+ def _port_check_availability(
242
+ options: StackOptions, facts: HostFacts, exc: StackError, lang: Lang
243
+ ) -> StackAvailability:
244
+ """No port of a range could be confirmed free (stack_ports.PortProbeError): blocked now and
245
+ retryable, never a reason to recommend another runtime when the hardware fits."""
246
+ capable = setup_inspection_harness.hardware_capable_without_harness(options, facts)
247
+ return {
248
+ "available": False,
249
+ "reasons": [
250
+ {
251
+ "code": "port-check-failed",
252
+ "message": text("port-check-failed", lang, detail=str(exc))
253
+ if capable
254
+ else str(exc),
255
+ }
256
+ ],
257
+ "plan": None,
258
+ "hardwareCapable": capable,
259
+ }
260
+
261
+
240
262
  def _plan_stack(
241
263
  options: StackOptions, facts: HostFacts, share_gpu: bool, lang: Lang
242
264
  ) -> StackAvailability:
243
265
  try:
244
266
  try:
245
267
  plan = stack.build(options, facts=facts)
268
+ except stack_ports.PortProbeError as exc:
269
+ return _port_check_availability(options, facts, exc, lang)
246
270
  except (PlanError, stack.StackError) as exc:
247
271
  last_error: PlanError | StackError | None = exc
248
272
  last_options = options
@@ -518,7 +542,7 @@ INSPECT = (
518
542
  INSPECT_REASONS = (
519
543
  "unsupported-platform · facts-unavailable · plan-unavailable · gpu-sharing-required\n"
520
544
  "cuda-driver-update-required · cuda-driver-version-unknown · gateway-port-in-use · "
521
- "harness-unavailable\n"
545
+ "harness-unavailable · port-check-failed\n"
522
546
  "(gpu-sharing-required: a plan fits only beside other GPU work, its owner known or not; ask, "
523
547
  "then rerun with --share-gpu, which plans by the free VRAM)\n"
524
548
  "cuda-driver-update-required / cuda-driver-version-unknown (stack.state is blocked-now, "
@@ -528,6 +552,9 @@ INSPECT_REASONS = (
528
552
  "gateway-port-in-use / harness-unavailable (stack.state is blocked-now with "
529
553
  "hardwareCapable true when the hardware fits, but the gateway port is held or tool checks "
530
554
  "failed; free the port or fix the tool issue and check again)\n"
555
+ "port-check-failed (stack.state is blocked-now with hardwareCapable true when the hardware "
556
+ "fits: no port of a range the stack needs could be confirmed free right now, because the "
557
+ "loopback check could not tell; check again)\n"
531
558
  "gpu-memory-required (stack.state is blocked-now, stack.basis is capacity: other programs "
532
559
  "or another inference app/GPU workload use the GPU memory the plan needs; close them and "
533
560
  "check again; gpuIndex, freeBytes and requiredBytes give the card and its free and needed "
@@ -7,7 +7,6 @@ from collections.abc import Callable
7
7
  from typing import TypedDict
8
8
 
9
9
  from localmodels import (
10
- budget,
11
10
  deploy,
12
11
  harness,
13
12
  metal,
@@ -21,6 +20,7 @@ from localmodels import (
21
20
  from localmodels.contracts import decode
22
21
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
23
22
  from localmodels.plan_envelope import PlanError
23
+ from localmodels.planning import budget
24
24
  from localmodels.probe import HostFacts
25
25
  from localmodels.setup_text import Lang, text
26
26
  from localmodels.stack_plan import RAM_FLOOR, StackOptions, StackPlan, deployments, platform_error
@@ -45,7 +45,10 @@ class Reason(_ReasonOptional):
45
45
  message: str
46
46
 
47
47
 
48
- HARNESS_CODES = frozenset({"gateway-port-in-use", "harness-unavailable"})
48
+ # Blocked-now reasons about the gateway, its tools or loopback ports, not the hardware.
49
+ # port-check-failed: the loopback probe could not tell whether any port of a range is free
50
+ # (stack_ports.PortProbeError, or the Magpie address); checking again may pass.
51
+ HARNESS_CODES = frozenset({"gateway-port-in-use", "harness-unavailable", "port-check-failed"})
49
52
  _PORT_CONFLICT_HINTS = (
50
53
  "is held by",
51
54
  "ports 3425..3456 are all in use",
@@ -106,6 +106,12 @@ MESSAGES: dict[str, tuple[str, str]] = {
106
106
  "This computer's hardware can run local models, but the gateway port is currently in use "
107
107
  "({detail}). Stop that program or set another gateway address, then check again.",
108
108
  ),
109
+ "port-check-failed": (
110
+ "这台电脑的硬件可以运行本地模型,但暂时无法确认本地端口是否空闲({detail})。"
111
+ "请稍后重新检查。",
112
+ "This computer's hardware can run local models, but whether a local port is free could "
113
+ "not be confirmed right now ({detail}). Check again in a moment.",
114
+ ),
109
115
  "harness-unavailable": (
110
116
  "这台电脑的硬件可以运行本地模型,但网关或工具环境检查未通过({detail})。"
111
117
  "请先处理该问题后重新检查。",
@@ -5,20 +5,11 @@ from __future__ import annotations
5
5
  from collections.abc import Callable
6
6
  from typing import TypedDict
7
7
 
8
- from localmodels import (
9
- budget,
10
- catalog,
11
- catalog_recipes,
12
- harness,
13
- library_vram,
14
- llm_rank,
15
- stack,
16
- stack_review,
17
- win_probe,
18
- )
8
+ from localmodels import catalog, catalog_recipes, harness, llm_rank, stack, stack_review, win_probe
19
9
  from localmodels.contracts import decode
20
10
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
21
11
  from localmodels.plan_envelope import PlanError
12
+ from localmodels.planning import budget, memory_pools
22
13
  from localmodels.probe import HostFacts
23
14
  from localmodels.setup_text import Lang, text
24
15
  from localmodels.stack_plan import StackError, StackOptions, StackPlan, deployments
@@ -150,6 +141,6 @@ def upgrade_hint(
150
141
  return None
151
142
  hint: StackUpgrade = {"plan": roomy_plan, "summary": summary, "reasons": reasons}
152
143
  if any(r["code"] == "gpu-memory-required" for r in reasons):
153
- if apps := library_vram.closeable_gpu_apps(facts):
144
+ if apps := memory_pools.closeable_gpu_apps(facts):
154
145
  hint["gpuApps"] = apps
155
146
  return hint
@@ -424,9 +424,7 @@ def main(argv: list[str]) -> int:
424
424
  tally = Tally(slot_dir)
425
425
  if not (slot_dir / PREFIX_FILE).exists():
426
426
  tally.kept = None # write the leading prefix again
427
- proxy = http.server.ThreadingHTTPServer(
428
- (host, int(port)), handler(upstream, slot_dir, tally, key)
429
- )
427
+ proxy = auth_proxy.bind_server((host, int(port)), handler(upstream, slot_dir, tally, key))
430
428
  proxy.daemon_threads = True
431
429
  child = subprocess.Popen(inner)
432
430
  guard = end_with_me(child.pid)
@@ -21,7 +21,6 @@ from pathlib import Path
21
21
 
22
22
  from localmodels import (
23
23
  app,
24
- budget,
25
24
  engines,
26
25
  hosts,
27
26
  library_state,
@@ -30,6 +29,7 @@ from localmodels import (
30
29
  speech_catalog,
31
30
  speech_state,
32
31
  )
32
+ from localmodels.planning import budget
33
33
  from localmodels.probe import GPU, HostFacts
34
34
  from localmodels.speech_catalog import SpeechModelSpec
35
35
  from localmodels.speech_model import EffectiveDevice, FallbackReason, RequestedDevice
@@ -137,6 +137,7 @@ def _decide_metal(
137
137
  spec: SpeechModelSpec,
138
138
  facts: HostFacts,
139
139
  reserved: Mapping[str, int],
140
+ llm_pools: set[str],
140
141
  ) -> DeviceDecision:
141
142
  adm = budget.admission_budget(facts, "unified", delta_bytes=reserved.get("unified", 0))
142
143
  if adm is None or adm.critical_pressure:
@@ -147,7 +148,13 @@ def _decide_metal(
147
148
  fallback_detail={"pool": "unified", "memory_pressure": "critical"},
148
149
  pool="system",
149
150
  )
150
- if adm.pressure_level == metal.PRESSURE_WARN:
151
+ # On Apple Silicon unified memory, running Whisper on CPU consumes roughly the same ~1.4 GB
152
+ # RAM as Metal while degrading 3s transcription from ~0.5s to ~15-19s. Everyday 16 GB Macs
153
+ # routinely sit at PRESSURE_WARN (level 2), so only yield Metal on PRESSURE_WARN / soft-budget
154
+ # tightness when a local LLM (RANK = 0) is active or loading on the unified pool; otherwise
155
+ # admit Metal whenever wired headroom (hard_ceiling_bytes) fits, relying on runtime_oom_fallback.
156
+ llm_on_unified = "unified" in llm_pools or reserved.get("unified", 0) > 0
157
+ if llm_on_unified and adm.pressure_level == metal.PRESSURE_WARN:
151
158
  return DeviceDecision(
152
159
  requested_device="gpu",
153
160
  effective_device="cpu",
@@ -156,8 +163,12 @@ def _decide_metal(
156
163
  pool="system",
157
164
  )
158
165
  need = spec.vram_estimate_bytes + SPEECH_METAL_WIRED_HEADROOM
159
- free_avail = min(adm.soft_budget_bytes, adm.hard_ceiling_bytes)
160
- if adm.soft_budget_bytes < need or adm.hard_ceiling_bytes < need:
166
+ if adm.hard_ceiling_bytes < need or (llm_on_unified and adm.soft_budget_bytes < need):
167
+ free_avail = (
168
+ min(adm.soft_budget_bytes, adm.hard_ceiling_bytes)
169
+ if llm_on_unified
170
+ else adm.hard_ceiling_bytes
171
+ )
161
172
  return DeviceDecision(
162
173
  requested_device="gpu",
163
174
  effective_device="cpu",
@@ -338,7 +349,8 @@ def decide_speech_device(
338
349
  in_flight_library_load_bytes() if reserved_by_pool is None else dict(reserved_by_pool)
339
350
  )
340
351
  if metal.supported(host):
341
- return _decide_metal(spec, host, reserved)
352
+ pools_with_llm = active_llm_pools() if llm_pools is None else llm_pools
353
+ return _decide_metal(spec, host, reserved, pools_with_llm)
342
354
  if host.get("platform") == "darwin":
343
355
  return DeviceDecision(
344
356
  requested_device="gpu",
@@ -17,7 +17,11 @@ from localmodels.contracts import decode
17
17
  SpeechEngine = Literal["sherpa-onnx", "whisper.cpp"]
18
18
  QualityRating = Literal["fast-cjk", "high-multilingual"]
19
19
 
20
- V1_SPEECH_MODEL_IDS: tuple[str, ...] = ("sensevoice-small", "whisper-large-v3-turbo")
20
+ V1_SPEECH_MODEL_IDS: tuple[str, ...] = (
21
+ "qwen3-asr-0.6b",
22
+ "sensevoice-small",
23
+ "whisper-large-v3-turbo",
24
+ )
21
25
 
22
26
 
23
27
  class _RawSpeechFile(TypedDict):
@@ -20,10 +20,10 @@ from localmodels.speech_model import (
20
20
  )
21
21
 
22
22
  DESCRIPTION = (
23
- "Manage local speech-to-text models (Whisper Large v3 Turbo and opt-in SenseVoice Small): "
24
- "inspect status, download with resumable verification, cancel, remove, and configure runtime "
25
- "preferences. Every command writes pure JSON or JSONL on stdout. Exit status: 0 ok, 1 failed, "
26
- "2 refused, 130 cancelled."
23
+ "Manage local speech-to-text models (Whisper Large v3 Turbo, Qwen3-ASR 0.6B, and opt-in "
24
+ "SenseVoice Small): inspect status, download with resumable verification, cancel, remove, and "
25
+ "configure runtime preferences. Every command writes pure JSON or JSONL on stdout. Exit "
26
+ "status: 0 ok, 1 failed, 2 refused, 130 cancelled."
27
27
  )
28
28
 
29
29
  _FALLBACK_CODE = {
@@ -51,7 +51,7 @@ def _add_model_arg(parser: argparse.ArgumentParser) -> None:
51
51
  parser.add_argument(
52
52
  "model",
53
53
  metavar="MODEL",
54
- help="speech model id (whisper-large-v3-turbo or sensevoice-small)",
54
+ help="speech model id (whisper-large-v3-turbo, qwen3-asr-0.6b, or sensevoice-small)",
55
55
  )
56
56
 
57
57
 
@@ -7,6 +7,8 @@ HF/hf-mirror/ModelScope selection, and SHA-256 verification before atomic replac
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import contextlib
11
+ import io
10
12
  import os
11
13
  import shutil
12
14
  import sys
@@ -21,6 +23,7 @@ from localmodels import (
21
23
  app,
22
24
  debug_mode,
23
25
  deploy,
26
+ deployment_lifecycle,
24
27
  engines,
25
28
  hosts,
26
29
  library_jobs,
@@ -60,10 +63,26 @@ KEEP_FAILED_CODES = frozenset(("DOWNLOAD_FAILED", "NETWORK_UNAVAILABLE", "DISK_I
60
63
 
61
64
 
62
65
  def model_dir(base_dir: str, model_id: str) -> Path:
63
- """Short, flat directory holding one speech model's weight files."""
66
+ """Directory holding one speech model's weight and tokenizer files."""
64
67
  return Path(os.path.expanduser(base_dir)).resolve() / "speech" / model_id
65
68
 
66
69
 
70
+ def _relative_file_path(file_path: str) -> Path:
71
+ """Validate and preserve relative subdirectories (e.g. ``tokenizer/vocab.json``)."""
72
+ normalized = file_path.replace("\\", "/")
73
+ if not normalized or normalized.startswith("/") or ":" in normalized.split("/", 1)[0]:
74
+ raise ValueError(f"unsafe relative speech file path: {file_path!r}")
75
+ parts = [part for part in normalized.split("/") if part not in ("", ".")]
76
+ if not parts or any(part == ".." for part in parts):
77
+ raise ValueError(f"unsafe relative speech file path: {file_path!r}")
78
+ return Path(*parts)
79
+
80
+
81
+ def model_file_dest(base_dir: str, model_id: str, file_path: str) -> Path:
82
+ """Destination path for one pinned file of ``model_id``, preserving relative subdirs."""
83
+ return model_dir(base_dir, model_id) / _relative_file_path(file_path)
84
+
85
+
67
86
  def _file_spec(
68
87
  spec: SpeechModelSpec,
69
88
  base_dir: str,
@@ -72,7 +91,8 @@ def _file_spec(
72
91
  sha256: str,
73
92
  hf_endpoint: str,
74
93
  ) -> ReusableFile:
75
- dest = str(model_dir(base_dir, spec.id) / Path(file_path).name)
94
+ rel = _relative_file_path(file_path)
95
+ dest = str(model_dir(base_dir, spec.id) / rel)
76
96
  url = plan_envelope.hub_url(hf_endpoint, spec.repo, spec.revision, file_path)
77
97
  entry: ReusableFile = {
78
98
  "repo": spec.repo,
@@ -80,7 +100,7 @@ def _file_spec(
80
100
  "revision": spec.revision,
81
101
  "size_bytes": size_bytes,
82
102
  "sha256": sha256,
83
- "local_name": Path(file_path).name,
103
+ "local_name": rel.as_posix(),
84
104
  "dest": dest,
85
105
  "url": url,
86
106
  }
@@ -121,6 +141,7 @@ def _build_model_row(
121
141
  runtime: SpeechRuntime,
122
142
  record: SpeechModelRecord | None,
123
143
  job_info: tuple[SpeechJob, bool] | None,
144
+ engine_bytes: int = 0,
124
145
  ) -> SpeechModelRow:
125
146
  active = runtime["running"] and runtime["active_model"] == spec.id
126
147
  download_info: SpeechDownloadProgress | None = None
@@ -170,7 +191,7 @@ def _build_model_row(
170
191
  "license": str(static["license"]),
171
192
  "license_url": str(static["license_url"]),
172
193
  "commercial_notice": static["commercial_notice"],
173
- "disk_size_bytes": int(static["disk_size_bytes"]),
194
+ "disk_size_bytes": int(static["disk_size_bytes"]) + engine_bytes,
174
195
  "vram_estimate_bytes": int(static["vram_estimate_bytes"]),
175
196
  "ram_estimate_bytes": int(static["ram_estimate_bytes"]),
176
197
  "gpu_supported": bool(static["gpu_supported"]),
@@ -187,8 +208,21 @@ def status(base_dir: str, *, state_dir: Path | None = None) -> SpeechStatusDocum
187
208
  runtime = speech_state.probe_live_runtime(cfg, state_dir)
188
209
  by_record = {rec["id"]: rec for rec in speech_state.records(state_dir)}
189
210
  by_job = speech_state.jobs(state_dir)
211
+ debug = debug_mode.current()
212
+ facts = (
213
+ cast(HostFacts, debug_mode.simulated_facts(debug))
214
+ if debug.mode == "simulate"
215
+ else hosts.load_facts(hosts.LOCAL_ID)
216
+ )
190
217
  rows = [
191
- _build_model_row(spec, base_dir, runtime, by_record.get(spec.id), by_job.get(spec.id))
218
+ _build_model_row(
219
+ spec,
220
+ base_dir,
221
+ runtime,
222
+ by_record.get(spec.id),
223
+ by_job.get(spec.id),
224
+ _engine_bytes(spec, base_dir, use_gpu=bool(cfg.get("use_gpu")), facts=facts),
225
+ )
192
226
  for spec in speech_catalog.speech_models()
193
227
  ]
194
228
  return {
@@ -201,6 +235,22 @@ def status(base_dir: str, *, state_dir: Path | None = None) -> SpeechStatusDocum
201
235
  }
202
236
 
203
237
 
238
+ def _engine_bytes(
239
+ spec: SpeechModelSpec, base_dir: str, *, use_gpu: bool, facts: HostFacts | None
240
+ ) -> int:
241
+ """Archive bytes of the engine build a download of ``spec`` fetches on this host with the
242
+ configured GPU preference, so a row's size is what the model takes with its engine (the
243
+ CUDA whisper.cpp build is larger than the weights). Uses the facts the last probe saved; a
244
+ host never probed counts the weights only, since a status read must not probe."""
245
+ if spec.engine != "whisper.cpp" or facts is None:
246
+ return 0
247
+ with contextlib.redirect_stderr(io.StringIO()):
248
+ engine = _select_whisper_engine(spec, base_dir, include_gpu_engine=use_gpu, facts=facts)
249
+ if engine is None:
250
+ return 0
251
+ return sum(int(asset["size_bytes"]) for asset in engine.get("assets") or ())
252
+
253
+
204
254
  def model_row(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> SpeechModelRow:
205
255
  """Return the current ``SpeechModelRow`` for ``model_id``."""
206
256
  doc = status(base_dir, state_dir=state_dir)
@@ -560,6 +610,7 @@ def download(
560
610
  with speech_state.held_job(claims, state_dir):
561
611
  handle = SpeechJobHandle(job, state_dir)
562
612
  try:
613
+ _unload_stale_if_active(spec, base_dir, state_dir)
563
614
  with _watch_cancel(job, state_dir):
564
615
  _run_fetch(spec, files, engine, handle, runner)
565
616
  except KeyboardInterrupt:
@@ -670,22 +721,43 @@ def _engine_in_use_elsewhere(
670
721
  if other and os.path.realpath(os.path.expanduser(other)) == target:
671
722
  return True
672
723
  for owned in hosts.load_owned()["deployments"].values():
673
- if not owned.get("removed"):
724
+ if deployment_lifecycle.holds_service(owned):
674
725
  for path in owned.get("files") or ():
675
726
  if os.path.realpath(os.path.expanduser(path)).startswith(target):
676
727
  return True
677
728
  return False
678
729
 
679
730
 
680
- def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> SpeechModelRow:
681
- """Unload if active, remove weight files idempotently, and preserve shared engines."""
682
- spec = _lookup_model(model_id)
683
- with speech_state.locked(state_dir):
684
- if speech_state.job_alive(spec.id, state_dir):
685
- raise SpeechError("INVALID_STATE", f"{spec.id} is downloading; cancel it first")
731
+ def _prune_empty_model_dirs(target_dir: Path, files: list[str]) -> None:
732
+ """Remove now-empty subdirectories under ``target_dir`` and then ``target_dir`` itself."""
733
+ if not target_dir.is_dir():
734
+ return
735
+ resolved_root = target_dir.resolve()
736
+ subdirs: set[Path] = set()
737
+ for file_path in files:
738
+ parent = Path(os.path.expanduser(file_path)).parent
739
+ try:
740
+ resolved_parent = parent.resolve()
741
+ except OSError:
742
+ continue
743
+ while resolved_parent != resolved_root and resolved_parent.is_relative_to(resolved_root):
744
+ subdirs.add(resolved_parent)
745
+ resolved_parent = resolved_parent.parent
746
+ for subdir in sorted(subdirs, key=lambda p: len(p.parts), reverse=True):
747
+ try:
748
+ subdir.rmdir()
749
+ except OSError:
750
+ pass
751
+ try:
752
+ target_dir.rmdir()
753
+ except OSError:
754
+ pass
755
+
686
756
 
757
+ def _unload_if_active(model_id: str, state_dir: Path | None) -> None:
758
+ """Best-effort unload ``model_id`` from a running sidecar before replacing or deleting weights."""
687
759
  rec_rt = speech_state.load_runtime_record(state_dir)
688
- if rec_rt is not None and rec_rt.get("active_model") == spec.id:
760
+ if rec_rt is not None and rec_rt.get("active_model") == model_id:
689
761
  rt_url = rec_rt.get("base_url")
690
762
  if isinstance(rt_url, str) and rt_url:
691
763
  key_file = rec_rt.get("key_file")
@@ -694,10 +766,26 @@ def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> Sp
694
766
  "/v1/speech/unload",
695
767
  method="POST",
696
768
  key_file=key_file if isinstance(key_file, str) else None,
697
- payload={"model_id": spec.id},
769
+ payload={"model_id": model_id},
698
770
  timeout=3.0,
699
771
  )
700
772
 
773
+
774
+ def _unload_stale_if_active(spec: SpeechModelSpec, base_dir: str, state_dir: Path | None) -> None:
775
+ """Unload a running worker before overwriting stale/mismatched weights."""
776
+ if not weights_installed(spec, base_dir):
777
+ _unload_if_active(spec.id, state_dir)
778
+
779
+
780
+ def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> SpeechModelRow:
781
+ """Unload if active, remove weight files idempotently, and preserve shared engines."""
782
+ spec = _lookup_model(model_id)
783
+ with speech_state.locked(state_dir):
784
+ if speech_state.job_alive(spec.id, state_dir):
785
+ raise SpeechError("INVALID_STATE", f"{spec.id} is downloading; cancel it first")
786
+
787
+ _unload_if_active(spec.id, state_dir)
788
+
701
789
  with speech_state.locked(state_dir):
702
790
  record = speech_state.load_record(spec.id, state_dir)
703
791
  files = [f["dest"] for f in model_file_specs(spec, base_dir)]
@@ -711,12 +799,7 @@ def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> Sp
711
799
  os.remove(candidate)
712
800
  except FileNotFoundError:
713
801
  pass
714
- target_dir = model_dir(base_dir, spec.id)
715
- if target_dir.is_dir():
716
- try:
717
- target_dir.rmdir()
718
- except OSError:
719
- pass
802
+ _prune_empty_model_dirs(model_dir(base_dir, spec.id), files)
720
803
  engine_dir = record.get("engine_dir") if record is not None else None
721
804
  if engine_dir and not _engine_in_use_elsewhere(engine_dir, spec.id, state_dir):
722
805
  eng_path = Path(os.path.expanduser(engine_dir))
@@ -188,6 +188,7 @@ class SpeechRuntime(TypedDict):
188
188
  keep_loaded_seconds: int
189
189
  idle_remaining_seconds: int | None
190
190
  active_sessions: int
191
+ error: SpeechModelError | None
191
192
 
192
193
 
193
194
  class SpeechModelRow(TypedDict):
@@ -268,6 +269,7 @@ def stopped_runtime(config: SpeechConfig) -> SpeechRuntime:
268
269
  "keep_loaded_seconds": config["keep_loaded_seconds"],
269
270
  "idle_remaining_seconds": None,
270
271
  "active_sessions": 0,
272
+ "error": None,
271
273
  }
272
274
 
273
275