@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +138 -97
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +5 -1
  11. package/modules/localmodels/catalog.json +51 -10
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines.json +57 -1
  22. package/modules/localmodels/engines.py +6 -2
  23. package/modules/localmodels/estimator.py +21 -7
  24. package/modules/localmodels/frontend.py +4 -4
  25. package/modules/localmodels/gateway.py +14 -4
  26. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  27. package/modules/localmodels/gateway_bifrost.py +70 -57
  28. package/modules/localmodels/gateway_probe.py +3 -4
  29. package/modules/localmodels/gguf.py +7 -0
  30. package/modules/localmodels/harness.py +24 -25
  31. package/modules/localmodels/harness_gateway.py +19 -10
  32. package/modules/localmodels/harness_probe.py +33 -6
  33. package/modules/localmodels/hosts.py +73 -9
  34. package/modules/localmodels/install.py +36 -6
  35. package/modules/localmodels/library_cli.py +179 -0
  36. package/modules/localmodels/library_convert.py +132 -0
  37. package/modules/localmodels/library_gateway.py +471 -0
  38. package/modules/localmodels/library_jobs.py +314 -0
  39. package/modules/localmodels/library_model.py +246 -0
  40. package/modules/localmodels/library_pricing.py +347 -0
  41. package/modules/localmodels/library_serve.py +348 -0
  42. package/modules/localmodels/library_state.py +373 -0
  43. package/modules/localmodels/library_status.py +349 -0
  44. package/modules/localmodels/llm_rank.py +16 -2
  45. package/modules/localmodels/memcalc.py +7 -30
  46. package/modules/localmodels/metal.py +26 -0
  47. package/modules/localmodels/plan_envelope.py +4 -1
  48. package/modules/localmodels/preparation.py +49 -0
  49. package/modules/localmodels/probe.py +8 -8
  50. package/modules/localmodels/process_identity.py +536 -9
  51. package/modules/localmodels/quant_formats.py +123 -0
  52. package/modules/localmodels/recommend_cli.py +8 -4
  53. package/modules/localmodels/records.py +1 -0
  54. package/modules/localmodels/remote_ops.py +104 -6
  55. package/modules/localmodels/remote_ops_download.py +17 -2
  56. package/modules/localmodels/remote_ops_prepare.py +406 -0
  57. package/modules/localmodels/remote_ops_remove.py +40 -7
  58. package/modules/localmodels/remote_ops_service.py +110 -8
  59. package/modules/localmodels/remote_ops_verify.py +15 -2
  60. package/modules/localmodels/runtime_auth.py +31 -1
  61. package/modules/localmodels/runtime_cli.py +3 -4
  62. package/modules/localmodels/runtime_io.py +50 -6
  63. package/modules/localmodels/service_autostart.py +45 -1
  64. package/modules/localmodels/service_control.py +13 -0
  65. package/modules/localmodels/service_deployment.py +12 -3
  66. package/modules/localmodels/service_jobs.py +33 -4
  67. package/modules/localmodels/service_probe.py +67 -13
  68. package/modules/localmodels/service_stop.py +152 -0
  69. package/modules/localmodels/service_worker.py +9 -1
  70. package/modules/localmodels/services_cli.py +50 -6
  71. package/modules/localmodels/setup_inspection.py +34 -25
  72. package/modules/localmodels/setup_text.py +118 -0
  73. package/modules/localmodels/sizecalc.py +625 -0
  74. package/modules/localmodels/sizecalc_cli.py +249 -0
  75. package/modules/localmodels/stack.py +69 -17
  76. package/modules/localmodels/stack_args.py +91 -19
  77. package/modules/localmodels/stack_auto.py +78 -0
  78. package/modules/localmodels/stack_binding.py +23 -35
  79. package/modules/localmodels/stack_card.py +195 -0
  80. package/modules/localmodels/stack_cleanup.py +379 -0
  81. package/modules/localmodels/stack_clients.py +4 -1
  82. package/modules/localmodels/stack_compose.py +150 -194
  83. package/modules/localmodels/stack_console.py +2 -0
  84. package/modules/localmodels/stack_decision.py +3 -2
  85. package/modules/localmodels/stack_down.py +189 -0
  86. package/modules/localmodels/stack_events.py +54 -0
  87. package/modules/localmodels/stack_hardware.py +22 -23
  88. package/modules/localmodels/stack_journal.py +29 -8
  89. package/modules/localmodels/stack_ledger.py +411 -0
  90. package/modules/localmodels/stack_lifecycle.py +162 -167
  91. package/modules/localmodels/stack_llm_ram.py +57 -5
  92. package/modules/localmodels/stack_memory.py +721 -0
  93. package/modules/localmodels/stack_picks.py +139 -0
  94. package/modules/localmodels/stack_plan.py +140 -22
  95. package/modules/localmodels/stack_ports.py +22 -0
  96. package/modules/localmodels/stack_preflight.py +699 -0
  97. package/modules/localmodels/stack_review.py +123 -5
  98. package/modules/localmodels/stack_rollback.py +2 -0
  99. package/modules/localmodels/stack_route.py +256 -0
  100. package/modules/localmodels/stack_run.py +11 -0
  101. package/modules/localmodels/stack_suite.py +102 -17
  102. package/modules/localmodels/stack_summary.py +65 -4
  103. package/modules/localmodels/stack_try.py +354 -0
  104. package/modules/localmodels/stack_try_client.py +194 -0
  105. package/modules/localmodels/stack_try_docs.py +139 -0
  106. package/modules/localmodels/stack_up.py +8 -1
  107. package/modules/localmodels/stack_update.py +29 -4
  108. package/modules/localmodels/stack_verify.py +3 -1
  109. package/modules/localmodels/stack_view.py +10 -11
  110. package/modules/localmodels/stack_view_apply.py +4 -2
  111. package/modules/localmodels/stack_view_events.py +2 -1
  112. package/modules/localmodels/stack_view_serve.py +3 -0
  113. package/modules/localmodels/stack_view_text.py +1 -1
  114. package/modules/localmodels/stack_view_words.py +4 -1
  115. package/modules/localmodels/stack_warm.py +574 -0
  116. package/modules/localmodels/stack_whatif.py +558 -0
  117. package/modules/localmodels/suite.py +48 -39
  118. package/modules/localmodels/tool_archive.py +40 -0
  119. package/modules/localmodels/tools.json +8 -0
  120. package/modules/localmodels/transport.py +1 -0
  121. package/modules/localmodels/vision.py +8 -1
  122. package/modules/localmodels/web/sizecalc/app.js +431 -0
  123. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  124. package/modules/localmodels/web/sizecalc/page.html +362 -0
  125. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  126. package/modules/localmodels/web/view/i18n.js +1 -1
  127. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  128. package/modules/localmodels/web/view/logo-codex.png +0 -0
  129. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  130. package/modules/localmodels/web/view/view.css +4 -0
  131. package/modules/localmodels/web/view/view.js +15 -6
  132. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/METADATA +1 -1
  133. package/modules/simplex_localmodels-0.1.0.dev35.dist-info/RECORD +241 -0
  134. package/package.json +1 -1
  135. package/tool.json +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  137. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/WHEEL +0 -0
  138. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/entry_points.txt +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/NOTICE +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,347 @@
