@simplexai/localmodels-darwin-arm64 0.1.0-dev.48 → 0.1.0-dev.50

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 (83) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +82 -72
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/budget.py +40 -14
  5. package/modules/localmodels/catalog.json +473 -36
  6. package/modules/localmodels/debug_mode.py +25 -0
  7. package/modules/localmodels/deploy.py +3 -0
  8. package/modules/localmodels/download-mirrors.json +47 -0
  9. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
  10. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  11. package/modules/localmodels/engines.py +31 -6
  12. package/modules/localmodels/gateway.py +23 -6
  13. package/modules/localmodels/gateway_bifrost.py +6 -2
  14. package/modules/localmodels/harness.py +8 -2
  15. package/modules/localmodels/harness_gateway.py +78 -17
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/hosts.py +52 -5
  18. package/modules/localmodels/library_floor.py +76 -0
  19. package/modules/localmodels/library_jobs.py +60 -7
  20. package/modules/localmodels/library_model.py +38 -2
  21. package/modules/localmodels/library_poly.py +272 -0
  22. package/modules/localmodels/library_pricing.py +251 -79
  23. package/modules/localmodels/library_serve.py +27 -4
  24. package/modules/localmodels/library_state.py +16 -0
  25. package/modules/localmodels/library_status.py +46 -18
  26. package/modules/localmodels/library_vram.py +123 -0
  27. package/modules/localmodels/llm_rank.py +42 -1
  28. package/modules/localmodels/magpie_windows.py +312 -0
  29. package/modules/localmodels/probe.py +39 -37
  30. package/modules/localmodels/process_identity.py +26 -33
  31. package/modules/localmodels/process_identity_darwin.py +189 -0
  32. package/modules/localmodels/process_identity_linux.py +62 -30
  33. package/modules/localmodels/recommend.py +3 -1
  34. package/modules/localmodels/remote_ops.py +11 -0
  35. package/modules/localmodels/remote_ops_download.py +30 -5
  36. package/modules/localmodels/remote_ops_service.py +15 -46
  37. package/modules/localmodels/reuse.py +13 -6
  38. package/modules/localmodels/runtime_io.py +32 -18
  39. package/modules/localmodels/service_probe.py +1 -1
  40. package/modules/localmodels/setup_inspection.py +97 -80
  41. package/modules/localmodels/setup_inspection_harness.py +147 -0
  42. package/modules/localmodels/setup_text.py +24 -0
  43. package/modules/localmodels/setup_upgrade.py +155 -0
  44. package/modules/localmodels/stack.py +3 -1
  45. package/modules/localmodels/stack_auto.py +6 -2
  46. package/modules/localmodels/stack_clients.py +1 -1
  47. package/modules/localmodels/stack_compose.py +5 -1
  48. package/modules/localmodels/stack_down.py +25 -16
  49. package/modules/localmodels/stack_hardware.py +17 -3
  50. package/modules/localmodels/stack_picks.py +28 -13
  51. package/modules/localmodels/stack_remove.py +3 -1
  52. package/modules/localmodels/stack_route.py +5 -1
  53. package/modules/localmodels/stack_suite.py +29 -8
  54. package/modules/localmodels/stack_view_access.py +238 -58
  55. package/modules/localmodels/stack_view_hub.py +12 -7
  56. package/modules/localmodels/stack_view_serve.py +13 -6
  57. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  58. package/modules/localmodels/strata_poly_server.py +14 -2
  59. package/modules/localmodels/suite.py +19 -3
  60. package/modules/localmodels/tool_archive.py +4 -0
  61. package/modules/localmodels/transport.py +3 -1
  62. package/modules/localmodels/tui.py +4 -1
  63. package/modules/localmodels/tui_dialogs.py +42 -9
  64. package/modules/localmodels/tui_modals.py +63 -16
  65. package/modules/localmodels/tui_screen.py +80 -53
  66. package/modules/localmodels/tui_views.py +36 -6
  67. package/modules/localmodels/vision.py +4 -2
  68. package/modules/localmodels/web/index.html +996 -300
  69. package/modules/localmodels/web/sizecalc/app.js +616 -88
  70. package/modules/localmodels/web/sizecalc/page.html +239 -106
  71. package/modules/localmodels/web/view/fleet.js +25 -2
  72. package/modules/localmodels/web/view/nav.js +19 -3
  73. package/modules/localmodels/web/view/view.css +110 -22
  74. package/modules/localmodels/web/view/view.js +40 -22
  75. package/modules/localmodels/win_probe.py +204 -0
  76. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/METADATA +1 -1
  77. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/RECORD +79 -69
  78. package/package.json +1 -1
  79. package/tool.json +1 -1
  80. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/WHEEL +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/entry_points.txt +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/NOTICE +0 -0
  83. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -19,17 +19,22 @@ import shutil
19
19
  from collections.abc import Iterable, Mapping
20
20
  from dataclasses import dataclass
21
21
  from pathlib import Path
