@simplexai/localmodels-darwin-arm64 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
@@ -76,18 +76,21 @@ def _magpie(doc: hosts.Owned, plan: StackPlan, notes: list[str]) -> str:
76
76
 
77
77
 
78
78
  def _gateway(plan: StackPlan | None, notes: list[str]) -> tuple[str, str]:
79
- if plan is None:
80
- doc = hosts.load_owned()
81
- if doc["gateway"].get("bifrost") or doc["gateway"]["started"]:
82
- return "failed: saved stack plan unavailable; gateway left untouched", "unknown"
83
- return "none", "none"
84
- doc = hosts.load_owned(plan["harness"]["tools_dir"])
79
+ """Stop the gateway this tool started. Bifrost's own record proves it ours, so it stops
80
+ also without a saved stack plan: the model library starts it with none (Linger's quit and
81
+ uninstall, GitHub linger#178). A Magpie this tool started needs the plan's tools
82
+ directory and is left untouched without it."""
83
+ doc = hosts.load_owned(plan["harness"]["tools_dir"] if plan else hosts.TOOLS_DIR)
85
84
  record = doc["gateway"].get("bifrost")
86
85
  results: list[tuple[str, str]] = []
87
86
  if record:
88
87
  results.append((_bifrost(record), "Bifrost"))
89
88
  if doc["gateway"]["started"]:
90
- results.append((_magpie(doc, plan, notes), "Magpie"))
89
+ results.append(
90
+ (_magpie(doc, plan, notes), "Magpie")
91
+ if plan is not None
92
+ else ("failed: saved stack plan unavailable; gateway left untouched", "unknown")
93
+ )
91
94
  for prefix in ("failed", "stopped", "kept", "not-running"):
92
95
  found = next((r for r in results if r[0].startswith(prefix)), None)
93
96
  if found:
@@ -95,6 +98,13 @@ def _gateway(plan: StackPlan | None, notes: list[str]) -> tuple[str, str]:
95
98
  return "none", "none"
96
99
 
97
100
 
101
+ def _library_loaded() -> list[str]:
102
+ """Models the library has loaded now, by its own records; none when it was never used."""
103
+ from localmodels import library_state
104
+
105
+ return [r["id"] for r in library_state.records() if r.get("state") == "loaded"]
106
+
107
+
98
108
  def down(out: Out = print) -> DownReport:
99
109
  if sys.platform != "darwin" and (error := platform_error(sys.platform)):
100
110
  raise StackError(error)
@@ -111,6 +121,11 @@ def _down(out: Out) -> DownReport:
111
121
  notes: list[str] = []
112
122
  # The gateway first: it routes to the services, as up starts it after them.
113
123
  gate, kind = _gateway(_latest() if members else None, notes)
124
+ if gate in ("stopped", "not-running") and _library_loaded():
125
+ notes.append(
126
+ "models the library loaded keep running without the gateway; unload them "
127
+ "(library unload) before quitting, or the next library load starts the gateway again"
128
+ )
114
129
  if gate.startswith("failed"):
115
130
  out(f"✗ gateway {gate}")
116
131
  parts: list[Part] = []
@@ -2,6 +2,8 @@ from __future__ import annotations
2
2
 
3
3
  import io
4
4
  import json
5
+ import threading
6
+ import time
5
7
  from collections.abc import Callable, Mapping, Sequence
6
8
  from typing import Literal, Protocol, TypedDict, runtime_checkable
7
9
 
@@ -300,3 +302,60 @@ class ToolEvents(io.StringIO):
300
302
  self.log(str(event.get("message", "")))
301
303
  elif event.get("event") == "progress":
302
304
  forward(self.log, "tools", "download", event)
