@simplexai/localmodels-darwin-x64 0.1.0-dev.102 → 0.1.0-dev.104

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 (153) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +126 -0
  3. package/README.md +10 -0
  4. package/bootstrap.identity +1 -1
  5. package/bootstrap.sha256 +139 -121
  6. package/modules/localmodels/__init__.py +1 -1
  7. package/modules/localmodels/__main__.py +3 -1
  8. package/modules/localmodels/catalog.json +435 -127
  9. package/modules/localmodels/catalog.py +7 -3
  10. package/modules/localmodels/catalog_recipes.py +3 -3
  11. package/modules/localmodels/cli_parser.py +7 -3
  12. package/modules/localmodels/component.py +1 -1
  13. package/modules/localmodels/console.py +1 -1
  14. package/modules/localmodels/context_policy.py +6 -5
  15. package/modules/localmodels/debug_cli.py +0 -12
  16. package/modules/localmodels/debug_mode.py +0 -6
  17. package/modules/localmodels/debug_stub_server.py +280 -7
  18. package/modules/localmodels/decode_calibration.json +3 -4
  19. package/modules/localmodels/decode_calibration.py +5 -2
  20. package/modules/localmodels/deployment_lifecycle.py +1 -1
  21. package/modules/localmodels/download-mirrors.json +77 -1
  22. package/modules/localmodels/engine_adapters/base.py +11 -1
  23. package/modules/localmodels/engine_adapters/strata_poly.py +65 -3
  24. package/modules/localmodels/engine_adapters/suite_plan.py +57 -20
  25. package/modules/localmodels/engines-b11583.json +6 -26
  26. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +3 -15
  27. package/modules/localmodels/engines-b12757-mix-ef2df21.json +3 -15
  28. package/modules/localmodels/engines-prism-b12178-03ec600.json +3 -15
  29. package/modules/localmodels/engines-speechcpp-v0.11.3.json +68 -0
  30. package/modules/localmodels/engines-strata-0.1.47.json +1 -5
  31. package/modules/localmodels/engines-strata-0.1.49.2.json +1 -5
  32. package/modules/localmodels/engines-strata-0.1.59.1.json +1 -5
  33. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +6 -30
  34. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +129 -0
  35. package/modules/localmodels/engines-whisper-b5454.json +6 -30
  36. package/modules/localmodels/engines.json +13 -61
  37. package/modules/localmodels/estimator.py +10 -5
  38. package/modules/localmodels/gpu_specs.py +1 -1
  39. package/modules/localmodels/hosts.py +12 -16
  40. package/modules/localmodels/kokoro-tts-0.6.1.txt +1 -1
  41. package/modules/localmodels/library_elastic.py +135 -6
  42. package/modules/localmodels/library_kept.py +9 -1
  43. package/modules/localmodels/library_model.py +28 -1
  44. package/modules/localmodels/library_poly.py +109 -11
  45. package/modules/localmodels/library_pricing.py +12 -3
  46. package/modules/localmodels/library_serve.py +162 -75
  47. package/modules/localmodels/library_smoke.py +63 -5
  48. package/modules/localmodels/library_state.py +3 -2
  49. package/modules/localmodels/library_status.py +8 -1
  50. package/modules/localmodels/llm_rank.py +13 -8
  51. package/modules/localmodels/metal.py +1 -2
  52. package/modules/localmodels/plan_envelope.py +29 -11
  53. package/modules/localmodels/planning/budget.py +14 -12
  54. package/modules/localmodels/planning/memory_pools.py +7 -1
  55. package/modules/localmodels/privacy_acceptance.py +6 -5
  56. package/modules/localmodels/py.typed +0 -0
  57. package/modules/localmodels/quant_formats.py +1 -1
  58. package/modules/localmodels/recommend_cli.py +1 -1
  59. package/modules/localmodels/remote_ops_common.py +12 -2
  60. package/modules/localmodels/remote_ops_launchd.py +8 -1
  61. package/modules/localmodels/runtime_process.py +1 -1
  62. package/modules/localmodels/service_deployment.py +2 -4
  63. package/modules/localmodels/service_probe.py +59 -13
  64. package/modules/localmodels/setup_inspection.py +72 -70
  65. package/modules/localmodels/setup_text.py +7 -56
  66. package/modules/localmodels/sidecar_downloads.py +460 -0
  67. package/modules/localmodels/sidecar_http.py +452 -0
  68. package/modules/localmodels/sidecar_state.py +516 -0
  69. package/modules/localmodels/speech_admission.py +33 -4
  70. package/modules/localmodels/speech_catalog.py +23 -0
  71. package/modules/localmodels/speech_cli.py +10 -2
  72. package/modules/localmodels/speech_jobs.py +120 -384
  73. package/modules/localmodels/speech_server.py +187 -77
  74. package/modules/localmodels/speech_state.py +90 -454
  75. package/modules/localmodels/speech_workers.py +51 -162
  76. package/modules/localmodels/stack.py +18 -0
  77. package/modules/localmodels/stack_args.py +6 -6
  78. package/modules/localmodels/stack_auto.py +1 -1
  79. package/modules/localmodels/stack_aux_gpu.py +1 -1
  80. package/modules/localmodels/stack_cleanup.py +21 -18
  81. package/modules/localmodels/stack_cli.py +6 -2
  82. package/modules/localmodels/stack_compose.py +11 -4
  83. package/modules/localmodels/stack_debug.py +1 -2
  84. package/modules/localmodels/stack_decision.py +4 -4
  85. package/modules/localmodels/stack_doctor.py +2 -2
  86. package/modules/localmodels/stack_down.py +19 -14
  87. package/modules/localmodels/stack_events.py +1 -1
  88. package/modules/localmodels/stack_gpu_memory.py +1 -1
  89. package/modules/localmodels/stack_hardware.py +3 -3
  90. package/modules/localmodels/stack_mcp.py +1 -2
  91. package/modules/localmodels/stack_picks.py +1 -1
  92. package/modules/localmodels/stack_plan.py +9 -9
  93. package/modules/localmodels/stack_ports.py +32 -4
  94. package/modules/localmodels/stack_rollback.py +1 -1
  95. package/modules/localmodels/stack_run.py +1 -1
  96. package/modules/localmodels/stack_suite.py +61 -12
  97. package/modules/localmodels/stack_up.py +51 -1
  98. package/modules/localmodels/stack_view_agent.py +1 -1
  99. package/modules/localmodels/stack_view_serve.py +0 -2
  100. package/modules/localmodels/stack_view_words.py +2 -2
  101. package/modules/localmodels/stack_warm.py +2 -2
  102. package/modules/localmodels/stack_whatif.py +524 -41
  103. package/modules/localmodels/stack_whatif_html.py +903 -0
  104. package/modules/localmodels/startlux-decide-83fe6c7d.txt +2 -2
  105. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.7.txt → strata-poly-serve-0.2.20-poly.9.txt} +1 -1
  106. package/modules/localmodels/strata_poly_server.py +251 -3
  107. package/modules/localmodels/suite.py +137 -5
  108. package/modules/localmodels/tts-moss.txt +321 -0
  109. package/modules/localmodels/tts_admission.py +381 -0
  110. package/modules/localmodels/tts_backend_speechcpp.py +487 -0
  111. package/modules/localmodels/tts_catalog.py +279 -0
  112. package/modules/localmodels/tts_cli.py +352 -0
  113. package/modules/localmodels/tts_http.py +623 -0
  114. package/modules/localmodels/tts_jobs.py +526 -0
  115. package/modules/localmodels/tts_model.py +591 -0
  116. package/modules/localmodels/tts_moss_presets.json +1 -0
  117. package/modules/localmodels/tts_serve.py +451 -0
  118. package/modules/localmodels/tts_server.py +1 -1
  119. package/modules/localmodels/tts_sidecar.py +788 -0
  120. package/modules/localmodels/tts_state.py +400 -0
  121. package/modules/localmodels/tts_worker_kokoro.py +463 -0
  122. package/modules/localmodels/tts_worker_moss.py +748 -0
  123. package/modules/localmodels/tts_workers.py +696 -0
  124. package/modules/localmodels/vision.py +5 -3
  125. package/modules/localmodels/web/view/ASSET-SOURCES.md +4 -7
  126. package/modules/localmodels/web/view/view.css +0 -1
  127. package/modules/localmodels/web/view/view.js +2 -5
  128. package/modules/localmodels/web/whatif/app.js +730 -0
  129. package/modules/localmodels/web/whatif/page.html +1172 -0
  130. package/modules/localmodels/web/whatif/sim.js +303 -0
  131. package/modules/localmodels/windows_job.py +179 -11
  132. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/METADATA +14 -0
  133. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/RECORD +132 -109
  134. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/LICENSE +201 -0
  135. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/NOTICE +126 -0
  136. package/package.json +11 -2
  137. package/tool.json +1 -1
  138. package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +0 -94
  139. package/modules/localmodels/fixtures/stack-research-demo-plan.json +0 -1059
  140. package/modules/localmodels/stack_research.py +0 -716
  141. package/modules/localmodels/stack_research_demo.py +0 -125
  142. package/modules/localmodels/stack_research_plan.py +0 -146
  143. package/modules/localmodels/web/index.html +0 -2605
  144. package/modules/localmodels/web/sizecalc/app.js +0 -1306
  145. package/modules/localmodels/web/sizecalc/calc.js +0 -269
  146. package/modules/localmodels/web/sizecalc/page.html +0 -520
  147. package/modules/localmodels/web/view/logo-claude.svg +0 -3
  148. package/modules/localmodels/web/view/logo-codex.png +0 -0
  149. package/modules/simplex_localmodels-0.1.0.dev102.dist-info/METADATA +0 -9
  150. package/modules/simplex_localmodels-0.1.0.dev102.dist-info/licenses/NOTICE +0 -68
  151. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/WHEEL +0 -0
  152. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/entry_points.txt +0 -0
  153. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -15,9 +15,9 @@ from __future__ import annotations