22
- from typing import Any
22
+ from typing import Any, Literal
23
23
 
24
24
  from localmodels import (
25
25
  budget,
26
26
  context_policy,
27
27
  deploy,
28
+ engines,
28
29
  hosts,
30
+ library_poly,
31
+ library_vram,
29
32
  llm_rank,
30
33
  metal,
31
34
  plan_envelope,
32
35
  stack_hardware,
36
+ stack_llm_ram,
37
+ suite,
33
38
  vision,
34
39
  )
35
40
  from localmodels import catalog as cat
@@ -40,7 +45,7 @@ from localmodels.estimator import (
40
45
  PhysicsRefusal,
41
46
  )
42
47
  from localmodels.library_model import LibraryError, Reason, display_name, split_id
43
- from localmodels.probe import GPU, HostFacts
48
+ from localmodels.probe import HostFacts
44
49
  from localmodels.records import Plan
45
50
  from localmodels.stack_plan import platform_error
46
51
 
@@ -82,11 +87,9 @@ def is_chat(entry: cat.CatalogEntry) -> bool:
82
87
 
83
88
 
84
89
  def shown(facts: HostFacts, catalog: Iterable[cat.CatalogEntry]) -> list[Model]:
85
- """The chat models validated for this platform, library-listed candidates, and the candidates
86
- ``stack --llm auto`` picks here too (the Mac small-memory ladder, the Windows NVIDIA
87
- fallback): one row per variant. Ling-3.0-tiny, which the ladder replaces in automatic
88
- selection, stays listed."""
89
- return [
90
+ """Validated chat models, library candidates, Mac ladder, Windows fallback, and
91
+ supported PolyStrata LLM recipes."""
92
+ rows = [
90
93
  Model(e, v)
91
94
  for e in catalog
92
95
  if is_chat(e)
@@ -98,6 +101,8 @@ def shown(facts: HostFacts, catalog: Iterable[cat.CatalogEntry]) -> list[Model]:
98
101
  )
99
102
  for v in e.variants
100
103
  ]
104
+ rows += [Model(e, v) for e, v in library_poly.shown_entries(facts)]
105
+ return rows
101
106
 
102
107
 
103
108
  def find(model_id: str, catalog: Iterable[cat.CatalogEntry]) -> Model:
@@ -109,6 +114,8 @@ def find(model_id: str, catalog: Iterable[cat.CatalogEntry]) -> Model:
109
114
  if not quant or variant.quant == quant:
110
115
  if quant or variant is entry.variants[-1]:
111
116
  return Model(entry, variant)
117
+ if poly := library_poly.find_entry(model_id):
118
+ return Model(*poly)
112
119
  raise LibraryError("MODEL_UNKNOWN", f"the catalog has no chat model {model_id}")
113
120
 
114
121
 
@@ -133,9 +140,16 @@ def visible(facts: HostFacts) -> set[int] | None:
133
140
  }
134
141
 
135
142
 
143
+ def _cuda_uma(facts: HostFacts) -> int | None:
144
+ """Allocator pool bytes for an NVIDIA unified-memory device (e.g. Grace/GB10), else None."""
145
+ if metal.supported(facts):
146
+ return None
147
+ return budget.unified_pool_bytes(facts)
148
+
149
+
136
150
  def pools(facts: HostFacts) -> dict[str, str]:
137
- """Pool id -> the planner's placement id: one per NVIDIA card (``gpu:N``), the Mac's unified
138
- memory (``unified``), and ``system`` for host RAM beside the cards."""
151
+ """Pool id -> the planner's placement id: one per discrete NVIDIA card (``gpu:N``),
152
+ Apple Silicon or CUDA unified memory (``unified``), and ``system`` for host RAM."""
139
153
  found: dict[str, str] = {}
140
154
  shown = visible(facts)
141
155
  for p in budget.placements(facts, planning=True):
@@ -143,6 +157,9 @@ def pools(facts: HostFacts) -> dict[str, str]:
143
157
  continue
144
158
  if p.backend == "metal":
145
159
  found["unified"] = p.id
160
+ elif p.backend == "cuda" and p.budget.uma:
161
+ if not p.gpu_indices or shown is None or p.gpu_indices[0] in shown:
162
+ found["unified"] = p.id
146
163
  elif p.backend == "cuda" and not p.budget.uma and len(p.gpu_indices) == 1:
147
164
  if shown is None or p.gpu_indices[0] in shown:
148
165
  found[f"gpu:{p.gpu_indices[0]}"] = p.id
@@ -155,17 +172,40 @@ def gpu_index(pool: str) -> int | None:
155
172
  return int(pool.split(":", 1)[1]) if pool.startswith("gpu:") else None
156
173
 
157
174
 
