@simplexai/localmodels-linux-x64 0.1.0-dev.39 → 0.1.0-dev.42

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 (72) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +70 -69
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/auth_proxy.py +74 -16
  5. package/modules/localmodels/budget.py +27 -18
  6. package/modules/localmodels/catalog.json +4 -130
  7. package/modules/localmodels/catalog.py +10 -0
  8. package/modules/localmodels/chat_template.py +35 -0
  9. package/modules/localmodels/debug_mode.py +8 -0
  10. package/modules/localmodels/deploy.py +7 -1
  11. package/modules/localmodels/download-mirrors.json +0 -8
  12. package/modules/localmodels/gateway.py +2 -0
  13. package/modules/localmodels/gateway_bifrost.py +3 -0
  14. package/modules/localmodels/gateway_home.py +132 -0
  15. package/modules/localmodels/harness.py +48 -13
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/library_gateway.py +13 -2
  18. package/modules/localmodels/library_jobs.py +63 -6
  19. package/modules/localmodels/library_model.py +60 -15
  20. package/modules/localmodels/library_pricing.py +99 -26
  21. package/modules/localmodels/library_serve.py +69 -14
  22. package/modules/localmodels/library_state.py +33 -2
  23. package/modules/localmodels/library_status.py +109 -13
  24. package/modules/localmodels/llm_rank.py +16 -27
  25. package/modules/localmodels/metal.py +29 -12
  26. package/modules/localmodels/probe.py +4 -0
  27. package/modules/localmodels/recommend.py +30 -13
  28. package/modules/localmodels/recommend_cli.py +6 -4
  29. package/modules/localmodels/remote_ops_download.py +75 -14
  30. package/modules/localmodels/remote_ops_remove.py +15 -0
  31. package/modules/localmodels/remote_ops_service.py +10 -0
  32. package/modules/localmodels/reuse.py +31 -5
  33. package/modules/localmodels/runtime_cli.py +61 -40
  34. package/modules/localmodels/runtime_discovery.py +38 -10
  35. package/modules/localmodels/runtime_install.py +31 -10
  36. package/modules/localmodels/runtime_io.py +4 -3
  37. package/modules/localmodels/runtime_pi.py +71 -19
  38. package/modules/localmodels/runtime_process.py +4 -2
  39. package/modules/localmodels/service_deployment.py +5 -3
  40. package/modules/localmodels/service_probe.py +84 -27
  41. package/modules/localmodels/setup_inspection.py +104 -25
  42. package/modules/localmodels/setup_text.py +12 -5
  43. package/modules/localmodels/sizecalc.py +0 -2
  44. package/modules/localmodels/slot_cache.py +467 -0
  45. package/modules/localmodels/stack_binding.py +90 -13
  46. package/modules/localmodels/stack_capacity.py +3 -3
  47. package/modules/localmodels/stack_card.py +1 -0
  48. package/modules/localmodels/stack_compose.py +2 -3
  49. package/modules/localmodels/stack_down.py +22 -7
  50. package/modules/localmodels/stack_events.py +59 -0
  51. package/modules/localmodels/stack_hardware.py +35 -29
  52. package/modules/localmodels/stack_hardware_text.py +40 -35
  53. package/modules/localmodels/stack_lifecycle.py +12 -3
  54. package/modules/localmodels/stack_mlx.py +4 -1
  55. package/modules/localmodels/stack_picks.py +6 -1
  56. package/modules/localmodels/stack_plan.py +1 -0
  57. package/modules/localmodels/stack_rollback.py +9 -4
  58. package/modules/localmodels/stack_summary.py +2 -0
  59. package/modules/localmodels/stack_up.py +27 -20
  60. package/modules/localmodels/stack_update.py +3 -1
  61. package/modules/localmodels/stack_warm.py +21 -11
  62. package/modules/localmodels/stack_warm_store.py +5 -16
  63. package/modules/localmodels/tools.json +1 -0
  64. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/METADATA +1 -1
  65. package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/RECORD +67 -66
  66. package/package.json +1 -1
  67. package/tool.json +1 -1
  68. package/modules/localmodels/engines-b12167.json +0 -26
  69. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/WHEEL +0 -0
  70. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/entry_points.txt +0 -0
  71. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/NOTICE +0 -0
  72. /package/modules/{simplex_localmodels-0.1.0.dev39.dist-info → simplex_localmodels-0.1.0.dev42.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -26,26 +26,35 @@ from localmodels import (
26
26
  library_pricing,
27
27
  library_state,
28
28
  library_status,
29
+ metal,
29
30
  plan_envelope,
30
31
  process_identity,
31
32
  remote_ops_download,
33
+ reuse,
32
34
  )
33
35
  from localmodels.deploy_steps import Action
34
36
  from localmodels.library_model import (
37
+ DOWNLOAD_SOURCES,
35
38
  NO_ROOM_TO_LOAD,
36
39
  LibraryError,
40
+ Phase,
37
41
  Row,
38
42
  progress,
39
43
  )
40
44
  from localmodels.library_pricing import Model
41
45
  from localmodels.library_state import Job, JobHandle, Record
42
46
  from localmodels.probe import HostFacts
43
- from localmodels.records import Plan
47
+ from localmodels.records import Plan, ReusableFile
44
48
  from localmodels.transport import Executor
45
49
 
46
50
 
47
51
  def probe() -> HostFacts:
48
- return app.probe(hosts.LOCAL_ID)
52
+ """This computer's facts, an inference server's file-cached weights on a Mac out of the RAM
53
+ available (metal.foreign_cached_bytes; the library's own servers are not foreign)."""
54
+ facts = app.probe(hosts.LOCAL_ID)
55
+ if foreign := metal.foreign_cached_bytes(facts):
56
+ facts["ram"]["available_bytes"] = max(0, facts["ram"]["available_bytes"] - foreign)
57
+ return facts
49
58
 
50
59
 
51
60
  def executor() -> Executor:
@@ -150,6 +159,19 @@ def _code(message: str) -> str:
150
159
  return "DOWNLOAD_FAILED"
151
160
 
152
161
 
162
+ def _download_telemetry(phase: str, event: dict[str, object]) -> tuple[str | None, int | None]:
163
+ if phase != "download":
164
+ return None, None
165
+ raw_source, raw_conns = event.get("source"), event.get("connections")
166
+ source = raw_source if isinstance(raw_source, str) and raw_source in DOWNLOAD_SOURCES else None
167
+ connections = (
168
+ raw_conns
169
+ if isinstance(raw_conns, int) and not isinstance(raw_conns, bool) and raw_conns >= 0
170
+ else None
171
+ )
172
+ return source, connections
173
+
174
+
153
175
  class _Counter:
154
176
  """Bytes of the whole model: the files already verified count as done; each progress event
155
177
  moves its file's counter for the phase it reports."""
@@ -171,14 +193,49 @@ class _Counter:
171
193
  label = str(event.get("file") or "")
172
194
  if event.get("event") != "progress" or label not in self.sizes:
173
195
  return
174
- phase = "verify" if event.get("phase") == "verify" else "download"
196
+ phase: Phase = "verify" if event.get("phase") == "verify" else "download"
175
197
  done = event.get("done")
176
198
  speed = event.get("bytes_per_s")
177
199
  self.done[label] = int(done) if isinstance(done, int) else 0
178
200
  finished = sum(min(n, self.sizes[k]) for k, n in self.done.items())
179
201
  rate = int(speed) if isinstance(speed, int) and phase == "download" else 0
180
- self.handle.update(phase, finished, self.total, rate)
181
- progress(self.model, phase, finished, self.total, rate) # type: ignore[arg-type]
202
+ source, connections = _download_telemetry(phase, event)
203
+ self.handle.update(
204
+ phase, finished, self.total, rate, source=source, connections=connections
205
+ )
206
+ progress(
207
+ self.model,
208
+ phase,
209
+ finished,
210
+ self.total,
211
+ rate,
212
+ source=source,
213
+ connections=connections,
214
+ )
215
+
216
+
217
+ def _reusable_names(f: ReusableFile) -> tuple[str, ...]:
218
+ if f.get("generated") or plan_envelope.verified_in_place(f) or f.get("reuse"):
219
+ return ()
220
+ dest_name = os.path.basename(os.path.expanduser(f["dest"]))
221
+ repo_name = f.get("path", "").rsplit("/", 1)[-1]
222
+ return (dest_name, repo_name) if repo_name and repo_name != dest_name else (dest_name,)
223
+
224
+
225
+ def _with_reuse(files: list[ReusableFile]) -> list[ReusableFile]:
226
+ wanted: dict[str, tuple[int, str]] = {}
227
+ for f in files:
228
+ dest = os.path.expanduser(f["dest"])
229
+ for name in _reusable_names(f):
230
+ wanted[name] = (f["size_bytes"], dest)
231
+ copies = reuse.find_library_copies(wanted) if wanted else {}
232
+ if not copies:
233
+ return files
234
+ updated: list[ReusableFile] = []
235
+ for f in files:
236
+ copy = next((copies[name] for name in _reusable_names(f) if name in copies), None)
237
+ updated.append({**f, "reuse": copy} if copy else f)
238
+ return updated
182
239
 
183
240
 
184
241
  def fetch(
@@ -198,7 +255,7 @@ def fetch(
198
255
  steps: tuple[Action, ...] = ("download",) if files else ()
199
256
  if engine and plan["engine"]["source"] == "release":
200
257
  steps = ("engine", *steps)
201
- mine: Plan = {**plan, "files": files}
258
+ mine: Plan = {**plan, "files": _with_reuse(files) if files else files}
202
259
  for step in steps:
203
260
  on_event = counter if step == "download" else None
204
261
  outcome, result = run.run_action(
@@ -17,6 +17,11 @@ EVENT_SCHEMA = "localmodels.library-event/v1"
17
17
  ModelState = Literal["absent", "downloading", "idle", "loading", "loaded", "failed"]
18
18
  Fit = Literal["gpu", "unified", "system", "none"]
19
19
  Phase = Literal["download", "verify", "load", "warm"]
20
+ MemoryPressure = Literal["normal", "warn", "critical"]
21
+ DownloadSource = Literal["huggingface", "modelscope", "custom", "cache"]
22
+ DOWNLOAD_SOURCES = ("huggingface", "modelscope", "custom", "cache")
23
+ LoadStep = Literal["prepare", "start", "load", "warm"]
24
+ LOAD_STEPS_PUBLIC = ("prepare", "start", "load", "warm")
20
25
 
21
26
  # Extend only together with the contract (contracts/linger-installer/library-v2.schema.json).
22
27
  ERROR_CODES = (
@@ -86,7 +91,7 @@ class Gpu(TypedDict):
86
91
  free_bytes: int
87
92
 
88
93
 
89
- class Host(TypedDict):
94
+ class _Host(TypedDict):
90
95
  platform: str # linux | darwin | windows
91
96
  arch: str # x86_64 | arm64
92
97
  os_label: str
@@ -96,6 +101,12 @@ class Host(TypedDict):
96
101
  gpus: list[Gpu]
97
102
 
98
103
 
104
+ class Host(_Host, total=False):
105
+ ram_available_bytes: int
106
+ metal_working_set_bytes: int
107
+ memory_pressure: MemoryPressure
108
+
109
+
99
110
  class Holder(TypedDict):
100
111
  kind: Literal["model", "component"]
101
112
  id: str
@@ -103,13 +114,17 @@ class Holder(TypedDict):
103
114
  bytes: int
104
115
 
105
116
 
106
- class Pool(TypedDict):
117
+ class _Pool(TypedDict):
107
118
  id: str # gpu:N | system | unified
108
119
  total_bytes: int
109
120
  used_bytes: int
110
121
  holders: list[Holder]
111
122
 
112
123
 
124
+ class Pool(_Pool, total=False):
125
+ reserve_bytes: int
126
+
127
+
113
128
  class _Reason(TypedDict):
114
129
  code: str # MEMORY_INSUFFICIENT | DISK_INSUFFICIENT | PLATFORM_UNSUPPORTED
115
130
 
@@ -127,13 +142,24 @@ class Availability(_Availability, total=False):
127
142
  reason: Reason # only when not downloadable
128
143
 
129
144
 
130
- class Download(TypedDict):
145
+ class _Download(TypedDict):
131
146
  step: Literal["download", "verify"]
132
147
  done_bytes: int
133
148
  total_bytes: int
134
149
  bytes_per_second: int
135
150
 
136
151
 
152
+ class Download(_Download, total=False):
153
+ source: DownloadSource
154
+ connections: int
155
+
156
+
157
+ class Load(TypedDict):
158
+ step: LoadStep
159
+ done_steps: int
160
+ total_steps: int
161
+
162
+
137
163
  class Endpoint(TypedDict):
138
164
  base_url: str
139
165
  gateway_model: str
@@ -166,6 +192,7 @@ class _Row(TypedDict):
166
192
 
167
193
  class Row(_Row, total=False):
168
194
  download: Download # downloading only
195
+ load: Load # loading only
169
196
  endpoint: Endpoint # loaded only
170
197
  pi_model: str # every model not absent: <pi provider>/<pi model id> once it is loaded
171
198
  tokens_per_second: float # the last measured warm speed; absent when unknown
@@ -179,6 +206,9 @@ class Row(_Row, total=False):
179
206
  license: str
180
207
  source_url: str
181
208
  prompt_tokens_per_second: float # the last load's measured prefill speed
209
+ fits_now: bool # live pool currently has enough free memory to load
210
+ load_need_bytes: int # pool-aligned memory needed to load when fits_now is False
211
+ load_free_bytes: int # pool-aligned free memory when fits_now is False
182
212
  error: Problem # failed only
183
213
  note: Note # idle only, when autoload was skipped
184
214
 
@@ -214,20 +244,35 @@ def _line(doc: object) -> None:
214
244
  sys.stdout.flush()
215
245
 
216
246
 
217
- def progress(model: str, phase: Phase, done: int, total: int, bytes_per_second: int = 0) -> None:
247
+ def progress(
248
+ model: str,
249
+ phase: Phase,
250
+ done: int,
251
+ total: int,
252
+ bytes_per_second: int = 0,
253
+ *,
254
+ source: str | None = None,
255
+ connections: int | None = None,
256
+ load_step: str | None = None,
257
+ ) -> None:
218
258
  """One JSONL progress line; counters are clamped to 0 <= done <= total."""
219
259
  total = max(0, int(total))
220
- _line(
221
- {
222
- "schema": EVENT_SCHEMA,
223
- "event": "progress",
224
- "model": model,
225
- "phase": phase,
226
- "done": min(max(0, int(done)), total),
227
- "total": total,
228
- "bytes_per_second": max(0, int(bytes_per_second)),
229
- }
230
- )
260
+ doc: dict[str, object] = {
261
+ "schema": EVENT_SCHEMA,
262
+ "event": "progress",
263
+ "model": model,
264
+ "phase": phase,
265
+ "done": min(max(0, int(done)), total),
266
+ "total": total,
267
+ "bytes_per_second": max(0, int(bytes_per_second)),
268
+ }
269
+ if source in DOWNLOAD_SOURCES:
270
+ doc["source"] = source
271
+ if isinstance(connections, int) and not isinstance(connections, bool) and connections >= 0:
272
+ doc["connections"] = connections
273
+ if load_step in LOAD_STEPS_PUBLIC:
274
+ doc["load_step"] = load_step
275
+ _line(doc)
231
276
 
232
277
 
233
278
  def result_doc(row: Row) -> dict[str, object]:
@@ -22,12 +22,14 @@ from typing import Any
22
22
  from localmodels import budget, deploy, hosts, llm_rank, metal, plan_envelope, stack_hardware
23
23
  from localmodels import catalog as cat
24
24
  from localmodels.context_policy import AgentPosture
25
+ from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES, METAL_VRAM_RESERVE_BYTES
25
26
  from localmodels.library_model import LibraryError, Reason, display_name, split_id
26
27
  from localmodels.probe import HostFacts
27
28
  from localmodels.records import Plan
28
29
  from localmodels.stack_plan import platform_error
29
30
 
30
- POOL_RAM_FRACTION = 0.8 # a "system" or "unified" pool's budget: RAM x 0.8 (contract v2)
31
+ POOL_RAM_FRACTION = 0.8 # a "system" pool's budget: RAM x 0.8 (contract v2)
32
+ UNIFIED_RESERVE_BYTES = metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
31
33
 
32
34
 
33
35
  @functools.cache
@@ -136,17 +138,42 @@ def gpu_index(pool: str) -> int | None:
136
138
 
137
139
  def pool_total(facts: HostFacts, pool: str) -> int:
138
140
  index = gpu_index(pool)
139
- if index is None:
140
- return int(facts["ram"]["total_bytes"] * POOL_RAM_FRACTION)
141
- return next(g["total_bytes"] for g in facts["gpus"] if g["index"] == index)
141
+ if index is not None:
142
+ return next(g["total_bytes"] for g in facts["gpus"] if g["index"] == index)
143
+ if pool == "unified":
144
+ return max(0, facts["ram"]["total_bytes"] - UNIFIED_RESERVE_BYTES)
145
+ return int(facts["ram"]["total_bytes"] * POOL_RAM_FRACTION)
146
+
147
+
148
+ def _unified_live(facts: HostFacts) -> tuple[int, int]:
149
+ """(free_bytes, reserve_bytes) on a Mac's unified pool after macOS keeps & pressure."""
150
+ level = facts["ram"].get("pressure_level")
151
+ pressured, _ = metal.pressured(facts)
152
+ kept = int(pressured["ram"].get("pressure_kept_bytes") or 0)
153
+ reserve = UNIFIED_RESERVE_BYTES + kept
154
+ if level is not None and level not in (1, metal.PRESSURE_WARN):
155
+ return 0, reserve
156
+ free = max(0, pressured["ram"]["available_bytes"] - UNIFIED_RESERVE_BYTES)
157
+ return free, reserve
142
158
 
143
159
 
144
160
  def pool_free(facts: HostFacts, pool: str) -> int:
145
161
  index = gpu_index(pool)
146
- if index is None:
147
- used = facts["ram"]["total_bytes"] - facts["ram"]["available_bytes"]
148
- return max(0, pool_total(facts, pool) - used)
149
- return next(g["free_bytes"] for g in facts["gpus"] if g["index"] == index)
162
+ if index is not None:
163
+ return next(g["free_bytes"] for g in facts["gpus"] if g["index"] == index)
164
+ if pool == "unified":
165
+ return _unified_live(facts)[0]
166
+ used = facts["ram"]["total_bytes"] - facts["ram"]["available_bytes"]
167
+ return max(0, pool_total(facts, pool) - used)
168
+
169
+
170
+ def pool_reserve(facts: HostFacts, pool: str) -> int:
171
+ """Memory kept back from models on ``pool`` for macOS, display, or safety margins."""
172
+ if gpu_index(pool) is not None:
173
+ return AGENT_VRAM_RESERVE_BYTES
174
+ if pool == "unified":
175
+ return _unified_live(facts)[1]
176
+ return max(0, facts["ram"]["total_bytes"] - pool_total(facts, pool))
150
177
 
151
178
 
152
179
  def pool_of(plan: Plan) -> str:
@@ -197,6 +224,10 @@ def live(
197
224
  # ---------------------------------------------------------------------------- pricing
198
225
 
199
226
 
227
+ class LiveMemoryUnavailable(plan_envelope.PlanError):
228
+ """The probe cannot establish a usable live Metal budget."""
229
+
230
+
200
231
  def price(
201
232
  facts: HostFacts,
202
233
  model: Model,
@@ -204,11 +235,17 @@ def price(
204
235
  base_dir: str,
205
236
  catalog: tuple[cat.CatalogEntry, ...],
206
237
  port: int = deploy.DEFAULT_PORT,
238
+ *,
239
+ require_live: bool = False,
207
240
  ) -> Plan:
208
241
  """The deployment plan on ``pool``; AgentMemoryError when it does not fit there."""
209
242
  placement = pools(facts).get(pool)
210
243
  if placement is None:
211
244
  raise plan_envelope.PlanError(f"this computer has no pool {pool}")
245
+ if require_live and pool == "unified":
246
+ if problem := metal.problem(facts):
247
+ raise LiveMemoryUnavailable(problem)
248
+ facts, _ = metal.pressured(facts)
212
249
  return deploy.build_plan(
213
250
  hosts.LOCAL_ID,
214
251
  facts,
@@ -243,6 +280,37 @@ class Priced:
243
280
  fits_now: bool # the planned pool has room now
244
281
  need_bytes: int = 0 # fit "none": the smallest shortfall's need and capacity
245
282
  have_bytes: int = 0
283
+ load_need_bytes: int = 0 # pool-aligned requirement when fits_now is False
284
+ load_free_bytes: int = 0 # pool-aligned free memory on the planned pool
285
+
286
+
287
+ def live_fit(
288
+ facts: HostFacts,
289
+ model: Model,
290
+ pool: str,
291
+ base_dir: str,
292
+ catalog: tuple[cat.CatalogEntry, ...],
293
+ reserved: dict[str, int],
294
+ *,
295
+ fallback_need: int = 0,
296
+ ) -> tuple[bool, int, int]:
297
+ """Check whether ``model`` fits ``pool`` in live memory right now.
298
+
299
+ Returns ``(fits_now, load_need_bytes, load_free_bytes)`` aligned with ``pool_free`` so row
300
+ and dialog figures match the pool summary while preserving the exact live deficit.
301
+ """
302
+ now = live(facts, reserved)
303
+ if pool not in pools(now):
304
+ return False, max(fallback_need, 1), 0
305
+ free = pool_free(now, pool)
306
+ try:
307
+ price(now, model, pool, base_dir, catalog, require_live=True)
308
+ except deploy.AgentMemoryError as exc:
309
+ deficit = max(1, exc.needed_bytes - exc.available_bytes)
310
+ return False, free + deficit, free
311
+ except plan_envelope.PlanError:
312
+ return False, max(fallback_need, free + 1), free
313
+ return True, 0, free
246
314
 
247
315
 
248
316
  def judge(
@@ -271,12 +339,15 @@ def judge(
271
339
  except plan_envelope.PlanError:
272
340
  continue
273
341
  fit = "unified" if pool == "unified" else "gpu"
274
- try:
275
- price(now, model, pool, base_dir, catalog)
276
- except plan_envelope.PlanError:
277
- fallback = fallback or Priced(fit, pool, plan, False)
278
- continue
279
- return Priced(fit, pool, plan, True)
342
+ fits, load_need, load_free = live_fit(
343
+ facts, model, pool, base_dir, catalog, reserved, fallback_need=memory_bytes(plan)
344
+ )
345
+ if fits:
346
+ return Priced(fit, pool, plan, True, load_free_bytes=load_free)
347
+ if fallback is None:
348
+ fallback = Priced(
349
+ fit, pool, plan, False, load_need_bytes=load_need, load_free_bytes=load_free
350
+ )
280
351
  if fallback is not None:
281
352
  return fallback
282
353
  need, have = shortfall or (0, 0)
@@ -329,26 +400,28 @@ def download_reason(facts: HostFacts, priced: Priced, disk_free: int) -> Reason
329
400
 
330
401
  def smartest(facts: HostFacts) -> tuple[str, str] | None:
331
402
  """(catalog id, quant) of the smartest pick ``stack hardware`` shows for this computer with
332
- its memory free (stack_picks, decision 45): what ``stack plan --llm auto`` installs on it,
333
- the Mac ladder and the Windows fallback included. None when nothing fits automatically."""
403
+ its live free memory (without sharing another server's GPU): what ``stack plan --llm auto``
404
+ installs now, Mac ladder and Windows fallback included. None when nothing fits live."""
334
405
  from localmodels import stack
335
406
 
336
- seen = capacity(facts)
337
- seen["disk"] = facts["disk"] # Strata's fit still sees the real disk
338
- if seen["ram"].get("pressure_level") is not None: # a Mac with its memory free: no pressure
339
- seen["ram"]["pressure_level"] = 1
407
+ seen = copy.deepcopy(facts)
408
+ if (shown_cards := visible(facts)) is not None:
409
+ seen["gpus"] = [g for g in seen.get("gpus") or [] if g["index"] in shown_cards]
340
410
  try:
341
411
  view = stack_hardware.view(seen, stack.default_options(), posture())
342
412
  except (KeyError, ValueError, TypeError, OSError):
343
413
  return None
344
- pick = next((p for p in view.get("picks") or [] if p["role"] == "smartest"), None)
414
+ pick = next(
415
+ (p for p in view.get("picks") or [] if p["role"] == "smartest" and not p.get("shared")),
416
+ None,
417
+ )
345
418
  return (pick["id"], pick["quant"]) if pick is not None else None
346
419
 
347
420
 
348
- def recommend(facts: HostFacts, candidates: list[tuple[Model, str]]) -> str | None:
349
- """The one model to suggest: the CLI's smartest pick, when it is among the absent,
350
- downloadable ``candidates``. None when it is already on disk, not a library model (a
351
- Strata recipe) or nothing fits: never a runner-up in its place."""
421
+ def recommend(facts: HostFacts, candidates: list[Model]) -> str | None:
422
+ """The one model to suggest: the CLI's smartest live pick, when it is among the absent,
423
+ downloadable ``candidates`` that fit live memory now. None when it is already on disk,
424
+ not a library model (a Strata recipe), or nothing fits now."""
352
425
  if not candidates or (pick := smartest(facts)) is None:
353
426
  return None
354
- return next((m.id for m, _ in candidates if (m.entry.id, m.variant.quant) == pick), None)
427
+ return next((m.id for m in candidates if (m.entry.id, m.variant.quant) == pick), None)
@@ -33,9 +33,9 @@ from localmodels import (
33
33
  stack_verify,
34
34
  stack_warm,
35
35
  )
36
- from localmodels.library_model import LibraryError, Row, progress
36
+ from localmodels.library_model import LibraryError, LoadStep, Row, progress
37
37
  from localmodels.library_pricing import Model
38
- from localmodels.library_state import Job, Record
38
+ from localmodels.library_state import Job, JobHandle, Record
39
39
  from localmodels.probe import HostFacts
40
40
  from localmodels.records import FinishedRecord, Plan
41
41
  from localmodels.transport import Executor
@@ -44,6 +44,14 @@ LOAD_STEPS = deploy.STEPS
44
44
  OOM = ("out of memory", "cudamalloc failed", "failed to allocate", "unable to allocate")
45
45
 
46
46
 
47
+ def _deploy_load_step(step: str) -> LoadStep:
48
+ if step in ("engine", "download", "install"):
49
+ return "prepare"
50
+ if step == "start":
51
+ return "start"
52
+ return "load"
53
+
54
+
47
55
  def base_of(record: Record) -> str:
48
56
  """The base directory the model was downloaded into."""
49
57
  if record.get("base_dir"):
@@ -65,7 +73,12 @@ def _room(facts: HostFacts, model: Model, record: Record, freed: dict[str, int])
65
73
  now = library_pricing.live(facts, _reserved(model.id), freed)
66
74
  try:
67
75
  library_pricing.price(
68
- now, model, record["pool"], base_of(record), library_pricing.entries()
76
+ now,
77
+ model,
78
+ record["pool"],
79
+ base_of(record),
80
+ library_pricing.entries(),
81
+ require_live=True,
69
82
  )
70
83
  except deploy.AgentMemoryError as exc:
71
84
  raise LibraryError(
@@ -75,7 +88,7 @@ def _room(facts: HostFacts, model: Model, record: Record, freed: dict[str, int])
75
88
  need_bytes=exc.needed_bytes,
76
89
  free_bytes=exc.available_bytes,
77
90
  ) from None
78
- except plan_envelope.PlanError as exc: # its pool is gone (hidden or removed): no room
91
+ except plan_envelope.PlanError as exc: # its pool is gone, hidden, or under critical pressure
79
92
  need = record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"])
80
93
  raise LibraryError(
81
94
  "LOAD_NO_ROOM", str(exc), pool=record["pool"], need_bytes=need, free_bytes=0
@@ -169,12 +182,25 @@ def stop(record: Record, run: Executor) -> None:
169
182
  library_state.save(record)
170
183
 
171
184
 
172
- def _serve(model: Model, record: Record, facts: HostFacts, run: Executor, port: int) -> Record:
185
+ def _serve(
186
+ model: Model,
187
+ record: Record,
188
+ facts: HostFacts,
189
+ run: Executor,
190
+ port: int,
191
+ handle: JobHandle,
192
+ ) -> Record:
173
193
  base = base_of(record)
174
194
  now = library_pricing.live(facts, _reserved(model.id))
175
195
  try:
176
196
  plan = library_pricing.price(
177
- now, model, record["pool"], base, library_pricing.entries(), port=port
197
+ now,
198
+ model,
199
+ record["pool"],
200
+ base,
201
+ library_pricing.entries(),
202
+ port=port,
203
+ require_live=True,
178
204
  )
179
205
  except deploy.AgentMemoryError as exc: # after --unload: no longer a refusal
180
206
  raise LibraryError(
@@ -185,6 +211,15 @@ def _serve(model: Model, record: Record, facts: HostFacts, run: Executor, port:
185
211
  need_bytes=exc.needed_bytes,
186
212
  free_bytes=exc.available_bytes,
187
213
  ) from None
214
+ except library_pricing.LiveMemoryUnavailable as exc:
215
+ raise LibraryError(
216
+ "LOAD_NO_ROOM",
217
+ str(exc),
218
+ failed=True,
219
+ pool=record["pool"],
220
+ need_bytes=record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"]),
221
+ free_bytes=0,
222
+ ) from None
188
223
  if missing := library_jobs.files_missing(plan):
189
224
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing), failed=True)
190
225
  steps = [str(step) for step in LOAD_STEPS]
@@ -192,9 +227,10 @@ def _serve(model: Model, record: Record, facts: HostFacts, run: Executor, port:
192
227
  record["plan"], record["state"] = plan, "starting"
193
228
  record.pop("error", None)
194
229
  library_state.save(record) # the server about to start is recorded before it exists
195
- progress(model.id, "load", 0, len(steps))
230
+ handle.update("load", 0, len(steps), load_step="prepare")
231
+ progress(model.id, "load", 0, len(steps), load_step="prepare")
196
232
  try:
197
- _start(model, record, plan, facts, run, steps)
233
+ _start(model, record, plan, facts, run, steps, handle)
198
234
  except LibraryError:
199
235
  raise
200
236
  except BaseException: # interrupted (cancel, Ctrl-C) or crashed once the server may run
@@ -208,10 +244,19 @@ def _serve(model: Model, record: Record, facts: HostFacts, run: Executor, port:
208
244
 
209
245
 
210
246
  def _start(
211
- model: Model, record: Record, plan: Plan, facts: HostFacts, run: Executor, steps: list[str]
247
+ model: Model,
248
+ record: Record,
249
+ plan: Plan,
250
+ facts: HostFacts,
251
+ run: Executor,
252
+ steps: list[str],
253
+ handle: JobHandle,
212
254
  ) -> None:
213
255
  def seen(step: str, _event: object) -> None:
214
- progress(model.id, "load", steps.index(step), len(steps))
256
+ done = steps.index(step)
257
+ load_step = _deploy_load_step(step)
258
+ handle.update("load", done, len(steps), load_step=load_step)
259
+ progress(model.id, "load", done, len(steps), load_step=load_step)
215
260
 
216
261
  finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
217
262
  if not finished["ok"]:
@@ -219,11 +264,14 @@ def _start(
219
264
  with contextlib.suppress(LibraryError): # the record keeps the plan to stop it later
220
265
  _remove_service(plan, run)
221
266
  raise _fail(record, error)
222
- progress(model.id, "load", len(steps), len(steps))
223
- progress(model.id, "warm", 0, 2)
267
+ handle.update("load", len(steps), len(steps), load_step="load")
268
+ progress(model.id, "load", len(steps), len(steps), load_step="load")
269
+ handle.update("warm", 0, 2, load_step="warm")
270
+ progress(model.id, "warm", 0, 2, load_step="warm")
224
271
  speed = stack_warm.warm_llm(plan)["decode_tok_s"]
225
272
  prefill = stack_warm.prompt_speed(plan) # one more request; warm still counts two steps
226
- progress(model.id, "warm", 2, 2)
273
+ handle.update("warm", 2, 2, load_step="warm")
274
+ progress(model.id, "warm", 2, 2, load_step="warm")
227
275
  if speed is not None:
228
276
  record["tokens_per_second"] = float(speed)
229
277
  if prefill is not None:
@@ -266,6 +314,11 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
266
314
  releasing the lock, so the next claimant sees it."""
267
315
  freed: dict[str, int] = {}
268
316
  for target in [*targets, *([record] if record["state"] != "idle" else [])]:
317
+ # A server that does not answer (failed, crashed, already stopped) is not counted:
318
+ # ``facts`` already count a gone one's memory as free (on a Mac its weights as file
319
+ # cache), and one still starting is priced as held.
320
+ if not library_status.answering(str(target["plan"]["endpoint"]["base_url"])):
321
+ continue
269
322
  pool = target["pool"]
270
323
  freed[pool] = freed.get(pool, 0) + library_pricing.memory_bytes(target["plan"])
271
324
  _room(facts, model, record, freed)
@@ -314,13 +367,15 @@ def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
314
367
  executor = library_jobs.executor()
315
368
  refresh = bool(targets) or record["state"] != "idle" # memory was freed: probe again
316
369
  with library_state.held(claims):
370
+ handle = library_state.JobHandle(claims[0])
371
+ handle.update("load", 0, len(LOAD_STEPS), load_step="prepare")
317
372
  for target in targets:
318
373
  stop(target, executor)
319
374
  if record["state"] != "idle": # a server that stopped answering, or a failed load
320
375
  # A stop that fails ends the load: a server that may still run keeps its record
321
376
  # and its memory, and nothing is started beside it.
322
377
  stop(record, executor)
323
- _serve(model, record, library_jobs.probe() if refresh else facts, executor, port)
378
+ _serve(model, record, library_jobs.probe() if refresh else facts, executor, port, handle)
324
379
  return _row(model, base_dir)
325
380
 
326
381