15
15
  import contextlib
16
16
  import os
17
17
  import shutil
18
+ import time
18
19
  from dataclasses import dataclass
19
20
  from pathlib import Path
20
- from typing import cast
21
21
 
22
22
  from localmodels import (
23
23
  app,
@@ -35,10 +35,13 @@ from localmodels import (
35
35
  library_status,
36
36
  metal,
37
37
  plan_envelope,
38
+ sidecar_state,
38
39
  speech_admission,
40
+ speech_state,
39
41
  stack_lifecycle,
40
42
  stack_ports,
41
43
  stack_warm,
44
+ tts_state,
42
45
  )
43
46
  from localmodels.library_elastic import ElasticPlan, ElasticRoomError
44
47
  from localmodels.library_model import LibraryError, LoadStep, Row, problem_from_error, progress
@@ -51,6 +54,8 @@ from localmodels.transport import Executor
51
54
 
52
55
  LOAD_STEPS = deploy.STEPS
53
56
  MAX_OOM_RETRIES = 2
57
+ _METAL_UNLOAD_SETTLE_POLLS = 6
58
+ _METAL_UNLOAD_SETTLE_S = 0.5
54
59
  OOM = (
55
60
  "out of memory",
56
61
  "cudamalloc failed",
@@ -142,6 +147,13 @@ def _reserved(skip: str) -> dict[str, int]:
142
147
  for model, (job, alive) in library_state.jobs().items():
143
148
  if alive and job["kind"] == "load" and model != skip:
144
149
  found[job["pool"]] = found.get(job["pool"], 0) + job["memory_bytes"]
150
+ state_dir = hosts.state_dir()
151
+ for rec in (
152
+ tts_state.load_runtime_record(state_dir),
153
+ speech_state.load_runtime_record(state_dir),
154
+ ):
155
+ for pool, used in sidecar_state.loading_vram_by_pool(rec).items():
156
+ found[pool] = found.get(pool, 0) + used
145
157
  return found
146
158
 
147
159
 
@@ -379,6 +391,11 @@ def demote_speech_if_holding_pool(state_dir: Path | None, pool_id: str) -> bool:
379
391
  return speech_admission.demote_speech_if_holding_pool(state_dir, pool_id)
380
392
 
381
393
 
394
+ def demote_tts_if_holding_pool(state_dir: Path | None, pool_id: str) -> bool:
395
+ """Demote a running TTS sidecar (RANK 3) to CPU when it holds memory on ``pool_id``."""
396
+ return tts_state.demote_if_holding_pool(state_dir, pool_id, reason="yielded_to_llm")
397
+
398
+
382
399
  def _serve_elastic_plan(
383
400
  model: Model,
384
401
  record: Record,
@@ -389,7 +406,7 @@ def _serve_elastic_plan(
389
406
  *,
390
407
  use_jinja: bool,
391
408
  ) -> tuple[HostFacts, ElasticPlan]:
392
- """Price the elastic plan for ``_serve``, demoting GPU-resident speech first when tight."""
409
+ """Price the elastic plan for ``_serve``, demoting TTS (RANK 3) then STT (RANK 2) when tight."""
393
410
 
394
411
  def price(seen: HostFacts) -> ElasticPlan:
395
412
  now = memory_pools.live(seen, _reserved(model.id))
@@ -409,15 +426,15 @@ def _serve_elastic_plan(
409
426
  try:
410
427
  elastic = price(facts)
411
428
  except deploy.AgentMemoryError as exc:
412
- if demote_speech_if_holding_pool(hosts.state_dir(), record["pool"]):
413
- fresh = library_jobs.probe()
414
- try:
415
- return fresh, price(fresh)
416
- except deploy.AgentMemoryError as retry_exc:
417
- raise _fail(
418
- record, _no_room_error(model, retry_exc, record["pool"], failed=True)
419
- ) from None
420
- raise _fail(record, _no_room_error(model, exc, record["pool"], failed=True)) from None
429
+ last_exc: deploy.AgentMemoryError = exc
430
+ for demoter in (demote_tts_if_holding_pool, demote_speech_if_holding_pool):
431
+ if demoter(hosts.state_dir(), record["pool"]):
432
+ fresh = library_jobs.probe()
433
+ try:
434
+ return fresh, price(fresh)
435
+ except deploy.AgentMemoryError as retry_exc:
436
+ last_exc = retry_exc
437
+ raise _fail(record, _no_room_error(model, last_exc, record["pool"], failed=True)) from None
421
438
  except engines.CudaDriverError as exc:
422
439
  raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc), failed=True) from None
423
440
  except engines.EngineUnavailableError as exc:
@@ -438,11 +455,17 @@ def _serve_elastic_plan(
438
455
  can_force=False,
439
456
  ),
440
457
  ) from None
441
- if elastic.degraded and demote_speech_if_holding_pool(hosts.state_dir(), record["pool"]):
442
- fresh = library_jobs.probe()
443
- with contextlib.suppress(deploy.AgentMemoryError, library_pricing.LiveMemoryUnavailable):
444
- return fresh, price(fresh)
445
- return facts, elastic
458
+ current_facts = facts
459
+ for demoter in (demote_tts_if_holding_pool, demote_speech_if_holding_pool):
460
+ if not elastic.degraded:
461
+ break
462
+ if demoter(hosts.state_dir(), record["pool"]):
463
+ fresh = library_jobs.probe()
464
+ with contextlib.suppress(
465
+ deploy.AgentMemoryError, library_pricing.LiveMemoryUnavailable
466
+ ):
467
+ current_facts, elastic = fresh, price(fresh)
468
+ return current_facts, elastic
446
469
 
447
470
 
448
471
  def _serve(
@@ -615,15 +638,15 @@ def _abandon(record: Record, run: Executor) -> None:
615
638
  library_state.save(record)
616
639
 
617
640
 
618
- def _admit(
619
- model: Model, record: Record, targets: list[Record], facts: HostFacts, ctx: LoadContext
620
- ) -> None:
621
- """Under ``locked()``: LOAD_NO_ROOM unless the model fits its pool in ``facts`` (probed
622
- under the same lock), less every live load's reservation, plus what ``targets`` and a
623
- stale server of the model itself give back. If speech holds VRAM/unified memory on the
624
- target pool and admission would fail or degrade posture, demote speech to CPU and re-probe
625
- first. The caller commits its own reservation before releasing the lock, so the next
626
- claimant sees it."""
641
+ @dataclass(frozen=True)
642
+ class _AdmitAttempt:
643
+ already_loaded: Row | None = None
644
+ claimed: tuple[Record, list[Record], HostFacts, int, list[Job]] | None = None
645
+ demote_pool: str | None = None
646
+ room_error: LibraryError | None = None
647
+
648
+
649
+ def _freed_for_targets(record: Record, targets: list[Record]) -> dict[str, int]:
627
650
  freed: dict[str, int] = {}
628
651
  catalog = library_pricing.entries()
629
652
  for target in [*targets, *([record] if record["state"] != "idle" else [])]:
@@ -638,23 +661,117 @@ def _admit(
638
661
  freed["system"] = freed.get("system", 0) + library_pricing.host_ram_bytes(
639
662
  target["plan"], catalog
640
663
  )
664
+ return freed
665
+
666
+
667
+ def _demote_next_voice_rank(pool_id: str, tried: set[int]) -> bool:
668
+ """Ask the next untried voice sidecar holding ``pool_id`` to yield (RANK 3 TTS before RANK 2 STT).
669
+
670
+ Called strictly outside ``library_state.locked()`` so voice sidecars that acquire the shared
671
+ admission lock under their in-process ``_cond`` can never deadlock with an LLM demote call.
672
+ """
673
+ for idx, demoter in enumerate((demote_tts_if_holding_pool, demote_speech_if_holding_pool)):
674
+ if idx in tried:
675
+ continue
676
+ tried.add(idx)
677
+ if demoter(hosts.state_dir(), pool_id):
678
+ return True
679
+ return False
680
+
681
+
682
+ def _try_claim_load_locked(
683
+ model: Model,
684
+ others: list[str],
685
+ base_dir: str,
686
+ load_ctx: LoadContext,
687
+ *,
688
+ can_demote: bool,
689
+ ) -> _AdmitAttempt:
690
+ """Under ``library_state.locked()``: validate, price room, and commit load claims atomically."""
691
+ library_state.refuse_busy(model.id, "load")
692
+ record = library_state.load(model.id)
693
+ if record is None:
694
+ raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
695
+ if missing := library_jobs.files_missing(record["plan"]):
696
+ raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
697
+ facts = library_jobs.probe()
698
+ url = str(record["plan"]["endpoint"]["base_url"])
699
+ if record["state"] == "loaded" and library_status.answering(url):
700
+ existing_reg = record.get("registration")
701
+ if existing_reg is None or existing_reg.get("kind") != "direct":
702
+ reg = library_direct.registration(model.id, record["plan"])
703
+ record["registration"] = reg
704
+ if pi_selector := reg.get("pi_model"):
705
+ record["pi_model"] = pi_selector
706
+ library_state.save(record)
707
+ row = library_status.model_row(library_status.Library.read(facts, base_dir), model.id)
708
+ return _AdmitAttempt(already_loaded=row)
709
+ if library_kept.retired(model.entry):
710
+ raise LibraryError(
711
+ "INVALID_STATE",
712
+ f"this version no longer ships {model.id}; remove it and download a current model",
713
+ )
714
+ targets: list[Record] = []
715
+ for other in others:
716
+ library_state.refuse_busy(other, "unload")
717
+ found = library_state.load(other)
718
+ if other != model.id and found is not None and found["state"] != "idle":
719
+ targets.append(found)
720
+ freed = _freed_for_targets(record, targets)
641
721
  try:
642
- elastic = _room(facts, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
722
+ elastic = _room(
723
+ facts, model, record, freed, force=load_ctx.force, ctx=load_ctx.ctx_override
724
+ )
643
725
  except LibraryError as exc:
644
- if exc.code == "LOAD_NO_ROOM" and demote_speech_if_holding_pool(
645
- hosts.state_dir(), record["pool"]
646
- ):
647
- fresh = library_jobs.probe()
648
- _room(fresh, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
649
- cast(dict[str, object], facts).clear()
650
- facts.update(fresh)
651
- return
652
- raise
653
- if elastic.degraded and demote_speech_if_holding_pool(hosts.state_dir(), record["pool"]):
726
+ if exc.code != "LOAD_NO_ROOM" or not can_demote:
727
+ raise
728
+ return _AdmitAttempt(demote_pool=record["pool"], room_error=exc)
729
+ if elastic.degraded and can_demote:
730
+ return _AdmitAttempt(demote_pool=record["pool"])
731
+ memory = record.get("memory_bytes") or memory_pools.memory_bytes(record["plan"])
732
+ port = _port(facts) # reserved with the claim: no concurrent load takes it too
733
+ claims = [library_state.acquire("load", model.id, record["pool"], memory, [], port=port)]
734
+ for target in targets:
735
+ claims.append(library_state.acquire("unload", target["id"], target["pool"], 0, []))
736
+ return _AdmitAttempt(claimed=(record, targets, facts, port, claims))
737
+
738
+
739
+ def _admit_and_claim(
740
+ model: Model,
741
+ others: list[str],
742
+ base_dir: str,
743
+ load_ctx: LoadContext,
744
+ ) -> _AdmitAttempt:
745
+ """Validate, admit (demoting lower-rank voice sidecars outside the lock), and claim atomically."""
746
+ tried_demoters: set[int] = set()
747
+ while True:
748
+ with library_state.locked(): # validate, admit and claim as one step
749
+ attempt = _try_claim_load_locked(
750
+ model, others, base_dir, load_ctx, can_demote=len(tried_demoters) < 2
751
+ )
752
+ if attempt.already_loaded is not None or attempt.claimed is not None:
753
+ return attempt
754
+ assert attempt.demote_pool is not None
755
+ if not _demote_next_voice_rank(attempt.demote_pool, tried_demoters):
756
+ if attempt.room_error is not None:
757
+ raise attempt.room_error from None
758
+ # Degraded posture fits and no untried voice sidecar yielded; re-enter once
759
+ # with can_demote=False to commit the degraded load claim atomically.
760
+
761
+
762
+ def _probe_after_unload(pool: str) -> HostFacts:
763
+ """Re-probe host facts after unloading a model; on Apple Silicon unified memory, wait briefly
764
+ when macOS VM pressure is still transiently at WARN right after freeing wired GPU pages."""
765
+ fresh = library_jobs.probe()
766
+ if pool != "unified" or not metal.supported(fresh):
767
+ return fresh
768
+ for _ in range(_METAL_UNLOAD_SETTLE_POLLS):
769
+ if fresh["ram"].get("pressure_level") != metal.PRESSURE_WARN:
770
+ break
771
+ if _METAL_UNLOAD_SETTLE_S > 0:
772
+ time.sleep(_METAL_UNLOAD_SETTLE_S)
654
773
  fresh = library_jobs.probe()
655
- _room(fresh, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
656
- cast(dict[str, object], facts).clear()
657
- facts.update(fresh)
774
+ return fresh
658
775
 
659
776
 
660
777
  def _row(model: Model, base_dir: str) -> Row:
@@ -680,41 +797,11 @@ def load(
680
797
  dict.fromkeys(library_pricing.find(m, library_pricing.entries()).id for m in unload)
681
798
  )
682
799
  load_ctx = LoadContext(force=force, ctx_override=ctx)
683
- targets: list[Record] = []
684
- with library_state.locked(): # validate, admit and claim as one step
685
- library_state.refuse_busy(model.id, "load")
686
- record = library_state.load(model.id)
687
- if record is None:
688
- raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
689
- if missing := library_jobs.files_missing(record["plan"]):
690
- raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
691
- facts = library_jobs.probe()
692
- url = str(record["plan"]["endpoint"]["base_url"])
693
- if record["state"] == "loaded" and library_status.answering(url):
694
- existing_reg = record.get("registration")
695
- if existing_reg is None or existing_reg.get("kind") != "direct":
696
- reg = library_direct.registration(model.id, record["plan"])
697
- record["registration"] = reg
698
- if pi_selector := reg.get("pi_model"):
699
- record["pi_model"] = pi_selector
700
- library_state.save(record)
701
- return library_status.model_row(library_status.Library.read(facts, base_dir), model.id)
702
- if library_kept.retired(model.entry):
703
- raise LibraryError(
704
- "INVALID_STATE",
705
- f"this version no longer ships {model.id}; remove it and download a current model",
706
- )
707
- for other in others:
708
- library_state.refuse_busy(other, "unload")
709
- found = library_state.load(other)
710
- if other != model.id and found is not None and found["state"] != "idle":
711
- targets.append(found)
712
- _admit(model, record, targets, facts, load_ctx)
713
- memory = record.get("memory_bytes") or memory_pools.memory_bytes(record["plan"])
714
- port = _port(facts) # reserved with the claim: no concurrent load takes it too
715
- claims = [library_state.acquire("load", model.id, record["pool"], memory, [], port=port)]
716
- for target in targets:
717
- claims.append(library_state.acquire("unload", target["id"], target["pool"], 0, []))
800
+ attempt = _admit_and_claim(model, others, base_dir, load_ctx)
801
+ if attempt.already_loaded is not None:
802
+ return attempt.already_loaded
803
+ assert attempt.claimed is not None
804
+ record, targets, facts, port, claims = attempt.claimed
718
805
  library_jobs.cancel_on_sigterm()
719
806
  executor = library_jobs.executor()
720
807
  refresh = bool(targets) or record["state"] != "idle" # memory was freed: probe again
@@ -730,7 +817,7 @@ def load(
730
817
  _serve(
731
818
  model,
732
819
  record,
733
- library_jobs.probe() if refresh else facts,
820
+ _probe_after_unload(record["pool"]) if refresh else facts,
734
821
  executor,
735
822
  port,
736
823
  handle,
@@ -19,10 +19,13 @@ from pathlib import Path
19
19
 
20
20
  from localmodels import (
21
21
  app,
22
+ chat_template,
22
23
  custom_hub,
23
24
  draft_spec,
24
25
  hosts,
25
26
  library_jobs,
27
+ library_kept,
28
+ library_poly,
26
29
  library_pricing,
27
30
  library_serve,
28
31
  library_state,
@@ -91,6 +94,12 @@ def _strip_flags(argv: list[str], names: set[str], valued: set[str]) -> list[str
91
94
  return out
92
95
 
93
96
 
97
+ def _unwrap_launcher(argv: list[str]) -> list[str]:
98
+ if len(argv) >= 3 and Path(argv[1].replace("\\", "/")).name == chat_template.SLOT_CACHE:
99
+ return argv[2:]
100
+ return argv
101
+
102
+
94
103
  def _build_smoke_plan(
95
104
  record: Record,
96
105
  facts: HostFacts,
@@ -114,11 +123,11 @@ def _build_smoke_plan(
114
123
  deploy_dir = f"{base}/deployments/{smoke_name}"
115
124
  api_key_file = f"{deploy_dir}/api-key"
116
125
 
117
- argv = list(plan["service"]["argv"])
126
+ argv = _unwrap_launcher(list(plan["service"]["argv"]))
118
127
  argv = _strip_flags(
119
128
  argv,
120
- names={"--jinja", "--no-warmup", "--mmproj-offload"},
121
- valued={"--mmproj", "--chat-template-file", "--reasoning-budget"},
129
+ names={"--jinja", "--no-warmup", "--mmproj-offload", "--no-mmproj-offload"},
130
+ valued={"--mmproj", "--chat-template-file", "--reasoning-budget", "--slot-save-path"},
122
131
  )
123
132
  argv = _replace_flag(argv, ("-c", "--ctx-size"), "-c", str(ctx))
124
133
  argv = _replace_flag(argv, ("-np", "--parallel"), "-np", "1")
@@ -223,16 +232,65 @@ def _restore_verification(model_id: str, prior: VerificationRecord | None) -> No
223
232
  library_state.save(current)
224
233
 
225
234
 
226
- def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
227
- """Run an isolated ephemeral smoke-test at ``ctx`` tokens and persist ``verification``."""
235
+ def _validate_smoke_target(model_id: str, ctx: int) -> library_pricing.Model:
228
236
  if isinstance(ctx, bool) or ctx <= 0:
229
237
  raise LibraryError("INVALID_STATE", "--ctx must be a positive integer")
230
238
  model = library_pricing.find(model_id, library_pricing.entries())
239
+ if model.entry.runtime != "llama.cpp":
240
+ raise LibraryError(
241
+ "INVALID_STATE",
242
+ f"smoke-test supports llama.cpp models only ({model.id} uses {model.entry.runtime})",
243
+ )
244
+ if library_kept.retired(model.entry):
245
+ raise LibraryError(
246
+ "INVALID_STATE",
247
+ f"this version no longer ships {model.id}; remove it and download a current model",
248
+ )
249
+ return model
250
+
251
+
252
+ def _record_runtime_issue(record: Record) -> str | None:
253
+ custom = record.get("custom")
254
+ if custom is not None and (fmt := custom.get("format")) not in (None, "gguf"):
255
+ return str(fmt)
256
+ plan = record["plan"]
257
+ if library_poly.is_poly_plan(plan):
258
+ return "strata-poly"
259
+ launch_runtime = str(plan["launch"].get("runtime") or "")
260
+ if launch_runtime and launch_runtime != "llama.cpp":
261
+ return launch_runtime
262
+ build = str(plan["engine"].get("build") or "")
263
+ if build.startswith("strata"):
264
+ return "strata"
265
+ if build.startswith("mlx"):
266
+ return "mlx-lm"
267
+ source = str(plan["engine"].get("source") or "")
268
+ if source in ("python", "venv"):
269
+ return source
270
+ argv = _unwrap_launcher(list(plan["service"]["argv"]))
271
+ binary = str(plan["engine"].get("binary") or "")
272
+ if not argv or (binary and argv[0] != binary):
273
+ return "an unsupported launcher"
274
+ return None
275
+
276
+
277
+ def _validate_smoke_record(model_id: str, record: Record) -> None:
278
+ if issue := _record_runtime_issue(record):
279
+ raise LibraryError(
280
+ "INVALID_STATE",
281
+ f"smoke-test supports llama.cpp models only ({model_id} uses {issue})",
282
+ )
283
+
284
+
285
+ def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
286
+ """Run an isolated ephemeral smoke-test at ``ctx`` tokens and persist ``verification``."""
287
+ model = _validate_smoke_target(model_id, ctx)
231
288
  with library_state.locked():
232
289
  library_state.refuse_busy(model.id, "smoke_test")
233
290
  record = library_state.load(model.id)
234
291
  if record is None:
235
292
  raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
293
+ _validate_smoke_record(model.id, record)
236
294
  if missing := library_jobs.files_missing(record["plan"]):
237
295
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
238
296
  facts = library_jobs.probe()
@@ -199,9 +199,10 @@ def pid_path(model: str) -> Path:
199
199
 
200
200
 
201
201
  @contextmanager
202
- def locked() -> Iterator[None]:
202
+ def locked(state_dir: Path | None = None) -> Iterator[None]:
203
203
  """The one lock every state transition holds, briefly."""
204
- with hosts.file_lock(root() / ".lock"):
204
+ lock_root = root() if state_dir is None else state_dir / "library"
205
+ with hosts.file_lock(lock_root / ".lock"):
205
206
  yield
206
207
 
207
208
 
@@ -64,6 +64,7 @@ from localmodels.library_model import (
64
64
  VerificationFailureKind,
65
65
  VerificationMeta,
66
66
  VerificationStatus,
67
+ disambiguate_row_names,
67
68
  sanitize_problem,
68
69
  )
69
70
  from localmodels.library_pricing import Model, Priced
@@ -492,7 +493,12 @@ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None
492
493
  else (1 if engine == "strata" else library_pricing.posture().slots)
493
494
  )
494
495
  )
495
- if plan is not None and engine in ("polystrata", "strata"):
496
+ if (
497
+ plan is not None
498
+ and engine in ("polystrata", "strata")
499
+ and found["pool"] != "unified"
500
+ and memory_pools.pool_of(plan) != "unified"
501
+ ):
496
502
  host_ram = library_pricing.host_ram_bytes(plan, lib.catalog)
497
503
  if host_ram > 0:
498
504
  found["host_ram_bytes"] = host_ram
@@ -1147,6 +1153,7 @@ def host(lib: Library) -> Host:
1147
1153
  def build(lib: Library) -> Status:
1148
1154
  models = lib.models()
1149
1155
  rows = [row(lib, m) for m in models]
1156
+ disambiguate_row_names(rows)
1150
1157
  now = memory_pools.live(lib.facts, lib.reserved())
1151
1158
  candidates = [
1152
1159
  m
@@ -1,6 +1,6 @@
1
1
  """Which catalog LLM is the default for a budget: a gate, then an order.
2
2
 
3
- The gate is the agent posture — since roadmap decision 26 a window of at least 64K for the
3
+ The gate is the agent posture — a window of at least 64K for the
4
4
  posture's slots, weights and KV resident. Gated entries are ordered by ``quality.score``, which
5
5
  for scored entries is the installed SimplexAI score (docs/local-models/model-scoring.md),
6
6
  then by predicted decode speed; ``choose`` applies the user's scenario (``--prefer``).
@@ -12,6 +12,7 @@ from __future__ import annotations
12
12
 
13
13
  from collections.abc import Iterable, Mapping
14
14
  from dataclasses import dataclass
15
+ from typing import Literal
15
16
 
16
17
  from localmodels import engines, metal, vision
17
18
  from localmodels.catalog import (
@@ -26,7 +27,7 @@ from localmodels.catalog import (
26
27
  validated_here,
27
28
  )
28
29
  from localmodels.context_policy import AGENT, AgentPosture
29
- from localmodels.estimator import HardwareBudget, PhysicsRefusal, llama_host_bytes
30
+ from localmodels.estimator import Backend, HardwareBudget, PhysicsRefusal, llama_host_bytes
30
31
  from localmodels.plan_envelope import PlanError
31
32
  from localmodels.planning.budget import HARNESS_RAM, RAM_FLOOR, host_ram
32
33
  from localmodels.probe import HostFacts
@@ -35,7 +36,7 @@ from localmodels.probe import HostFacts
35
36
  # rarely swap): a challenger with another engine must beat the llama.cpp pick by at least this.
36
37
  TIE_BAND = 3
37
38
  # Scores within this band are statistically indistinguishable (AIHOT: under 1 point is a coin
38
- # flip; roadmap decision 71): break ties by decode speed, and let prefer_over_llama recipes win.
39
+ # flip): break ties by decode speed, and let prefer_over_llama recipes win.
39
40
  COIN_FLIP = 1
40
41
  # --prefer fast: the fastest fitting model whose score is within this many points of the best.
41
42
  FAST_QUALITY_BAND = 5
@@ -90,12 +91,12 @@ PRODUCT_DEFAULTS = {
90
91
 
91
92
 
92
93
  # The installed SimplexAI score at which a validated model takes over from the Mac ladder
93
- # (roadmap decision 40, 2026-11-09: intelligence first): 50 is the AIHOT reference-model mean.
94
+ # (intelligence first): 50 is the reference-model mean.
94
95
  # A 24 GB Mac with the memory free holds Qwen3.8-27B UD-IQ3_S (52); one under desktop load, and
95
96
  # every 16 GB Mac, stays on the ladder rather than a lower-scored model such as Qwen3.6-35B-A3B.
96
97
  MAC_DEFAULT_YIELD_SCORE = 50
97
98
 
98
- # The Mac small-memory ladder (roadmap decisions 57, 61 and 68, user-selected; replaces decision
99
+ # The Mac small-memory ladder (user-selected; replaces earlier
99
100
  # 39's LFM3-1.7B): on every Apple Silicon Mac of MAC_LADDER_MIN_BYTES or more, while no validated
100
101
  # model scoring MAC_DEFAULT_YIELD_SCORE or more fits, --llm auto tries Ornith 1.5 9B Q4_K_M first
101
102
  # (fits 16 GB idle Macs and busy 24 GB+ Macs from ~12.5 GiB available), then falls back to
@@ -209,7 +210,7 @@ def agent_ready(
209
210
  budget: HardwareBudget,
210
211
  posture: AgentPosture = AGENT,
211
212
  ) -> bool:
212
- """The gate every recommended LLM passes before it is ranked (roadmap decision 21): the
213
+ """The gate every recommended LLM passes before it is ranked: the
213
214
  agent posture fits this budget, a window of at least ``posture.floor`` (64K) shared by
214
215
  ``posture.slots`` concurrent requests with weights and KV resident. Long context is a
215
216
  precondition of agent work, so a model that cannot hold it is never the default."""
@@ -336,7 +337,11 @@ def automatic_fit(
336
337
 
337
338
 
338
339
  def rank_key(
339
- entry: CatalogEntry, variant: QuantVariant, budget: HardwareBudget, *, backend: str = "auto"
340
+ entry: CatalogEntry,
341
+ variant: QuantVariant,
342
+ budget: HardwareBudget,
343
+ *,
344
+ backend: Backend | Literal["auto"] = "auto",
340
345
  ) -> tuple[int, float]:
341
346
  """How gated LLMs are ordered: agent capability (``quality.score``) first, predicted decode
342
347
  tok/s second. Time to first token has no separate estimator: prefill and decode are both
@@ -395,7 +400,7 @@ def recommended_entry(
395
400
  budget: HardwareBudget,
396
401
  entries: tuple[CatalogEntry, ...],
397
402
  *,
398
- backend: str = "auto",
403
+ backend: Backend | Literal["auto"] = "auto",
399
404
  ladder: tuple[str, ...] = (),
400
405
  ) -> tuple[CatalogEntry, str] | None:
401
406
  """Pick among resident entries that pass ``agent_ready`` (64K shared by two requests).
@@ -28,8 +28,7 @@ METAL_UUID = "metal-0" # service_probe.METAL_UUID labels the processes it finds
28
28
  # HARNESS_RAM (a test keeps them equal; importing them here would cycle through deploy).
29
29
  HOST_KEEP_BYTES = 2 * GIB
30
30
  # Apple's default recommendedMaxWorkingSetSize (iogpu.wired_limit_mb unset) as Macs reported it:
31
- # (total, working set). M4 16 GB and M6 24 GB read 74.0% (evidence/2026-10-30-macos-metal,
32
- # evidence/2026-11-05-macmini-64k); oMLX 0.7.4 records 107.5 GiB on a 128 GiB MacBook
31
+ # (total, working set). M4 16 GB and M6 24 GB read 74.0% (measured on Apple Silicon Macs); oMLX 0.7.4 records 107.5 GiB on a 128 GiB MacBook
33
32
  # (omlx/cluster/node_role.py); macOS 27 on the 256 GB M5 Ultra read 222.7 GiB (MT1). A simulated
34
33
  # Mac interpolates the share linearly in between; a real one uses its own probe reading, which
35
34
  # also shows a raised sysctl (local-119: 249036 MiB set, the same value read, 2026-11-09).
@@ -5,6 +5,8 @@ argv; this module adds where the deployment lives, its service identity, endpoin
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
+ import contextlib
9
+ import contextvars
8
10
  import datetime as dt
9
11
  import functools
10
12
  import hashlib
@@ -17,13 +19,13 @@ import time
17
19
  import urllib.error
18
20
  import urllib.parse
19
21
  import urllib.request
20
- from collections.abc import Callable, Mapping, Sequence
22
+ from collections.abc import Callable, Iterator, Mapping, Sequence
21
23
  from dataclasses import dataclass
22
24
  from pathlib import Path
23
25
  from typing import TypedDict
24
26
 
25
27
  from localmodels import catalog as cat
26
- from localmodels import region
28
+ from localmodels import deployment_lifecycle, region
27
29
  from localmodels.contracts import decode
28
30
  from localmodels.planning.budget import gib
29
31
  from localmodels.probe import HostFacts
@@ -324,13 +326,6 @@ def service_name(base_dir: str, name: str) -> str:
324
326
  return f"localmodels-{root_tag(base_dir)}-{name}"
325
327
 
326
328
 
327
- def _same_dir(a: str, b: str) -> bool:
328
- def norm(path: str) -> str:
329
- return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
330
-
331
- return norm(a) == norm(b)
332
-
333
-
334
329
  def resolved_name(model_id: str, port: int, base_dir: str, taken: Mapping[str, str]) -> str:
335
330
  """The deployment name under ``base_dir``. ``taken`` maps each recorded deployment's name to
336
331
  its directory. A name another base directory already uses gets this directory's tag, so two
@@ -339,9 +334,9 @@ def resolved_name(model_id: str, port: int, base_dir: str, taken: Mapping[str, s
339
334
  root = f"{base_dir.rstrip('/')}/deployments"
340
335
  tag = hashlib.sha256(os.path.normpath(os.path.expanduser(base_dir)).encode()).hexdigest()[:6]
341
336
  tagged = f"{plain}-{tag}"
342
- if tagged in taken and _same_dir(taken[tagged], f"{root}/{tagged}"):
337
+ if tagged in taken and deployment_lifecycle.same_dir(taken[tagged], f"{root}/{tagged}"):
343
338
  return tagged
344
- if plain in taken and not _same_dir(taken[plain], f"{root}/{plain}"):
339
+ if plain in taken and not deployment_lifecycle.same_dir(taken[plain], f"{root}/{plain}"):
345
340
  return tagged
346
341
  return plain
347
342
 
@@ -410,10 +405,33 @@ def port_holder(facts: HostFacts, port: int) -> str | None:
410
405
  return None
411
406
 
412
407
 
408
+ _PORTS_ASSUMED_FREE: contextvars.ContextVar[bool] = contextvars.ContextVar(
409
+ "localmodels_ports_assumed_free", default=False
410
+ )
411
+
412
+
413
+ @contextlib.contextmanager
414
+ def assume_ports_free() -> Iterator[None]:
415
+ """Plan as if every loopback port were free (stack_ports.port_state and loopback_listening,
416
+ require_free_port): how setup inspect tells what else, if anything, blocks a host whose plan
417
+ was refused only for busy or unconfirmed ports. Never used for a plan that is applied."""
418
+ token = _PORTS_ASSUMED_FREE.set(True)
419
+ try:
420
+ yield
421
+ finally:
422
+ _PORTS_ASSUMED_FREE.reset(token)
423
+
424
+
425
+ def ports_assumed_free() -> bool:
426
+ return _PORTS_ASSUMED_FREE.get()
427
+
428
+
413
429
  def require_free_port(
414
430
  facts: HostFacts, port: int, *, role: str = "", fix: str = "pick a free port"
415
431
  ) -> None:
416
432
  """Refuse a port another server answers on, naming that server and how to get past it."""
433
+ if ports_assumed_free():
434
+ return
417
435
  if (holder := port_holder(facts, port)) is not None:
418
436
  raise PlanError(
419
437
  f"port {port} for {role} already has a server ({holder}); it is not part of this "