175
+ def _cuda_uma_budget_bytes(base: int) -> int:
176
+ usable = int(base * (1 - budget._UMA_HEADROOM_FRACTION))
177
+ return max(0, usable - AGENT_VRAM_RESERVE_BYTES)
178
+
179
+
180
+ def _cuda_uma_live(facts: HostFacts) -> tuple[int, int]:
181
+ """(free_bytes, reserve_bytes) on a CUDA unified-memory pool."""
182
+ unified = _cuda_uma(facts) or facts["ram"]["total_bytes"]
183
+ nvidia = [
184
+ g
185
+ for g in facts.get("gpus") or []
186
+ if g.get("vendor") == "nvidia" and g.get("mig_mode") != "enabled"
187
+ ]
188
+ first_free = nvidia[0]["free_bytes"] if nvidia else 0
189
+ _, ram_avail = budget.host_ram(facts)
190
+ free = _cuda_uma_budget_bytes(min(unified, first_free + ram_avail))
191
+ return free, max(0, unified - _cuda_uma_budget_bytes(unified))
192
+
193
+
158
194
  def pool_total(facts: HostFacts, pool: str) -> int:
159
195
  index = gpu_index(pool)
160
196
  if index is not None:
161
197
  return next(g["total_bytes"] for g in facts["gpus"] if g["index"] == index)
162
198
  if pool == "unified":
199
+ if (unified := _cuda_uma(facts)) is not None:
200
+ return _cuda_uma_budget_bytes(unified)
163
201
  return max(0, facts["ram"]["total_bytes"] - UNIFIED_RESERVE_BYTES)
164
202
  return int(facts["ram"]["total_bytes"] * POOL_RAM_FRACTION)
165
203
 
166
204
 
167
205
  def _unified_live(facts: HostFacts) -> tuple[int, int]:
168
- """(free_bytes, reserve_bytes) on a Mac's unified pool after macOS keeps & pressure."""
206
+ """(free_bytes, reserve_bytes) on a unified pool (Metal or CUDA UMA)."""
207
+ if _cuda_uma(facts) is not None:
208
+ return _cuda_uma_live(facts)
169
209
  level = facts["ram"].get("pressure_level")
170
210
  pressured, _ = metal.pressured(facts)
171
211
  kept = int(pressured["ram"].get("pressure_kept_bytes") or 0)
@@ -187,7 +227,7 @@ def pool_free(facts: HostFacts, pool: str) -> int:
187
227
 
188
228
 
189
229
  def pool_reserve(facts: HostFacts, pool: str) -> int:
190
- """Memory kept back from models on ``pool`` for macOS, display, or safety margins."""
230
+ """Memory kept back from models on ``pool`` for OS, display, or safety margins."""
191
231
  if gpu_index(pool) is not None:
192
232
  return AGENT_VRAM_RESERVE_BYTES
193
233
  if pool == "unified":
@@ -196,60 +236,25 @@ def pool_reserve(facts: HostFacts, pool: str) -> int:
196
236
 
197
237
 
198
238
  def pool_of(plan: Plan) -> str:
199
- """The pool a deployment plan runs in: its card, the Mac's unified memory, else RAM."""
239
+ """The pool a deployment plan runs in: its card, unified memory, else RAM."""
200
240
  placement: dict[str, Any] = dict(plan.get("placement") or {})
201
241
  gpus: list[dict[str, Any]] = list(placement.get("gpus") or [])
202
- if gpus and gpus[0].get("uuid") == metal.METAL_UUID:
242
+ if placement.get("id") == "host" or (gpus and gpus[0].get("uuid") == metal.METAL_UUID):
203
243
  return "unified"
204
244
  if gpus:
205
245
  return f"gpu:{gpus[0]['index']}"
206
246
  return "system"
207
247
 
208
248
 