1
+ """What each library model costs on this computer, priced by the stack's own planner.
2
+
3
+ Every figure comes from ``deploy.build_plan`` in the stack's agent posture (the estimator and
4
+ context policy ``stack plan`` uses): a model's memory is its plan's ``vram_bytes`` (on a Mac its
5
+ ``unified_bytes``), its window the plan's. Fit is judged on capacity (every card empty), so it
6
+ does not move as other models load; whether a model can load *now* is the same planner on the
7
+ free memory less what loading models have reserved. The catalog shown is the chat models
8
+ ``validated`` for this platform; a model already on disk stays listed.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ import functools
15
+ import os
16
+ import shutil
17
+ from collections.abc import Iterable
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from localmodels import budget, deploy, hosts, llm_rank, metal, plan_envelope, stack_hardware
23
+ from localmodels import catalog as cat
24
+ from localmodels.context_policy import AgentPosture
25
+ from localmodels.library_model import LibraryError, Reason, display_name, split_id
26
+ from localmodels.probe import HostFacts
27
+ from localmodels.records import Plan
28
+ from localmodels.stack_plan import platform_error
29
+
30
+ POOL_RAM_FRACTION = 0.8 # a "system" or "unified" pool's budget: RAM x 0.8 (contract v2)
31
+
32
+
33
+ @functools.cache
34
+ def posture() -> AgentPosture:
35
+ """The default stack plan's agent posture: its slots, image input and thinking cap."""
36
+ from localmodels import stack, stack_compose
37
+
38
+ return stack_compose.agent_posture(stack.default_options())
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Model:
43
+ """One library row: a catalog entry and one of its variants."""
44
+
45
+ entry: cat.CatalogEntry
46
+ variant: cat.QuantVariant
47
+
48
+ @property
49
+ def id(self) -> str:
50
+ return f"{self.entry.id}:{self.variant.quant}"
51
+
52
+ @property
53
+ def name(self) -> str:
54
+ return display_name(self.entry.display_name, self.variant.quant)
55
+
56
+
57
+ def entries() -> tuple[cat.CatalogEntry, ...]:
58
+ return cat.load_catalog_file()
59
+
60
+
61
+ def is_chat(entry: cat.CatalogEntry) -> bool:
62
+ return entry.runtime == "llama.cpp" and "llm" in entry.tasks
63
+
64
+
65
+ def shown(facts: HostFacts, catalog: Iterable[cat.CatalogEntry]) -> list[Model]:
66
+ """The chat models validated for this platform, one row per variant."""
67
+ return [
68
+ Model(e, v)
69
+ for e in catalog
70
+ if is_chat(e) and cat.validated_here(e, facts["platform"])
71
+ for v in e.variants
72
+ ]
73
+
74
+
75
+ def find(model_id: str, catalog: Iterable[cat.CatalogEntry]) -> Model:
76
+ """The catalog row a library id names (``id:QUANT``; a bare id is its last variant)."""
77
+ catalog_id, quant = split_id(model_id)
78
+ for entry in catalog:
79
+ if entry.id == catalog_id and is_chat(entry):
80
+ for variant in entry.variants:
81
+ if not quant or variant.quant == quant:
82
+ if quant or variant is entry.variants[-1]:
83
+ return Model(entry, variant)
84
+ raise LibraryError("MODEL_UNKNOWN", f"the catalog has no chat model {model_id}")
85
+
86
+
87
+ def platform_problem(facts: HostFacts) -> str | None:
88
+ return platform_error(facts["platform"], arch=facts.get("arch"))
89
+
90
+
91
+ # ---------------------------------------------------------------------------- pools
92
+
93
+
94
+ def visible(facts: HostFacts) -> set[int] | None:
95
+ """The NVIDIA cards ``CUDA_VISIBLE_DEVICES`` (indices or UUIDs) leaves to the library;
96
+ None when it is not set. The library never places a model on a card hidden from it."""
97
+ given = os.environ.get("CUDA_VISIBLE_DEVICES")
98
+ if given is None:
99
+ return None
100
+ names = {part.strip() for part in given.split(",") if part.strip()}
101
+ return {
102
+ g["index"]
103
+ for g in facts.get("gpus") or []
104
+ if str(g["index"]) in names or g["uuid"] in names
105
+ }
106
+
107
+
108
+ def pools(facts: HostFacts) -> dict[str, str]:
109
+ """Pool id -> the planner's placement id: one per NVIDIA card (``gpu:N``), the Mac's unified
110
+ memory (``unified``), and ``system`` for host RAM beside the cards."""
111
+ found: dict[str, str] = {}
112
+ shown = visible(facts)
113
+ for p in budget.placements(facts, planning=True):
114
+ if p.pooled:
115
+ continue
116
+ if p.backend == "metal":
117
+ found["unified"] = p.id
118
+ elif p.backend == "cuda" and not p.budget.uma and len(p.gpu_indices) == 1:
119
+ if shown is None or p.gpu_indices[0] in shown:
120
+ found[f"gpu:{p.gpu_indices[0]}"] = p.id
121
+ if "unified" not in found:
122
+ found["system"] = "cpu"
123
+ return found
124
+
125
+
126
+ def gpu_index(pool: str) -> int | None:
127
+ return int(pool.split(":", 1)[1]) if pool.startswith("gpu:") else None
128
+
129
+
130
+ def pool_total(facts: HostFacts, pool: str) -> int:
131
+ index = gpu_index(pool)
132
+ if index is None:
133
+ return int(facts["ram"]["total_bytes"] * POOL_RAM_FRACTION)
134
+ return next(g["total_bytes"] for g in facts["gpus"] if g["index"] == index)
135
+
136
+
137
+ def pool_free(facts: HostFacts, pool: str) -> int:
138
+ index = gpu_index(pool)
139
+ if index is None:
140
+ used = facts["ram"]["total_bytes"] - facts["ram"]["available_bytes"]
141
+ return max(0, pool_total(facts, pool) - used)
142
+ return next(g["free_bytes"] for g in facts["gpus"] if g["index"] == index)
143
+
144
+
145
+ def pool_of(plan: Plan) -> str:
146
+ """The pool a deployment plan runs in: its card, the Mac's unified memory, else RAM."""
147
+ placement: dict[str, Any] = dict(plan.get("placement") or {})
148
+ gpus: list[dict[str, Any]] = list(placement.get("gpus") or [])
149
+ if gpus and gpus[0].get("uuid") == metal.METAL_UUID:
150
+ return "unified"
151
+ if gpus:
152
+ return f"gpu:{gpus[0]['index']}"
153
+ return "system"
154
+
155
+
156
+ def capacity(facts: HostFacts) -> HostFacts:
157
+ """``facts`` with every card and the RAM empty: what fit is judged on."""
158
+ seen = copy.deepcopy(facts)
159
+ for gpu in seen.get("gpus") or []:
160
+ gpu["free_bytes"], gpu["used_bytes"] = gpu["total_bytes"], 0
161
+ seen["ram"]["available_bytes"] = seen["ram"]["total_bytes"]
162
+ seen["llama_servers"] = []
163
+ seen["disk"] = {**seen["disk"], "free_bytes": None}
164
+ if services := seen.get("services"):
165
+ services["compute_processes"], services["containers"] = [], []
166
+ services["systemd_units"] = []
167
+ return seen
168
+
169
+
170
+ def live(
171
+ facts: HostFacts, reserved: dict[str, int], freed: dict[str, int] | None = None
172
+ ) -> HostFacts:
173
+ """``facts`` less what loading models reserved and plus what ``freed`` gives back, per pool;
174
+ ports and disk are left to the load (a download plan is not bound to them)."""
175
+ seen = copy.deepcopy(facts)
176
+ change = dict(reserved)
177
+ for pool, n in (freed or {}).items():
178
+ change[pool] = change.get(pool, 0) - n
179
+ for gpu in seen.get("gpus") or []:
180
+ delta = change.get(f"gpu:{gpu['index']}", 0)
181
+ gpu["free_bytes"] = max(0, min(gpu["total_bytes"], gpu["free_bytes"] - delta))
182
+ ram = seen["ram"]
183
+ delta = change.get("unified", 0) + change.get("system", 0)
184
+ ram["available_bytes"] = max(0, min(ram["total_bytes"], ram["available_bytes"] - delta))
185
+ seen["llama_servers"] = []
186
+ seen["disk"] = {**seen["disk"], "free_bytes": None}
187
+ return seen
188
+
189
+
190
+ # ---------------------------------------------------------------------------- pricing
191
+
192
+
193
+ def price(
194
+ facts: HostFacts,
195
+ model: Model,
196
+ pool: str,
197
+ base_dir: str,
198
+ catalog: tuple[cat.CatalogEntry, ...],
199
+ port: int = deploy.DEFAULT_PORT,
200
+ ) -> Plan:
201
+ """The deployment plan on ``pool``; AgentMemoryError when it does not fit there."""
202
+ placement = pools(facts).get(pool)
203
+ if placement is None:
204
+ raise plan_envelope.PlanError(f"this computer has no pool {pool}")
205
+ return deploy.build_plan(
206
+ hosts.LOCAL_ID,
207
+ facts,
208
+ deploy.PlanOptions(
209
+ model_id=model.entry.id,
210
+ placement_id=placement,
211
+ port=port,
212
+ base_dir=base_dir,
213
+ hf_download_endpoint=deploy.hf_endpoint(),
214
+ hf_api_endpoint=deploy.hf_endpoint(),
215
+ agent=posture(),
216
+ quant=model.variant.quant,
217
+ ),
218
+ entries=catalog,
219
+ resolver=deploy.catalog_pins,
220
+ )
221
+
222
+
223
+ def memory_bytes(plan: Plan) -> int:
224
+ launch = plan["launch"]
225
+ value = launch.get("unified_bytes") or launch.get("vram_bytes") or 0
226
+ return int(str(value))
227
+
228
+
229
+ @dataclass
230
+ class Priced:
231
+ """A model against this computer: fit, the pool it would take, and its plan there."""
232
+
233
+ fit: str # gpu | unified | none
234
+ pool: str # the planned pool; "" when nothing fits
235
+ plan: Plan | None # priced on the pool's capacity
236
+ fits_now: bool # the planned pool has room now
237
+ need_bytes: int = 0 # fit "none": the smallest shortfall's need and capacity
238
+ have_bytes: int = 0
239
+
240
+
241
+ def judge(
242
+ facts: HostFacts,
243
+ model: Model,
244
+ base_dir: str,
245
+ catalog: tuple[cat.CatalogEntry, ...],
246
+ reserved: dict[str, int],
247
+ ) -> Priced:
248
+ """Fit on capacity; the planned pool is the card with the most free memory that fits now,
249
+ else (nothing has room now) the freest card that fits at all, else the unified pool."""
250
+ cap, now = capacity(facts), live(facts, reserved)
251
+ order = sorted(pools(facts), key=lambda p: -pool_free(now, p))
252
+ fallback: Priced | None = None
253
+ shortfall: tuple[int, int] | None = None
254
+ for pool in order:
255
+ if pool == "system":
256
+ continue # no catalog chat model runs from host RAM in the agent posture
257
+ try:
258
+ plan = price(cap, model, pool, base_dir, catalog)
259
+ except deploy.AgentMemoryError as exc:
260
+ gap = (exc.needed_bytes, exc.available_bytes)
261
+ if shortfall is None or gap[0] - gap[1] < shortfall[0] - shortfall[1]:
262
+ shortfall = gap
263
+ continue
264
+ except plan_envelope.PlanError:
265
+ continue
266
+ fit = "unified" if pool == "unified" else "gpu"
267
+ try:
268
+ price(now, model, pool, base_dir, catalog)
269
+ except plan_envelope.PlanError:
270
+ fallback = fallback or Priced(fit, pool, plan, False)
271
+ continue
272
+ return Priced(fit, pool, plan, True)
273
+ if fallback is not None:
274
+ return fallback
275
+ need, have = shortfall or (0, 0)
276
+ return Priced("none", "", None, False, need, have)
277
+
278
+
279
+ def base_free(base_dir: str) -> int:
280
+ """Free bytes on the filesystem that will hold ``base_dir``."""
281
+ path = Path(base_dir).expanduser()
282
+ while not path.exists() and path != path.parent:
283
+ path = path.parent
284
+ try:
285
+ return shutil.disk_usage(path).free
286
+ except OSError:
287
+ return 0
288
+
289
+
290
+ def missing_bytes(plan: Plan) -> int:
291
+ """Bytes a download still has to fetch: files neither verified in place nor partly kept."""
292
+ from localmodels import remote_ops_download
293
+
294
+ left = 0
295
+ for f in plan["files"]:
296
+ if plan_envelope.verified_in_place(f):
297
+ continue
298
+ part = str(Path(f["dest"]).expanduser()) + ".part"
299
+ try:
300
+ kept = remote_ops_download.kept_bytes(part, f["size_bytes"])
301
+ except OSError:
302
+ kept = 0
303
+ left += max(0, f["size_bytes"] - kept)
304
+ return left
305
+
306
+
307
+ def download_reason(facts: HostFacts, priced: Priced, disk_free: int) -> Reason | None:
308
+ """Why a download is refused now, if it is."""
309
+ if platform_problem(facts):
310
+ return {"code": "PLATFORM_UNSUPPORTED"}
311
+ if priced.plan is None:
312
+ return {
313
+ "code": "MEMORY_INSUFFICIENT",
314
+ "need_bytes": priced.need_bytes,
315
+ "have_bytes": priced.have_bytes,
316
+ }
317
+ need = missing_bytes(priced.plan)
318
+ if need > disk_free:
319
+ return {"code": "DISK_INSUFFICIENT", "need_bytes": need, "have_bytes": disk_free}
320
+ return None
321
+
322
+
323
+ def rank(facts: HostFacts, model: Model, pool: str) -> tuple[int, float]:
324
+ """``llm_rank``'s order (the installed score, then predicted decode speed on that card)."""
325
+ index = gpu_index(pool)
326
+ try:
327
+ if index is None:
328
+ index = (metal.device(facts) or {"index": 0})["index"]
329
+ from localmodels import stack
330
+
331
+ card, _ = stack_hardware.llm_budget(
332
+ capacity(facts), index, stack.default_options(), entry=model.entry, posture=posture()
333
+ )
334
+ return llm_rank.rank_key(model.entry, model.variant, card)
335
+ except (KeyError, StopIteration, ValueError, TypeError):
336
+ return (model.entry.quality, 0.0)
337
+
338
+
339
+ def recommend(facts: HostFacts, candidates: list[tuple[Model, str]]) -> str | None:
340
+ """The one model to suggest among absent, downloadable ones: the smartest by llm_rank."""
341
+ if not candidates:
342
+ return None
343
+ ranked = [(rank(facts, m, pool), m.id, 0) for m, pool in candidates]
344
+ small_mac = llm_rank.mac_default(facts)
345
+ default = next((m.id for m, _ in candidates if m.entry.id == small_mac), None)
346
+ chosen, _ = llm_rank.choose(ranked, "smartest", default)
347
+ return chosen
@@ -0,0 +1,348 @@
1
+ """``library load``, ``unload`` and ``remove``: start a downloaded model's server, stop it, and
2
+ delete its weights.
3
+
4
+ A load prices the model on its recorded pool against the free memory now, less what other
5
+ loading models reserved and plus what ``--unload`` would give back; without room it is
6
+ refused (LOAD_NO_ROOM) before anything is unloaded. It then holds a job that reserves the
7
+ model's memory, unloads what was named, picks a free port (stack_ports), and runs the stack's
8
+ deployment steps (app.run_deploy: install, start, the readiness check, the deployment record).
9
+ Two short requests measure its decode speed (stack_warm), and the gateway and pi get the model
10
+ (library_gateway). Unload undoes the registration and removes the service; the weights stay.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import os
17
+ import shutil
18
+ from pathlib import Path
19
+
20
+ from localmodels import (
21
+ app,
22
+ deploy,
23
+ harness,
24
+ hosts,
25
+ library_gateway,
26
+ library_jobs,
27
+ library_pricing,
28
+ library_state,
29
+ library_status,
30
+ plan_envelope,
31
+ stack_lifecycle,
32
+ stack_ports,
33
+ stack_verify,
34
+ stack_warm,
35
+ )
36
+ from localmodels.library_model import LibraryError, Row, progress
37
+ from localmodels.library_pricing import Model
38
+ from localmodels.library_state import Job, Record
39
+ from localmodels.probe import HostFacts
40
+ from localmodels.records import FinishedRecord, Plan
41
+ from localmodels.transport import Executor
42
+
43
+ LOAD_STEPS = deploy.STEPS
44
+ OOM = ("out of memory", "cudamalloc failed", "failed to allocate", "unable to allocate")
45
+
46
+
47
+ def base_of(record: Record) -> str:
48
+ """The base directory the model was downloaded into."""
49
+ if record.get("base_dir"):
50
+ return record["base_dir"]
51
+ deploy_dir = os.path.expanduser(record["plan"]["service"]["deploy_dir"])
52
+ return os.path.dirname(os.path.dirname(deploy_dir))
53
+
54
+
55
+ def _reserved(skip: str) -> dict[str, int]:
56
+ found: dict[str, int] = {}
57
+ for model, (job, alive) in library_state.jobs().items():
58
+ if alive and job["kind"] == "load" and model != skip:
59
+ found[job["pool"]] = found.get(job["pool"], 0) + job["memory_bytes"]
60
+ return found
61
+
62
+
63
+ def _room(facts: HostFacts, model: Model, record: Record, freed: dict[str, int]) -> None:
64
+ """LOAD_NO_ROOM unless the model fits its pool now, after ``freed`` is given back."""
65
+ now = library_pricing.live(facts, _reserved(model.id), freed)
66
+ try:
67
+ library_pricing.price(
68
+ now, model, record["pool"], base_of(record), library_pricing.entries()
69
+ )
70
+ except deploy.AgentMemoryError as exc:
71
+ raise LibraryError(
72
+ "LOAD_NO_ROOM",
73
+ f"{model.id} does not fit {record['pool']} now",
74
+ pool=record["pool"],
75
+ need_bytes=exc.needed_bytes,
76
+ free_bytes=exc.available_bytes,
77
+ ) from None
78
+ except plan_envelope.PlanError as exc: # its pool is gone (hidden or removed): no room
79
+ need = record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"])
80
+ raise LibraryError(
81
+ "LOAD_NO_ROOM", str(exc), pool=record["pool"], need_bytes=need, free_bytes=0
82
+ ) from None
83
+
84
+
85
+ def _port(facts: HostFacts) -> int:
86
+ """Under ``locked()``: a free port that no recorded server and no live load holds; the
87
+ caller reserves it in its load job before releasing the lock."""
88
+ taken = [r["plan"]["service"]["port"] for r in library_state.records() if r["state"] != "idle"]
89
+ taken += [
90
+ job.get("port", 0)
91
+ for job, alive in library_state.jobs().values()
92
+ if alive and job.get("port")
93
+ ]
94
+ try:
95
+ return stack_ports.default_port(
96
+ facts, stack_ports.AUTO_PORTS, stack_ports.loopback_listening, reserved=taken
97
+ )
98
+ except (plan_envelope.PlanError, OSError) as exc:
99
+ raise LibraryError("ENGINE_START_FAILED", str(exc)) from None
100
+
101
+
102
+ def _start_code(finished: FinishedRecord) -> str:
103
+ failed = next((s for s in finished["steps"] if not s["ok"]), None)
104
+ text = " ".join(
105
+ str(x) for x in (finished.get("error"), failed and failed.get("stderr")) if x
106
+ ).lower()
107
+ if any(word in text for word in OOM):
108
+ return "OUT_OF_MEMORY"
109
+ if failed is not None and failed["step"] == "verify":
110
+ return "HEALTH_CHECK_FAILED"
111
+ if failed is not None and failed["step"] in ("engine", "download"):
112
+ return "MODEL_FILES_MISSING"
113
+ return "ENGINE_START_FAILED"
114
+
115
+
116
+ def _remove_service(plan: Plan, run: Executor) -> None:
117
+ outcome = run.run_action("remove", stack_lifecycle.plan_params(plan), timeout=600)[0]
118
+ if outcome.get("event") != "result":
119
+ raise LibraryError(
120
+ "ENGINE_START_FAILED", f"stopping {plan['name']}: {outcome.get('message')}"
121
+ )
122
+ hosts.delete_record(hosts.LOCAL_ID, plan["name"])
123
+
124
+
125
+ def _forget_deployment(plan: Plan) -> None:
126
+ """The removed server's directory (its log) and its manifest entry: nothing of the model is
127
+ left for a later purge to find."""
128
+ deploy_dir = Path(os.path.expanduser(plan["service"]["deploy_dir"]))
129
+ if deploy_dir.parent.name == "deployments" and deploy_dir.is_dir():
130
+ shutil.rmtree(deploy_dir, ignore_errors=True)
131
+ hosts.delete_record(hosts.LOCAL_ID, plan["name"], purged=True)
132
+
133
+
134
+ def stack_member(record: Record) -> str | None:
135
+ """The Quick Install stack provider an adopted LLM keeps (its main or fastest LLM)."""
136
+ if not record.get("converted"):
137
+ return None
138
+ return record.get("stack_provider") or harness.LLM_PROVIDER
139
+
140
+
141
+ def _fail(record: Record, error: LibraryError) -> LibraryError:
142
+ record["state"] = "failed"
143
+ record["error"] = {"code": error.code, "detail": error.detail}
144
+ library_state.save(record) # a registration it could not take out stays for unload
145
+ return error
146
+
147
+
148
+ def stop(record: Record, run: Executor) -> None:
149
+ """Unregister, then stop and remove the model's server; its weights stay. Either failing
150
+ raises with the record unchanged, so the next unload or remove tries both again."""
151
+ if registration := record.get("registration"):
152
+ library_gateway.unregister(registration)
153
+ if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
154
+ _remove_service(record["plan"], run)
155
+ record["state"] = "idle"
156
+ for key in ("registration", "error", "note"):
157
+ record.pop(key, None) # type: ignore[misc]
158
+ library_state.save(record)
159
+
160
+
161
+ def _serve(model: Model, record: Record, facts: HostFacts, run: Executor, port: int) -> Record:
162
+ base = base_of(record)
163
+ now = library_pricing.live(facts, _reserved(model.id))
164
+ try:
165
+ plan = library_pricing.price(
166
+ now, model, record["pool"], base, library_pricing.entries(), port=port
167
+ )
168
+ except deploy.AgentMemoryError as exc: # after --unload: no longer a refusal
169
+ raise LibraryError(
170
+ "LOAD_NO_ROOM",
171
+ f"{model.id} does not fit {record['pool']} now",
172
+ failed=True,
173
+ pool=record["pool"],
174
+ need_bytes=exc.needed_bytes,
175
+ free_bytes=exc.available_bytes,
176
+ ) from None
177
+ if missing := library_jobs.files_missing(plan):
178
+ raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing), failed=True)
179
+ steps = [str(step) for step in LOAD_STEPS]
180
+
181
+ record["plan"], record["state"] = plan, "starting"
182
+ record.pop("error", None)
183
+ library_state.save(record) # the server about to start is recorded before it exists
184
+ progress(model.id, "load", 0, len(steps))
185
+ try:
186
+ _start(model, record, plan, facts, run, steps)
187
+ except LibraryError:
188
+ raise
189
+ except BaseException: # interrupted (cancel, Ctrl-C) or crashed once the server may run
190
+ _abandon(record, run)
191
+ raise
192
+ record["state"] = "loaded"
193
+ record.pop("error", None)
194
+ record.pop("note", None)
195
+ library_state.save(record)
196
+ return record
197
+
198
+
199
+ def _start(
200
+ model: Model, record: Record, plan: Plan, facts: HostFacts, run: Executor, steps: list[str]
201
+ ) -> None:
202
+ def seen(step: str, _event: object) -> None:
203
+ progress(model.id, "load", steps.index(step), len(steps))
204
+
205
+ finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
206
+ if not finished["ok"]:
207
+ error = LibraryError(_start_code(finished), str(finished.get("error") or "start failed"))
208
+ with contextlib.suppress(LibraryError): # the record keeps the plan to stop it later
209
+ _remove_service(plan, run)
210
+ raise _fail(record, error)
211
+ progress(model.id, "load", len(steps), len(steps))
212
+ progress(model.id, "warm", 0, 2)
213
+ speed = stack_warm.warm_llm(plan)["decode_tok_s"]
214
+ progress(model.id, "warm", 2, 2)
215
+ if speed is not None:
216
+ record["tokens_per_second"] = float(speed)
217
+ key = stack_verify.key(plan) or ""
218
+ member = stack_member(record)
219
+ record["registration"] = library_gateway.planned(model.id, plan, stack_provider=member)
220
+ library_state.save(record) # what registering may add, recorded before it adds anything
221
+ try:
222
+ record["registration"] = library_gateway.register(
223
+ model.id, model.entry, plan, key, facts, stack_provider=member
224
+ )
225
+ except LibraryError as exc:
226
+ with contextlib.suppress(LibraryError): # kept for unload when this fails too
227
+ library_gateway.unregister(record["registration"])
228
+ record.pop("registration")
229
+ with contextlib.suppress(LibraryError):
230
+ _remove_service(plan, run)
231
+ raise _fail(record, exc) from None
232
+
233
+
234
+ def _abandon(record: Record, run: Executor) -> None:
235
+ """Undo a load cut short after its server may have started: stop that exact deployment.
236
+ When even that fails the record keeps the plan (state ``starting``), so unload, remove or
237
+ the next load stops it."""
238
+ try:
239
+ stop(record, run)
240
+ except LibraryError as exc:
241
+ record["error"] = {"code": exc.code, "detail": exc.detail}
242
+ with contextlib.suppress(OSError):
243
+ library_state.save(record)
244
+
245
+
246
+ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts) -> None:
247
+ """Under ``locked()``: LOAD_NO_ROOM unless the model fits its pool in ``facts`` (probed
248
+ under the same lock), less every live load's reservation, plus what ``targets`` and a
249
+ stale server of the model itself give back. The caller commits its own reservation before
250
+ releasing the lock, so the next claimant sees it."""
251
+ freed: dict[str, int] = {}
252
+ for target in [*targets, *([record] if record["state"] != "idle" else [])]:
253
+ pool = target["pool"]
254
+ freed[pool] = freed.get(pool, 0) + library_pricing.memory_bytes(target["plan"])
255
+ _room(facts, model, record, freed)
256
+
257
+
258
+ def _row(model: Model, base_dir: str) -> Row:
259
+ return library_status.model_row(
260
+ library_status.Library.read(library_jobs.probe(), base_dir), model.id
261
+ )
262
+
263
+
264
+ def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
265
+ from localmodels import library_convert
266
+
267
+ library_convert.convert_once()
268
+ model = library_pricing.find(model_id, library_pricing.entries())
269
+ # One entry per model, whatever spelling or repetition named it: each allocation is
270
+ # counted, and each server stopped, once.
271
+ others = list(
272
+ dict.fromkeys(library_pricing.find(m, library_pricing.entries()).id for m in unload)
273
+ )
274
+ targets: list[Record] = []
275
+ with library_state.locked(): # validate, admit and claim as one step
276
+ library_state.refuse_busy(model.id, "load")
277
+ record = library_state.load(model.id)
278
+ if record is None:
279
+ raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
280
+ if missing := library_jobs.files_missing(record["plan"]):
281
+ raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
282
+ facts = library_jobs.probe()
283
+ url = str(record["plan"]["endpoint"]["base_url"])
284
+ if record["state"] == "loaded" and library_status.answering(url):
285
+ return library_status.model_row(library_status.Library.read(facts, base_dir), model.id)
286
+ for other in others:
287
+ library_state.refuse_busy(other, "unload")
288
+ found = library_state.load(other)
289
+ if other != model.id and found is not None and found["state"] != "idle":
290
+ targets.append(found)
291
+ _admit(model, record, targets, facts)
292
+ memory = record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"])
293
+ port = _port(facts) # reserved with the claim: no concurrent load takes it too
294
+ claims = [library_state.acquire("load", model.id, record["pool"], memory, [], port=port)]
295
+ for target in targets:
296
+ claims.append(library_state.acquire("unload", target["id"], target["pool"], 0, []))
297
+ library_jobs.cancel_on_sigterm()
298
+ executor = library_jobs.executor()
299
+ refresh = bool(targets) or record["state"] != "idle" # memory was freed: probe again
300
+ with library_state.held(claims):
301
+ for target in targets:
302
+ stop(target, executor)
303
+ if record["state"] != "idle": # a server that stopped answering, or a failed load
304
+ # A stop that fails ends the load: a server that may still run keeps its record
305
+ # and its memory, and nothing is started beside it.
306
+ stop(record, executor)
307
+ _serve(model, record, library_jobs.probe() if refresh else facts, executor, port)
308
+ return _row(model, base_dir)
309
+
310
+
311
+ def _claim(model: Model, kind: str) -> tuple[Record, Job]:
312
+ """Validate and claim a downloaded model for ``kind`` in one step."""
313
+ with library_state.locked():
314
+ library_state.refuse_busy(model.id, kind)
315
+ record = library_state.load(model.id)
316
+ if record is None:
317
+ raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
318
+ return record, library_state.acquire(kind, model.id, record["pool"], 0, [])
319
+
320
+
321
+ def unload(model_id: str, base_dir: str) -> Row:
322
+ from localmodels import library_convert
323
+
324
+ library_convert.convert_once()
325
+ model = library_pricing.find(model_id, library_pricing.entries())
326
+ record, job = _claim(model, "unload")
327
+ with library_state.held([job]):
328
+ if record["state"] != "idle":
329
+ stop(record, library_jobs.executor())
330
+ return _row(model, base_dir)
331
+
332
+
333
+ def remove(model_id: str, base_dir: str) -> Row:
334
+ from localmodels import library_convert
335
+
336
+ library_convert.convert_once()
337
+ model = library_pricing.find(model_id, library_pricing.entries())
338
+ record, job = _claim(model, "remove")
339
+ with library_state.held([job]):
340
+ if record["state"] != "idle":
341
+ stop(record, library_jobs.executor())
342
+ with library_state.locked():
343
+ library_jobs.delete_weights(
344
+ library_jobs.dests(record["plan"]), library_jobs.in_use(model.id)
345
+ )
346
+ _forget_deployment(record["plan"])
347
+ library_state.forget(model.id)
348
+ return _row(model, base_dir)