305
+
306
+
307
+ class CombinedEvents(ToolEvents):
308
+ """ToolEvents for files downloading together on several threads: their progress events
309
+ become one download of the total bytes, which never goes back; the rate counts only bytes
310
+ that came over the network."""
311
+
312
+ def __init__(self, log: Callable[[str], None], sizes: Mapping[str, int]) -> None:
313
+ super().__init__(log)
314
+ self.sizes = dict(sizes)
315
+ self.done: dict[str, int] = {}
316
+ self.fetched: dict[str, int] = {}
317
+ self.shown = 0
318
+ self.start = time.monotonic()
319
+ self.lock = threading.Lock()
320
+
321
+ def write(self, text: str) -> int:
322
+ with self.lock:
323
+ return super().write(text)
324
+
325
+ def finished(self, name: str) -> None:
326
+ with self.lock:
327
+ self.done[name] = self.sizes[name]
328
+ self._report()
329
+
330
+ def _line(self, line: str) -> None:
331
+ try:
332
+ event = json.loads(line)
333
+ except (ValueError, RecursionError):
334
+ return
335
+ if not isinstance(event, dict) or event.get("event") != "progress":
336
+ super()._line(line)
337
+ return
338
+ name = event.get("file")
339
+ if not isinstance(name, str) or name not in self.sizes:
340
+ super()._line(line)
341
+ return
342
+ done = event.get("done")
343
+ if type(done) is int and 0 <= done:
344
+ count = min(done, self.sizes[name])
345
+ self.done[name] = max(self.done.get(name, 0), count)
346
+ self.fetched[name] = max(self.fetched.get(name, 0), count)
347
+ self._report()
348
+
349
+ def _report(self) -> None:
350
+ total = sum(self.sizes.values())
351
+ self.shown = max(self.shown, min(total, sum(self.done.values())))
352
+ elapsed = time.monotonic() - self.start
353
+ event: dict[str, object] = {
354
+ "event": "progress",
355
+ "phase": "download",
356
+ "done": self.shown,
357
+ "total": total,
358
+ }
359
+ if elapsed >= 1.0:
360
+ event["bytes_per_s"] = int(sum(self.fetched.values()) / elapsed)
361
+ forward(self.log, "tools", "download", event)
@@ -21,12 +21,10 @@ from localmodels import (
21
21
  )
22
22
  from localmodels.budget import (
23
23
  gib,
24
- gpu_conflicts,
25
24
  holders,
26
25
  host_ram,
27
26
  placements,
28
27
  sharing_cards,
29
- unknown_services,
30
28
  )
31
29
  from localmodels.context_policy import AGENT, AgentPosture, cache_floor_bytes, posture_for
32
30
  from localmodels.estimator import (
@@ -55,7 +53,7 @@ from localmodels.stack_hardware_text import (
55
53
  reboot_line as reboot_line,
56
54
  )
57
55
  from localmodels.stack_hardware_text import (
58
- slow_warning as slow_warning,
56
+ slow_advisory as slow_advisory,
59
57
  )
60
58
  from localmodels.stack_picks import picks
61
59
  from localmodels.stack_plan import (
@@ -78,10 +76,6 @@ _FIRST_TIER_RAM = 60 * GIB # 64 GB of RAM reads about 62 GiB
78
76
  UNIFIED_MEMORY_ENV = "LOCALMODELS_UNIFIED_MEMORY"
79
77
 
80
78
 
81
- class GpuOwnershipError(StackError):
82
- """No eligible GPU can be shared because discovery could not verify ownership."""
83
-
84
-
85
79
  def add_arguments(parser: argparse._ActionsContainer) -> None:
86
80
  """``--unified-memory``, which ``stack plan``, ``install``, ``stack hardware`` and
87
81
  ``setup inspect`` share; LOCALMODELS_UNIFIED_MEMORY is its default."""
@@ -138,11 +132,9 @@ def decision_reserve(card_budget_bytes: int, options: StackOptions) -> int:
138
132
 
139
133
 
140
134
  def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False) -> list[int]:
141
- """Single-card choices by free memory; foreign GPU work needs explicit sharing."""
142
- if share_gpu and unknown_services(facts):
143
- raise GpuOwnershipError(
144
- "GPU service owners unknown; explicit sharing cannot skip the unknown-service check"
145
- )
135
+ """Single-card choices by free memory. A card with foreign GPU work needs explicit sharing;
136
+ with it, who else uses the card, known or not, does not matter: the free memory decides,
137
+ with the usual margins (roadmap decision 60)."""
146
138
  if metal.device(facts) is not None:
147
139
  if gpu not in (None, 0):
148
140
  raise StackError(f"this computer has one Metal GPU (GPU 0), no GPU {gpu}")
@@ -156,12 +148,8 @@ def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False)
156
148
  raise StackError(
157
149
  f"no placeable GPU {gpu} here (usable cards: {found}; MIG-mode cards excluded)"
158
150
  )