209
- def _owned_gpu_bytes(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
210
- pool = f"gpu:{gpu['index']}"
211
- from_records = max(0, int((reclaimable or {}).get(pool, 0)))
212
- services = facts.get("services")
213
- procs = (services.get("compute_processes") if services else None) or []
214
- from_procs = sum(
215
- int(p.get("used_bytes") or 0)
216
- for p in procs
217
- if p["gpu_uuid"] == gpu["uuid"] and p.get("owned") is True
218
- )
219
- return max(from_records, from_procs)
220
-
221
-
222
- def _foreign_gpu_bytes(facts: HostFacts, gpu: GPU) -> int:
223
- services = facts.get("services")
224
- procs = (services.get("compute_processes") if services else None) or []
225
- return sum(
226
- int(p.get("used_bytes") or 0)
227
- for p in procs
228
- if p["gpu_uuid"] == gpu["uuid"] and budget.foreign_work(p, facts)
229
- )
230
-
231
-
232
- def _gpu_capacity_free(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
233
- """Loadable VRAM on ``gpu`` once owned models and transient foreign work clear, keeping
234
- observed desktop/WDDM baseline occupancy on Windows and display-active GPUs."""
235
- total = gpu["total_bytes"]
236
- if facts.get("platform") != "win32" and not gpu.get("display_active"):
237
- return total
238
- taken = max(gpu["used_bytes"], max(0, total - gpu["free_bytes"]))
239
- desktop_used = max(
240
- 0, taken - _owned_gpu_bytes(facts, gpu, reclaimable) - _foreign_gpu_bytes(facts, gpu)
241
- )
242
- baseline = min(desktop_used, DESKTOP_VRAM_BASELINE_CAP_BYTES)
243
- return min(total, max(gpu["free_bytes"], total - baseline))
244
-
245
-
246
249
  def capacity(facts: HostFacts, *, reclaimable: Mapping[str, int] | None = None) -> HostFacts:
247
250
  """``facts`` at loadable capacity once loaded library models are unloaded: keeps macOS's
248
251
  idle baseline (``metal.in_use``) on Apple Silicon and observed desktop/WDDM baseline VRAM
249
252
  on Windows and display-active GPUs instead of pretending zero OS/desktop overhead."""
250
253
  seen = copy.deepcopy(facts)
251
254
  for gpu in seen.get("gpus") or []:
252
- free = _gpu_capacity_free(facts, gpu, reclaimable)
255
+ free = library_vram.gpu_capacity_free(
256
+ facts, gpu, reclaimable, DESKTOP_VRAM_BASELINE_CAP_BYTES
257
+ )
253
258
  gpu["free_bytes"], gpu["used_bytes"] = free, max(0, gpu["total_bytes"] - free)
254
259
  ram = seen["ram"]
255
260
  if metal.supported(seen):
@@ -261,6 +266,8 @@ def capacity(facts: HostFacts, *, reclaimable: Mapping[str, int] | None = None)
261
266
  ram.pop("pressure_kept_bytes", None)
262
267
  else:
263
268
  ram["available_bytes"] = ram["total_bytes"]
269
+ if cgroup := seen.get("cgroup_memory"):
270
+ cgroup["usage_bytes"] = 0
264
271
  seen["llama_servers"] = []
265
272
  seen["disk"] = {**seen["disk"], "free_bytes": None}
266
273
  if services := seen.get("services"):
@@ -282,8 +289,30 @@ def live(
282
289
  delta = change.get(f"gpu:{gpu['index']}", 0)
283
290
  gpu["free_bytes"] = max(0, min(gpu["total_bytes"], gpu["free_bytes"] - delta))
284
291
  ram = seen["ram"]
285
- delta = change.get("unified", 0) + change.get("system", 0)
286
- ram["available_bytes"] = max(0, min(ram["total_bytes"], ram["available_bytes"] - delta))
292
+ unified_delta = change.get("unified", 0)
293
+ system_delta = change.get("system", 0)
294
+ if (unified := _cuda_uma(seen)) is not None and unified_delta:
295
+ nvidia = [
296
+ g
297
+ for g in seen.get("gpus") or []
298
+ if g.get("vendor") == "nvidia" and g.get("mig_mode") != "enabled"
299
+ ]
300
+ first = nvidia[0] if nvidia else None
301
+ first_free = first["free_bytes"] if first is not None else 0
302
+ current_live = min(unified, first_free + ram["available_bytes"])
303
+ scaled = int(round(unified_delta / (1 - budget._UMA_HEADROOM_FRACTION)))
304
+ target = max(0, min(unified, current_live - scaled))
305
+ if first is not None and first_free > target:
306
+ first["free_bytes"], ram["available_bytes"] = target, 0
307
+ else:
308
+ ram["available_bytes"] = max(0, min(ram["total_bytes"], target - first_free))
309
+ if system_delta:
310
+ ram["available_bytes"] = max(
311
+ 0, min(ram["total_bytes"], ram["available_bytes"] - system_delta)
312
+ )
313
+ else:
314
+ delta = unified_delta + system_delta
315
+ ram["available_bytes"] = max(0, min(ram["total_bytes"], ram["available_bytes"] - delta))
287
316
  seen["llama_servers"] = []
288
317
  seen["disk"] = {**seen["disk"], "free_bytes": None}
289
318
  return seen
@@ -296,6 +325,20 @@ class LiveMemoryUnavailable(plan_envelope.PlanError):
296
325
  """The probe cannot establish a usable live Metal budget."""
297
326
 
298
327
 
328
+ def host_ram_bytes(plan: Plan, catalog: tuple[cat.CatalogEntry, ...]) -> int:
329
+ """Host RAM held by one discrete-GPU model (llama.cpp or PolyStrata)."""
330
+ if library_poly.is_poly_plan(plan):
331
+ return suite.bounded_ram(plan)
332
+ min_cache_bytes = (
333
+ (posture().prompt_cache_min_mib << 20) if posture().prompt_cache_mib > 0 else 0
334
+ )
335
+ return stack_llm_ram.own_bytes(plan, catalog, running=False, metal=False) + min_cache_bytes
336
+
337
+
338
+ def _required_host_ram(plan: Plan, catalog: tuple[cat.CatalogEntry, ...]) -> int:
339
+ return host_ram_bytes(plan, catalog) + budget.HARNESS_RAM + budget.RAM_FLOOR
340
+
341
+
299
342
  def price(
300
343
  facts: HostFacts,
301
344
  model: Model,
@@ -310,7 +353,11 @@ def price(
310
353
  placement = pools(facts).get(pool)
311
354
  if placement is None:
312
355
  raise plan_envelope.PlanError(f"this computer has no pool {pool}")
313
- if require_live and pool == "unified":
356
+ if model.entry.runtime == "strata-poly":
357
+ return library_poly.price(
358
+ facts, model.entry.id, pool, base_dir, port, posture(), require_live=require_live
359
+ )
360
+ if require_live and pool == "unified" and metal.supported(facts):
314
361
  if problem := metal.problem(facts):
315
362
  raise LiveMemoryUnavailable(problem)
316
363
  facts, _ = metal.pressured(facts)
@@ -343,6 +390,19 @@ def price(
343
390
  refused,
344
391
  "unified memory" if pool == "unified" else "GPU memory",
345
392
  )
393
+ if gpu_index(pool) is not None:
394
+ needed_ram = _required_host_ram(plan, catalog)
395
+ _, avail_ram = budget.host_ram(facts)
396
+ if needed_ram > avail_ram:
397
+ refused = PhysicsRefusal(
398
+ needed_bytes=needed_ram,
399
+ available_bytes=avail_ram,
400
+ message=(
401
+ f"{model.id} needs {needed_ram} bytes of system memory, "
402
+ f"exceeding {avail_ram} bytes available"
403
+ ),
404
+ )
405
+ raise deploy.AgentMemoryError(refused.message, refused, "system memory")
346
406
  return plan
347
407
 
348
408
 
@@ -364,14 +424,20 @@ class Priced:
364
424
  have_bytes: int = 0
365
425
  load_need_bytes: int = 0 # pool-aligned requirement when fits_now is False
366
426
  load_free_bytes: int = 0 # pool-aligned free memory on the planned pool
427
+ memory_kind: str = "" # vram | ram | unified (when fit == "none" due to memory)
428
+ blocker: Reason | None = None # driver/runtime incompatibility when no pool priced
429
+ reclaimable_desktop_vram: bool = False # fits discrete GPU once desktop apps near 1 GiB idle
430
+ reclaim_bytes: int = 0 # approximate VRAM to free when reclaimable_desktop_vram is True
367
431
 
368
432
 
369
- def _min_pool_need(model: Model, pool: str, exc: deploy.AgentMemoryError) -> int:
433
+ def _min_pool_need(model: Model, pool: str, exc: deploy.AgentMemoryError, facts: HostFacts) -> int:
370
434
  """Exact pool-aligned free bytes required at the agent floor when ``available_bytes`` clamped
371
435
  to zero inside ``agent_budget`` or ``vision.priced``."""
436
+ if model.entry.runtime == "strata-poly":
437
+ return exc.needed_bytes
372
438
  if gpu_index(pool) is not None:
373
439
  return exc.needed_bytes + AGENT_VRAM_RESERVE_BYTES
374
- if pool == "unified":
440
+ if pool == "unified" and metal.supported(facts):
375
441
  profile = model.entry.profile(model.variant)
376
442
  mac_posture = model.entry.agent_posture(context_policy.posture_for(posture(), "metal"))
377
443
  host_side = context_policy.cache_floor_bytes(
@@ -404,10 +470,12 @@ def _live_plan(
404
470
  try:
405
471
  plan = price(now, model, pool, base_dir, catalog, require_live=True)
406
472
  except deploy.AgentMemoryError as exc:
473
+ if exc.memory == "system memory":
474
+ return None, exc.needed_bytes, exc.available_bytes
407
475
  deficit = max(1, exc.needed_bytes - exc.available_bytes)
408
476
  need = free + deficit
409
477
  if exc.available_bytes == 0:
410
- need = max(need, _min_pool_need(model, pool, exc))
478
+ need = max(need, _min_pool_need(model, pool, exc, now))
411
479
  return None, need, free
412
480
  except plan_envelope.PlanError:
413
481
  return None, max(fallback_need, free + 1), free
@@ -444,24 +512,30 @@ def judge(
444
512
  *,
445
513
  reclaimable: Mapping[str, int] | None = None,
446
514
  ) -> Priced:
447
- """Fit on loadable capacity; the planned pool is the card with the most free memory that
448
- fits now, else (nothing has room now) the freest card that fits at all, else the unified pool.
449
- When the model fits live now, its live plan is returned so displayed context and memory match
450
- what ``library load`` will actually allocate."""
515
+ """Fit on loadable capacity; pick the freest card that fits live, else capacity, else unified."""
451
516
  cap, now = capacity(facts, reclaimable=reclaimable), live(facts, reserved)
452
517
  order = sorted(pools(facts), key=lambda p: -pool_free(now, p))
453
518
  fallback: Priced | None = None
454
- shortfall: tuple[int, int] | None = None
519
+ shortfall: tuple[int, int, str] | None = None
520
+ blocker: Reason | None = None
455
521
  for pool in order:
456
522
  if pool == "system":
457
523
  continue # no catalog chat model runs from host RAM in the agent posture
458
524
  try:
459
525
  plan = price(cap, model, pool, base_dir, catalog)
460
526
  except deploy.AgentMemoryError as exc:
461
- gap = (exc.needed_bytes, exc.available_bytes)
527
+ kind = (
528
+ "ram"
529
+ if exc.memory == "system memory"
530
+ else ("unified" if pool == "unified" else "vram")
531
+ )
532
+ gap = (exc.needed_bytes, exc.available_bytes, kind)
462
533
  if shortfall is None or gap[0] - gap[1] < shortfall[0] - shortfall[1]:
463
534
  shortfall = gap
464
535
  continue
536
+ except (engines.CudaDriverError, engines.EngineUnavailableError) as exc:
537
+ blocker = blocker or library_poly.engine_blocker(exc)
538
+ continue
465
539
  except plan_envelope.PlanError:
466
540
  continue
467
541
  fit = "unified" if pool == "unified" else "gpu"
@@ -476,8 +550,27 @@ def judge(
476
550
  )
477
551
  if fallback is not None:
478
552
  return fallback
479
- need, have = shortfall or (0, 0)
480
- return Priced("none", "", None, False, need, have)
553
+ need, have, memory_kind = shortfall or (0, 0, "")
554
+ reclaim = (
555
+ blocker is None
556
+ and memory_kind == "vram"
557
+ and need > have
558
+ and library_vram.fits_idle_desktop(
559
+ facts, cap, order, lambda f, p: price(f, model, p, base_dir, catalog)
560
+ )
561
+ )
562
+ return Priced(
563
+ "none",
564
+ "",
565
+ None,
566
+ False,
567
+ need,
568
+ have,
569
+ memory_kind=memory_kind,
570
+ blocker=blocker,
571
+ reclaimable_desktop_vram=reclaim,
572
+ reclaim_bytes=max(1, need - have) if reclaim else 0,
573
+ )
481
574
 
482
575
 
483
576
  def base_free(base_dir: str) -> int:
@@ -508,26 +601,97 @@ def missing_bytes(plan: Plan) -> int:
508
601
  return left
509
602
 
510
603
 
604
+ def _gpu_unsupported_reason(facts: HostFacts) -> Reason | None:
605
+ if any(p != "system" for p in pools(facts)):
606
+ return None
607
+ if visible(facts) == set() and any(
608
+ g.get("vendor") == "nvidia" for g in facts.get("gpus") or []
609
+ ):
610
+ return None
611
+ raw = str(facts.get("gpu_vendor_class") or "unknown")
612
+ vendor: Literal["amd", "intel", "none", "unknown"] = (
613
+ "amd"
614
+ if raw == "amd"
615
+ else "intel"
616
+ if raw == "intel"
617
+ else "unknown"
618
+ if raw == "unknown"
619
+ else "none"
620
+ )
621
+ return {"code": "GPU_UNSUPPORTED", "gpu_vendor": vendor}
622
+
623
+
511
624
  def download_reason(facts: HostFacts, priced: Priced, disk_free: int) -> Reason | None:
512
- """Why a download is refused now, if it is."""
513
625
  if platform_problem(facts):
514
626
  return {"code": "PLATFORM_UNSUPPORTED"}
515
627
  if priced.plan is None:
516
- return {
628
+ if priced.blocker is not None:
629
+ return priced.blocker
630
+ if gpu_reason := _gpu_unsupported_reason(facts):
631
+ return gpu_reason
632
+ reason: Reason = {
517
633
  "code": "MEMORY_INSUFFICIENT",
518
634
  "need_bytes": priced.need_bytes,
519
635
  "have_bytes": priced.have_bytes,
520
636
  }
521
- need = missing_bytes(priced.plan)
522
- if need > disk_free:
637
+ if priced.memory_kind in ("vram", "ram", "unified"):
638
+ reason["memory_kind"] = priced.memory_kind # type: ignore[typeddict-item]
639
+ if priced.reclaimable_desktop_vram:
640
+ reason["reclaimable_desktop_vram"] = True
641
+ if priced.reclaim_bytes > 0:
642
+ reason["reclaim_bytes"] = priced.reclaim_bytes
643
+ return reason
644
+ if (need := missing_bytes(priced.plan)) > disk_free:
523
645
  return {"code": "DISK_INSUFFICIENT", "need_bytes": need, "have_bytes": disk_free}
524
646
  return None
525
647
 
526
648
 
527
- def smartest(facts: HostFacts) -> tuple[str, str] | None:
528
- """(catalog id, quant) of the smartest pick ``stack hardware`` shows for this computer with
529
- its live free memory (without sharing another server's GPU): what ``stack plan --llm auto``
530
- installs now, Mac ladder and Windows fallback included. None when nothing fits live."""
649
+ def _smartest_library_fallback(facts: HostFacts, base_dir: str) -> tuple[str, str] | None:
650
+ """Best live-fitting llama.cpp library model ranked by ``llm_rank.choose()``."""
651
+ catalog = entries()
652
+ pool_map = pools(facts)
653
+ live_pools = [p for p in pool_map if p != "system"]
654
+ if not live_pools:
655
+ return None
656
+ placements_by_id = {p.id: p for p in budget.placements(facts, planning=False)}
657
+ ranked: list[tuple[tuple[int, float], str, int]] = []
658
+ by_id: dict[str, Model] = {}
659
+ fallback_ids: set[str] = set()
660
+ for model in shown(facts, catalog):
661
+ if (
662
+ model.entry.runtime != "llama.cpp"
663
+ or not llm_rank.automatic_here(model.entry, facts)
664
+ or model.variant is not model.entry.variants[-1]
665
+ ):
666
+ continue
667
+ for pool in live_pools:
668
+ try:
669
+ price(facts, model, pool, base_dir, catalog, require_live=True)
670
+ except plan_envelope.PlanError:
671
+ continue
672
+ pl = placements_by_id.get(pool_map[pool])
673
+ hw = (budget.agent_budget(pl, facts) if pl else None) or (pl.budget if pl else None)
674
+ tok_s = (
675
+ round(cat.decode_estimate(model.entry, model.variant, hw).tok_s, 1) if hw else 0.0
676
+ )
677
+ is_fb = llm_rank.windows_fallback(model.entry, facts)
678
+ score = 0 if (is_fb or llm_rank.mac_rung(model.entry, facts)) else model.entry.quality
679
+ ranked.append(((score, tok_s), model.entry.id, gpu_index(pool) or 0))
680
+ by_id[model.entry.id] = model
681
+ if is_fb:
682
+ fallback_ids.add(model.entry.id)
683
+ break
684
+ if not ranked:
685
+ return None
686
+ chosen_id, _ = llm_rank.choose(
687
+ ranked, "smartest", llm_rank.mac_ladder(facts), fallback_ids=fallback_ids
688
+ )
689
+ return by_id[chosen_id].entry.id, by_id[chosen_id].variant.quant
690
+
691
+
692
+ def smartest(facts: HostFacts, base_dir: str = deploy.DEFAULT_BASE_DIR) -> tuple[str, str] | None:
693
+ """(catalog id, quant) of the smartest live library pick; falls back to library models when
694
+ ``stack`` selects Strata/PolyStrata or on CUDA unified-memory hosts."""
531
695
  from localmodels import stack
532
696
 
533
697
  seen = copy.deepcopy(facts)
@@ -541,13 +705,21 @@ def smartest(facts: HostFacts) -> tuple[str, str] | None:
541
705
  (p for p in view.get("picks") or [] if p["role"] == "smartest" and not p.get("shared")),
542
706
  None,
543
707
  )
544
- return (pick["id"], pick["quant"]) if pick is not None else None
708
+ if pick is not None and (
709
+ pick["id"] not in library_poly.strata_ids() or library_poly.in_library(pick["id"], seen)
710
+ ):
711
+ return (pick["id"], pick["quant"])
712
+ if pick is not None or _cuda_uma(seen) is not None:
713
+ return _smartest_library_fallback(seen, base_dir)
714
+ return None
545
715
 
546
716
 
547
- def recommend(facts: HostFacts, candidates: list[Model]) -> str | None:
548
- """The one model to suggest: the CLI's smartest live pick, when it is among the absent,
549
- downloadable ``candidates`` that fit live memory now. None when it is already on disk,
550
- not a library model (a Strata recipe), or nothing fits now."""
551
- if not candidates or (pick := smartest(facts)) is None:
717
+ def recommend(
718
+ facts: HostFacts, candidates: list[Model], base_dir: str = deploy.DEFAULT_BASE_DIR
719
+ ) -> str | None:
720
+ """The one model to suggest: the smartest live library pick, when it is among the absent,
721
+ downloadable ``candidates`` that fit live memory now. None when it is already on disk
722
+ or nothing fits now."""
723
+ if not candidates or (pick := smartest(facts, base_dir)) is None:
552
724
  return None
553
725
  return next((m.id for m in candidates if (m.entry.id, m.variant.quant) == pick), None)
@@ -20,6 +20,8 @@ from pathlib import Path
20
20
  from localmodels import (
21
21
  app,
22
22
  deploy,
23
+ engines,
24
+ frontend,
23
25
  harness,
24
26
  hosts,
25
27
  library_gateway,
@@ -81,13 +83,18 @@ def _room(facts: HostFacts, model: Model, record: Record, freed: dict[str, int])
81
83
  require_live=True,
82
84
  )
83
85
  except deploy.AgentMemoryError as exc:
86
+ refused_pool = "system" if exc.memory == "system memory" else record["pool"]
84
87
  raise LibraryError(
85
88
  "LOAD_NO_ROOM",
86
- f"{model.id} does not fit {record['pool']} now",
87
- pool=record["pool"],
89
+ f"{model.id} does not fit {refused_pool} now",
90
+ pool=refused_pool,
88
91
  need_bytes=exc.needed_bytes,
89
92
  free_bytes=exc.available_bytes,
90
93
  ) from None
94
+ except engines.CudaDriverError as exc:
95
+ raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc)) from None
96
+ except engines.EngineUnavailableError as exc:
97
+ raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc)) from None
91
98
  except plan_envelope.PlanError as exc: # its pool is gone, hidden, or under critical pressure
92
99
  need = record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"])
93
100
  raise LibraryError(
@@ -203,14 +210,19 @@ def _serve(
203
210
  require_live=True,
204
211
  )
205
212
  except deploy.AgentMemoryError as exc: # after --unload: no longer a refusal
213
+ refused_pool = "system" if exc.memory == "system memory" else record["pool"]
206
214
  raise LibraryError(
207
215
  "LOAD_NO_ROOM",
208
- f"{model.id} does not fit {record['pool']} now",
216
+ f"{model.id} does not fit {refused_pool} now",
209
217
  failed=True,
210
- pool=record["pool"],
218
+ pool=refused_pool,
211
219
  need_bytes=exc.needed_bytes,
212
220
  free_bytes=exc.available_bytes,
213
221
  ) from None
222
+ except engines.CudaDriverError as exc:
223
+ raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc), failed=True) from None
224
+ except engines.EngineUnavailableError as exc:
225
+ raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc), failed=True) from None
214
226
  except library_pricing.LiveMemoryUnavailable as exc:
215
227
  raise LibraryError(
216
228
  "LOAD_NO_ROOM",
@@ -258,6 +270,12 @@ def _start(
258
270
  handle.update("load", done, len(steps), load_step=load_step)
259
271
  progress(model.id, "load", done, len(steps), load_step=load_step)
260
272
 
273
+ if reqs := plan["launch"].get("frontend_requirements"):
274
+ try:
275
+ frontend.install(str(plan["launch"]["frontend_base_dir"]), str(reqs))
276
+ except frontend.FrontendError as exc:
277
+ raise _fail(record, LibraryError("ENGINE_START_FAILED", str(exc))) from None
278
+
261
279
  finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
262
280
  if not finished["ok"]:
263
281
  error = LibraryError(_start_code(finished), str(finished.get("error") or "start failed"))
@@ -313,6 +331,7 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
313
331
  stale server of the model itself give back. The caller commits its own reservation before
314
332
  releasing the lock, so the next claimant sees it."""
315
333
  freed: dict[str, int] = {}
334
+ catalog = library_pricing.entries()
316
335
  for target in [*targets, *([record] if record["state"] != "idle" else [])]:
317
336
  # A server that does not answer (failed, crashed, already stopped) is not counted:
318
337
  # ``facts`` already count a gone one's memory as free (on a Mac its weights as file
@@ -321,6 +340,10 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
321
340
  continue
322
341
  pool = target["pool"]
323
342
  freed[pool] = freed.get(pool, 0) + library_pricing.memory_bytes(target["plan"])
343
+ if library_pricing.gpu_index(pool) is not None:
344
+ freed["system"] = freed.get("system", 0) + library_pricing.host_ram_bytes(
345
+ target["plan"], catalog
346
+ )
324
347
  _room(facts, model, record, freed)
325
348
 
326
349
 
@@ -76,6 +76,7 @@ class _JobSince20261113(TypedDict, total=False):
76
76
  source: str # download source label: huggingface | modelscope | custom | cache
77
77
  connections: int # active parallel download connections
78
78
  load_step: str # load sub-step: prepare | start | load | warm
79
+ error: Problem # a download that stopped cleanly: status shows why; cancel discards it
79
80
 
80
81
 
81
82
  class Job(_JobSince20261113):
@@ -233,6 +234,21 @@ def clear_job(model: str) -> None:
233
234
  path.unlink(missing_ok=True)
234
235
 
235
236
 
237
+ def fail_job(job: Job, error: Problem) -> None:
238
+ """Under ``locked()``: end the job's live claim while keeping its record and error on disk so
239
+ ``status`` reports why it stopped, ``cancel`` discards its partials, and a new download
240
+ resumes them."""
241
+ job["error"] = error
242
+ job["updated_at"] = utc_now()
243
+ hosts.save_private(job_path(job["model"]), job)
244
+ for path in (
245
+ cancel_path(job["model"]),
246
+ pid_path(job["model"]),
247
+ Path(str(pid_path(job["model"])) + ".identity.json"),
248
+ ):
249
+ path.unlink(missing_ok=True)
250
+
251
+
236
252
  class JobHandle:
237
253
  """This process's job: progress written for ``status``, at most once a second."""
238
254