159
- if share_gpu and gpu not in {g["index"] for g in sharing_cards(facts, 0)}:
160
- raise GpuOwnershipError("GPU process owners unknown; cannot share this GPU")
161
151
  return [gpu]
162
152
  allowed = {g["index"] for g in sharing_cards(facts, 0)} if share_gpu else set()
163
- if share_gpu and singles and not allowed and gpu_conflicts(facts):
164
- raise GpuOwnershipError("GPU process owners unknown; cannot share any GPU")
165
153
  free = [
166
154
  p.gpu_indices[0]
167
155
  for p in singles
@@ -171,14 +159,12 @@ def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False)
171
159
 
172
160
 
173
161
  def check_shared_start(
174
- part: Plan, facts: HostFacts, *, options: StackOptions | None = None, shared: bool = True
162
+ part: Plan, facts: HostFacts, *, options: StackOptions | None = None
175
163
  ) -> None:
176
- """Recheck free VRAM and ownership before starting; sharing needs all discovery sections."""
177
- from localmodels import budget, hosts, stack_lifecycle
164
+ """Recheck free VRAM before starting. Shared or not, an unknown owner of other GPU work no
165
+ longer refuses (roadmap decision 60): the card's free memory, less the margins, decides."""
166
+ from localmodels import hosts, stack_lifecycle
178
167
 
179
- services = facts.get("services")
180
- if budget.gpu_users_unknown(facts) or (shared and (unknown_services(facts) or not services)):
181
- raise StackError("GPU service owners unknown; cannot start a model that shares the GPU")
182
168
  for record in hosts.records("local"):
183
169
  if (
184
170
  record["plan"]["model"] == part["model"]
@@ -199,8 +185,6 @@ def check_shared_start(
199
185
  raise StackError("the GPU-sharing model has no VRAM budget or no approved GPU placement")
200
186
  for target in assigned:
201
187
  card = next((g for g in facts.get("gpus") or [] if g["uuid"] == target["uuid"]), None)
202
- if shared and card and card["index"] not in {g["index"] for g in sharing_cards(facts, 0)}:
203
- raise StackError("GPU process owners unknown; cannot start a shared model")
204
188
  reserve = (
205
189
  decision_reserve(component.auto_budget(card["total_bytes"]), options)
206
190
  if card and options
@@ -208,7 +192,12 @@ def check_shared_start(
208
192
  )
209
193
  margin = AGENT_VRAM_RESERVE_BYTES if options is not None else component.VRAM_MARGIN
210
194
  if card is None or card["free_bytes"] < needed + margin + reserve:
211
- raise StackError("free VRAM too low for the approved shared model; recheck resources")
195
+ free = gib(card["free_bytes"]) if card else "no such card"
196
+ raise StackError(
197
+ f"free VRAM too low for the approved shared model ({free} free, "
198
+ f"{gib(needed + margin + reserve)} needed); close programs that use the GPU "
199
+ "and retry"
200
+ )
212
201
 
213
202
 
214
203
  def shared_start_guard(
@@ -351,7 +340,9 @@ def llm_fits(
351
340
  "decode_tok_s": round(speed.tok_s, 1),
352
341
  "decode_basis": speed.basis,
353
342
  }
354
- stack_warm_store.apply_fit_measurement(facts, index, fit)
343
+ if note := cat.decode_advisory(speed.tok_s, measured=speed.basis == "measured-decode"):
344
+ fit["decode_advisory"] = note
345
+ _apply_fit_measurement(facts, index, fit)
355
346
  if llm_rank.windows_fallback(entry, facts):
356
347
  fit["candidate_fallback"] = True
357
348
  tok_s = float(fit["decode_tok_s"]) if fit["decode_tok_s"] is not None else -1.0
@@ -361,7 +352,7 @@ def llm_fits(
361
352
  (f["quality"] for _, f in found if not f.get("candidate_fallback")), default=-1
362
353
  )
363
354
  for fit in stack_auto.card_fits(facts, index, options, llama_score):
364
- stack_warm_store.apply_fit_measurement(facts, index, fit)
355
+ _apply_fit_measurement(facts, index, fit)
365
356
  found.append(((fit["quality"], -1.0), fit))
366
357
  found = [row for row in found if not row[1].get("candidate_fallback")] or found
367
358
  default_id = llm_rank.listed_default(facts, [(f["id"], f["quality"]) for _, f in found])
@@ -371,6 +362,18 @@ def llm_fits(
371
362
  ]
372
363
 
373
364
 
365
+ def _apply_fit_measurement(facts: HostFacts, index: int, fit: LlmFit) -> None:
366
+ measured = stack_warm_store.lookup(facts, index, fit["id"], fit["quant"])
367
+ if measured is None:
368
+ return
369
+ fit["decode_tok_s"] = round(measured, 1)
370
+ fit["decode_basis"] = "measured-decode"
371
+ if note := cat.decode_advisory(measured, measured=True):
372
+ fit["decode_advisory"] = note
373
+ else:
374
+ fit.pop("decode_advisory", None)
375
+
376
+
374
377
  def tier(facts: HostFacts, profile: str | None = None) -> str:
375
378
  """The hardware tier the largest NVIDIA card and the RAM put this host in, and what the
376
379
  product says about it (product.md: only 24 GB + 64 GB is delivered; others need their own
@@ -585,6 +588,9 @@ def view(facts: HostFacts, options: StackOptions, posture: AgentPosture | None)
585
588
  return seen
586
589
 
587
590
 
588
- def snapshot(facts: HostFacts, options: StackOptions) -> Hardware:
591
+ def snapshot(facts: HostFacts, options: StackOptions, llm: Plan | None = None) -> Hardware:
589
592
  """The copy a stack plan keeps: the readings it was priced against, without LLM lists."""
590
- return view(facts, options, None)
593
+ readings = view(facts, options, None)
594
+ if llm is not None and (advisory := slow_advisory(facts, llm)):
595
+ readings["llm_decode_advisory"] = advisory
596
+ return readings
@@ -3,12 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from localmodels import catalog as cat
6
- from localmodels import catalog_recipes, console, gpu_specs, metal, stack_capacity
7
- from localmodels.budget import gib
6
+ from localmodels import catalog_recipes, console, metal, stack_capacity, stack_warm_store
7
+ from localmodels.budget import gib, placements
8
8
  from localmodels.estimator import (
9
9
  AGENT_DISPLAY_RESERVE_BYTES,
10
10
  AGENT_VRAM_SAFETY_BYTES,
11
- HardwareBudget,
12
11
  )
13
12
  from localmodels.probe import HostFacts
14
13
  from localmodels.records import Plan
@@ -136,16 +135,9 @@ def lines(hw: Hardware, command: str) -> list[str]:
136
135
  else " other programs use this card, so --llm auto skips "
137
136
  f"it; when sharing is confirmed, use --gpu {c['index']} --share-gpu"
138
137
  )
139
- slow = [
140
- f
141
- for f in c["llm"][:1]
142
- if f["decode_tok_s"] is not None and f["decode_tok_s"] < cat.PLEASANT_FLOOR_TOK_S
143
- ]
144
- if slow:
145
- out.append(
146
- " note: the first choice's estimated decode is below the "
147
- f"pleasant floor of {cat.PLEASANT_FLOOR_TOK_S:g} tok/s"
148
- )
138
+ for fit in c["llm"][:1]:
139
+ if note := fit.get("decode_advisory"):
140
+ out.append(f" note: first choice's {note}")
149
141
  out += stack_capacity.lines(hw, command)
150
142
  out.append(
151
143
  f" RAM {gib(hw['ram_total_bytes'])}, available {gib(hw['ram_available_bytes'])}"
@@ -229,28 +221,41 @@ def reboot_line(hw: Hardware | None, llm: Plan, command: str) -> str:
229
221
  )
230
222
 
231
223
 
232
- def slow_warning(facts: HostFacts, llm: Plan) -> list[str]:
233
- """A note when the stack's LLM, priced at its card's spec bandwidth, decodes below the
234
- pleasant floor; silent where the card model has no published figure."""
235
- model, index = llm["model"], plan_card(llm, facts)
236
- gpu = next((g for g in facts.get("gpus") or [] if g["index"] == index), None)
237
- mid = model.get("id")
238
- entry = cat.find_entry(mid) if isinstance(mid, str) else None
239
- variant = (
240
- next((v for v in entry.variants if v.quant == model.get("quant")), None) if entry else None
241
- )
242
- bandwidth = gpu_specs.bandwidth_gb_s(gpu["name"]) if gpu else None
243
- if entry is None or variant is None or gpu is None or bandwidth is None:
244
- return []
245
- budget = HardwareBudget(0, 0, 0, gpu_bandwidth_gb_s=bandwidth)
246
- tok_s = cat.decode_estimate(entry, variant, budget).tok_s
247
- if tok_s >= cat.PLEASANT_FLOOR_TOK_S:
248
- return []
249
- return [
250
- f"LLM: at the {gpu['name']} spec memory bandwidth of {bandwidth:g} GB/s, single-stream "
251
- f"decode is about {tok_s:.0f} tok/s (estimate), below the pleasant floor of "
252
- f"{cat.PLEASANT_FLOOR_TOK_S:g} tok/s; --llm can pick a smaller model"
253
- ]
224
+ def slow_advisory(facts: HostFacts, llm: Plan) -> str | None:
225
+ model = llm["model"]
226
+ model_id, quant = model.get("id"), model.get("quant")
227
+ if not isinstance(model_id, str) or not isinstance(quant, str):
228
+ return None
229
+ identified, index = stack_warm_store.resolve_part_gpu(llm, facts)
230
+ if not identified or index is None:
231
+ return None
232
+ seen = stack_warm_store.lookup(facts, index, model_id, quant)
233
+ if seen is not None:
234
+ note = cat.decode_advisory(seen, measured=True)
235
+ else:
236
+ entry = cat.find_entry(model_id)
237
+ placement = next(
238
+ (
239
+ target
240
+ for target in placements(facts, planning=False)
241
+ if not target.pooled
242
+ and (target.backend == "metal" or target.gpu_indices == (index,))
243
+ ),
244
+ None,
245
+ )
246
+ if (
247
+ placement is None
248
+ or entry is None
249
+ or entry.runtime != "llama.cpp"
250
+ or llm["launch"].get("spilled")
251
+ ):
252
+ return None
253
+ variant = next((v for v in entry.variants if v.quant == quant), None)
254
+ if variant is None:
255
+ return None
256
+ speed = cat.decode_estimate(entry, variant, placement.budget, backend=placement.backend)
257
+ note = cat.decode_advisory(speed.tok_s, measured=speed.basis == "measured-decode")
258
+ return f"LLM: {note}; --llm can pick a smaller model" if note else None
254
259
 
255
260
 
256
261
  def agent_label(llm: Plan) -> str:
@@ -31,7 +31,7 @@ from localmodels import (
31
31
  from localmodels.budget import gib
32
32
  from localmodels.records import FinishedRecord, Plan, ProgressEvent
33
33
  from localmodels.remote_ops import RemoveParams
34
- from localmodels.remote_ops_service import listener_problem
34
+ from localmodels.remote_ops_service import group_pids, listener_problem
35
35
  from localmodels.stack_plan import command, start_here
36
36
  from localmodels.stack_remove import plan_params as plan_params
37
37
  from localmodels.transport import Executor
@@ -124,9 +124,18 @@ def restart_if_changed(executor: Executor, plan: Plan) -> None:
124
124
 
125
125
 
126
126
  def deployment_pids(plan: Plan) -> list[int]:
127
- """Current process identities of this exact deployment, including its unit children."""
127
+ """Current process identities of this exact deployment, including its unit children. A
128
+ nohup or launchd deployment is its recorded process and the group that process leads: the
129
+ server a launcher (slot_cache.py) starts is the one on the card's process list. Who holds
130
+ the port is still asked of the recorded process alone (_not_serving). A Windows service is
131
+ one process with no launcher: its recorded pid, with no look at other processes."""
128
132
  state, pid = _service(plan)
129
- return _service_pids(plan, pid) if state == "active" and pid is not None else []
133
+ if state != "active" or pid is None:
134
+ return []
135
+ systemd = sys.platform.startswith("linux") and plan["service"]["kind"] == "systemd-user"
136
+ if systemd or sys.platform == "win32":
137
+ return _service_pids(plan, pid)
138
+ return group_pids(pid)
130
139
 
131
140
 
132
141
  def _not_serving(plan: Plan, state: str, pid: int | None) -> str | None:
@@ -215,7 +215,10 @@ def parts(
215
215
  if e.runtime == "mlx-lm" and e.variants[-1].size_bytes + (1 << 30) <= MEMORY
216
216
  )
217
217
  entry = (
218
- llm_rank.preview_entry(entries, "mlx-lm")
218
+ (
219
+ llm_rank.preview_entry(entries, "mlx-lm")
220
+ or (max(entries, key=lambda e: (e.quality, e.id)) if entries else None)
221
+ )
219
222
  if options["llm"] == "auto"
220
223
  else next((e for e in entries if e.id == options["llm"]), None)
221
224
  )
@@ -26,6 +26,7 @@ ROLES = ("smartest", "fastest")
26
26
 
27
27
  class _FitPolicy(TypedDict, total=False):
28
28
  candidate_fallback: bool
29
+ decode_advisory: str
29
30
 
30
31
 
31
32
  class Fit(_FitPolicy):
@@ -132,7 +133,11 @@ def label(pick: Fit) -> str:
132
133
  speed = "speed unavailable"
133
134
  else:
134
135
  measured = pick["decode_basis"] == "measured-decode"
135
- speed = f"{tok_s:.0f} tok/s " + ("measured" if measured else "estimated")
136
+ shown = f"{tok_s:.0f}"
137
+ floor = f"{cat.PLEASANT_FLOOR_TOK_S:g}"
138
+ if shown == floor and pick.get("decode_advisory"):
139
+ shown = f"<{floor}"
140
+ speed = f"{shown} tok/s " + ("measured" if measured else "estimated")
136
141
  candidate = " · candidate product fallback" if pick.get("candidate_fallback") else ""
137
142
  return f"{pick['id']} {pick['quant']} · {score} · {speed}{candidate}"
138
143
 
@@ -251,6 +251,7 @@ class _HardwareSince20261112(_HardwareSince20261031, total=False):
251
251
  # The LLMs offered for this computer, smartest first, then the fastest when it is another
252
252
  # model (stack_picks.picks). A plan's snapshot keeps them so its summary names the other.
253
253
  picks: list[Pick]
254
+ llm_decode_advisory: str
254
255
 
255
256
 
256
257
  class Hardware(_HardwareSince20261112):
@@ -173,10 +173,15 @@ def _cards(target: StackPlan, facts: HostFacts, share_gpu: bool) -> list[str]:
173
173
  if isinstance(placed, list)
174
174
  else []
175
175
  )
176
- # Sharing, or Metal, needs every discovery section read; otherwise knowing who uses the
177
- # GPUs is enough, as at plan time (budget.gpu_users_unknown).
178
- strict = share_gpu or stack_hardware.on_metal(part)
179
- if cards and (unknown_services(facts) if strict else gpu_users_unknown(facts)):
176
+ # Metal needs every discovery section read; an unshared card needs to know who uses
177
+ # the GPUs, as at plan time (budget.gpu_users_unknown). Sharing consent decides by free
178
+ # VRAM whoever else is there (roadmap decision 60).
179
+ unknown = (
180
+ bool(unknown_services(facts))
181
+ if stack_hardware.on_metal(part)
182
+ else not share_gpu and gpu_users_unknown(facts)
183
+ )
184
+ if cards and unknown:
180
185
  found.append(
181
186
  f"{part['name']}: GPU service discovery unknown; cannot confirm who uses the GPU"
182
187
  )
@@ -243,6 +243,8 @@ def summary(plan: StackPlan, path: Path, *, apply_line: bool = True) -> str:
243
243
  lines += preflight_lines(plan)
244
244
  lines.append(hardware.reboot_line(plan.get("hardware"), llm, command()))
245
245
  lines += note_lines(plan["warnings"])
246
+ if seen and (advisory := seen.get("llm_decode_advisory")):
247
+ lines += note_lines([advisory])
246
248
  lines += stack_update.summary_lines(plan)
247
249
  if missing:
248
250
  lines.append(missing)
@@ -12,6 +12,7 @@ from __future__ import annotations
12
12
 
13
13
  import argparse
14
14
  import json
15
+ import os
15
16
  import sys
16
17
  import time
17
18
  from collections.abc import Callable
@@ -143,28 +144,18 @@ def _admit_start(part: Plan, share_gpu: bool) -> None:
143
144
  facts = app.probe(hosts.LOCAL_ID)
144
145
  services = facts.get("services")
145
146
  metal = stack_hardware.on_metal(part)
146
- # Sharing a card needs every discovery section read; an unshared start only needs to know
147
- # who uses the GPUs, as at plan time (budget.gpu_users_unknown).
148
- shared_unknown = bool(unknown_services(facts)) or (
149
- not metal
150
- and services is not None
151
- and (
152
- services.get("compute_processes") is None
153
- or (
154
- services.get("containers") is None
155
- and services.get("unknown", {}).get("containers") != "not-installed"
156
- )
157
- )
158
- )
159
- if share_gpu:
160
- unknown = shared_unknown
161
- elif metal:
162
- unknown = bool(unknown_services(facts))
147
+ # An unshared start needs to know who uses the GPUs, as at plan time
148
+ # (budget.gpu_users_unknown); a Mac needs every discovery section. With sharing consent an
149
+ # unknown owner or an unreadable section no longer refuses: the free VRAM decides
150
+ # (roadmap decision 60).
151
+ if metal:
152
+ unknown = services is None or bool(unknown_services(facts))
163
153
  else:
164
- unknown = gpu_users_unknown(facts)
165
- if services is None or unknown:
154
+ unknown = not share_gpu and gpu_users_unknown(facts)
155
+ if unknown:
166
156
  raise StackError(
167
157
  "GPU service discovery unknown; cannot confirm who uses the GPU, so no model starts"
158
+ + ("" if metal else "; add --share-gpu to start it beside them by free VRAM")
168
159
  )
169
160
  conflicts = gpu_conflicts(facts)
170
161
  held = [f"{uuid}: {', '.join(conflicts[uuid])}" for uuid in cards if conflicts.get(uuid)]
@@ -175,7 +166,20 @@ def _admit_start(part: Plan, share_gpu: bool) -> None:
175
166
  + ". Add --share-gpu once you confirm they can share it"
176
167
  )
177
168
  if not metal:
178
- stack_hardware.check_shared_start(part, facts, shared=share_gpu)
169
+ stack_hardware.check_shared_start(part, facts)
170
+
171
+
172
+ def _unstartable(part: Plan, state: str) -> str:
173
+ """Why waiting for a part that is not running is of no use: the program its service starts
174
+ with is gone from disk (a tool kit whose Python the launcher of an agent LLM runs on, or
175
+ an engine, was removed). Only a new plan names programs that exist."""
176
+ program = os.path.expanduser(part["service"]["argv"][0])
177
+ if state == "active" or not os.path.isabs(program) or os.path.exists(program):
178
+ return ""
179
+ return (
180
+ f"{program} is missing, so this service cannot start; plan and apply the stack "
181
+ f"again ({command()} stack plan, then stack apply)"
182
+ )
179
183
 
180
184
 
181
185
  def up(
@@ -246,6 +250,9 @@ def _up(plan: StackPlan, share_gpu: bool, timeout: float, out: Out) -> UpReport:
246
250
  row["state"], row["health"] = lifecycle.liveness(part)
247
251
  if lifecycle.healthy(row["state"], row["health"]):
248
252
  waiting.remove(part)
253
+ elif reason := _unstartable(part, row["state"]):
254
+ row["action"], row["detail"] = "failed", reason
255
+ waiting.remove(part)
249
256
  if waiting and time.monotonic() < deadline:
250
257
  time.sleep(POLL_SECONDS)
251
258
  else:
@@ -154,7 +154,9 @@ def reclaimed(facts: HostFacts, pids: set[int]) -> HostFacts:
154
154
  gone = {id(p) for p in mine}
155
155
  freed: dict[str, int] = {}
156
156
  for p in mine:
157
- freed[p["gpu_uuid"]] = freed.get(p["gpu_uuid"], 0) + (p["used_bytes"] or 0)
157
+ # A Mac process's file cache is already in the RAM available (cached_bytes).
158
+ back = max(0, (p["used_bytes"] or 0) - p.get("cached_bytes", 0))
159
+ freed[p["gpu_uuid"]] = freed.get(p["gpu_uuid"], 0) + back
158
160
  seen_services = seen.get("services")
159
161
  if seen_services is not None:
160
162
  seen_services["compute_processes"] = [p for p in procs or [] if id(p) not in gone]
@@ -58,6 +58,7 @@ from localmodels.records import Plan
58
58
  from localmodels.stack_plan import StackPlan, command
59
59
 
60
60
  SCHEMA: Literal["localmodels.stack-warm/v1"] = "localmodels.stack-warm/v1"
61
+ DECODE_TIMING: Literal["engine-timing"] = "engine-timing"
61
62
  HOLDERS_SHOWN = 5
62
63
  HOLDER_FLOOR_BYTES = 200 << 20 # smaller processes are noise next to a model
63
64
  REQUEST_TIMEOUT_S = 180 # a cold first request on a large model
@@ -95,7 +96,12 @@ class Step(TypedDict):
95
96
  hint: str | None # a command for an administrator; this tool runs it only under --sudo
96
97
 
97
98
 
98
- class LlmWarm(TypedDict):
99
+ class _WarmFallback(TypedDict, total=False):
100
+ wall_tok_s: float
101
+ decode_basis: Literal["engine-timing"]
102
+
103
+
104
+ class LlmWarm(_WarmFallback):
99
105
  name: str
100
106
  ok: bool
101
107
  detail: str
@@ -352,17 +358,12 @@ def _chat(
352
358
  return time.monotonic() - started, doc if isinstance(doc, dict) else {}
353
359
 
354
360
 
355
- def _decode_speed(doc: dict[str, object], seconds: float) -> float | None:
356
- """Decode tok/s: llama-server's own ``timings``; else completion tokens over the wall time,
357
- which includes the prefill and so reads low."""
361
+ def _decode_speed(doc: dict[str, object]) -> float | None:
358
362
  timings = doc.get("timings")
359
363
  decode = timings.get("predicted_per_second") if isinstance(timings, dict) else None
360
- if isinstance(decode, int | float) and decode > 0:
361
- return float(decode)
362
- usage = doc.get("usage")
363
- tokens = usage.get("completion_tokens") if isinstance(usage, dict) else None
364
- if isinstance(tokens, int) and tokens > 0 and seconds > 0:
365
- return tokens / seconds
364
+ if isinstance(decode, int | float) and not isinstance(decode, bool):
365
+ if 0 < decode < float("inf"):
366
+ return float(decode)
366
367
  return None
367
368
 
368
369
 
@@ -418,7 +419,14 @@ def warm_llm(part: Plan, chat: Chat = _chat) -> LlmWarm:
418
419
  seen["detail"] = f"no answer from {url}: {exc}; run {command()} stack up"
419
420
  return seen
420
421
  seen["first_s"], seen["second_s"] = first, second
421
- seen["decode_tok_s"] = _decode_speed(doc, second)
422
+ seen["decode_tok_s"] = _decode_speed(doc)
423
+ if seen["decode_tok_s"] is not None:
424
+ seen["decode_basis"] = DECODE_TIMING
425
+ else:
426
+ usage = doc.get("usage")
427
+ tokens = usage.get("completion_tokens") if isinstance(usage, dict) else None
428
+ if type(tokens) is int and 0 < tokens <= WARM_TOKENS and second > 0:
429
+ seen["wall_tok_s"] = tokens / second
422
430
  seen["ok"] = True
423
431
  seen["detail"] = "loaded and answering"
424
432
  return seen
@@ -562,6 +570,8 @@ def lines(report: Report) -> list[str]:
562
570
  speed = (
563
571
  f"decode {llm['decode_tok_s']:.1f} tok/s"
564
572
  if llm["decode_tok_s"]
573
+ else f"completion {llm['wall_tok_s']:.1f} tok/s (wall time, including prefill)"
574
+ if "wall_tok_s" in llm
565
575
  else "decode speed not reported"
566
576
  )
567
577
  out.append(