@simplexai/localmodels-linux-x64 0.1.0-dev.38 → 0.1.0-dev.40

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 (82) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +81 -73
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/auth_proxy.py +74 -16
  6. package/modules/localmodels/bifrost_config.py +19 -0
  7. package/modules/localmodels/budget.py +27 -18
  8. package/modules/localmodels/catalog.json +18 -6
  9. package/modules/localmodels/chat_template.py +35 -0
  10. package/modules/localmodels/cli_parser.py +26 -3
  11. package/modules/localmodels/deploy.py +44 -10
  12. package/modules/localmodels/deploy_steps.py +6 -3
  13. package/modules/localmodels/download-mirrors.json +52 -4
  14. package/modules/localmodels/engines-b11583.json +20 -4
  15. package/modules/localmodels/engines-b12167.json +5 -1
  16. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  17. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  18. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  19. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  20. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  21. package/modules/localmodels/engines.json +55 -11
  22. package/modules/localmodels/frontend.py +5 -2
  23. package/modules/localmodels/gateway.py +2 -0
  24. package/modules/localmodels/gateway_bifrost.py +3 -0
  25. package/modules/localmodels/gateway_home.py +132 -0
  26. package/modules/localmodels/guard.py +15 -6
  27. package/modules/localmodels/harness.py +104 -37
  28. package/modules/localmodels/harness_gateway.py +9 -3
  29. package/modules/localmodels/harness_probe.py +5 -1
  30. package/modules/localmodels/hf_repo.py +15 -8
  31. package/modules/localmodels/library_gateway.py +28 -15
  32. package/modules/localmodels/library_jobs.py +7 -1
  33. package/modules/localmodels/library_serve.py +5 -0
  34. package/modules/localmodels/metal.py +29 -12
  35. package/modules/localmodels/metal_probe.py +16 -6
  36. package/modules/localmodels/npm_signatures.py +131 -0
  37. package/modules/localmodels/npm_transport.py +26 -10
  38. package/modules/localmodels/probe.py +4 -0
  39. package/modules/localmodels/process_identity.py +21 -5
  40. package/modules/localmodels/region.py +244 -0
  41. package/modules/localmodels/remote_ops.py +69 -13
  42. package/modules/localmodels/remote_ops_download.py +217 -10
  43. package/modules/localmodels/remote_ops_prepare.py +61 -8
  44. package/modules/localmodels/remote_ops_remove.py +15 -0
  45. package/modules/localmodels/remote_ops_service.py +10 -0
  46. package/modules/localmodels/runtime-lock.json +13 -13
  47. package/modules/localmodels/runtime_args.py +4 -2
  48. package/modules/localmodels/runtime_cli.py +76 -74
  49. package/modules/localmodels/runtime_discovery.py +58 -0
  50. package/modules/localmodels/runtime_install.py +103 -7
  51. package/modules/localmodels/runtime_io.py +64 -7
  52. package/modules/localmodels/runtime_pi.py +122 -0
  53. package/modules/localmodels/runtime_process.py +101 -15
  54. package/modules/localmodels/runtime_releases.py +51 -71
  55. package/modules/localmodels/service_deployment.py +5 -3
  56. package/modules/localmodels/service_probe.py +146 -31
  57. package/modules/localmodels/setup_inspection.py +110 -14
  58. package/modules/localmodels/setup_text.py +13 -0
  59. package/modules/localmodels/slot_cache.py +467 -0
  60. package/modules/localmodels/source_byok.py +484 -0
  61. package/modules/localmodels/source_byok_probe.py +275 -0
  62. package/modules/localmodels/source_cli.py +426 -0
  63. package/modules/localmodels/stack_args.py +2 -1
  64. package/modules/localmodels/stack_binding.py +125 -5
  65. package/modules/localmodels/stack_capacity.py +3 -3
  66. package/modules/localmodels/stack_down.py +22 -7
  67. package/modules/localmodels/stack_events.py +62 -0
  68. package/modules/localmodels/stack_hardware.py +20 -17
  69. package/modules/localmodels/stack_lifecycle.py +12 -3
  70. package/modules/localmodels/stack_rollback.py +9 -4
  71. package/modules/localmodels/stack_up.py +27 -20
  72. package/modules/localmodels/stack_update.py +3 -1
  73. package/modules/localmodels/tools.json +1365 -14
  74. package/modules/localmodels/transport.py +2 -0
  75. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/METADATA +1 -1
  76. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/RECORD +78 -70
  77. package/package.json +1 -1
  78. package/tool.json +1 -1
  79. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/WHEEL +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/entry_points.txt +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/NOTICE +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -289,7 +289,8 @@ def add_plan_arguments(plan: argparse.ArgumentParser) -> None:
289
289
  default=deploy.hf_endpoint(),
290
290
  metavar="URL",
291
291
  help="where weights are downloaded from (default: $HF_ENDPOINT, else Hugging Face); "
292
- "faster sources of the same pinned files, such as ModelScope, are still tried",
292
+ "other sources of the same pinned files (ModelScope, hf-mirror.com) are still tried, "
293
+ "China-first in download region cn",
293
294
  )
294
295
  where.add_argument(
295
296
  "--offline",
@@ -3,11 +3,12 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import hashlib
6
+ import json
6
7
  import os
7
8
  from pathlib import Path
8
9
  from typing import TypedDict, cast
9
10
 
10
- from localmodels import harness, hosts, stack, stack_run
11
+ from localmodels import harness, hosts, runtime_discovery, stack, stack_run
11
12
  from localmodels import stack_lifecycle as lifecycle
12
13
  from localmodels.setup_text import Lang, text
13
14
  from localmodels.stack_plan import StackPlan, deployments
@@ -64,8 +65,46 @@ def _acceptance_ready(plan: StackPlan) -> bool:
64
65
  return bool(view and view["ok"])
65
66
 
66
67
 
67
- def _deployments_ready(plan: StackPlan, owned: hosts.Owned) -> bool:
68
- parts = {part["name"]: part for part in deployments(plan)}
68
+ def _adopted(plan: StackPlan) -> set[str]:
69
+ """The plan's LLM components the library adopted (``library_convert``): from then on the
70
+ library loads, unloads, wires and may remove them, so their deployments, gateway route and
71
+ pi selection are no longer the stack's to check. The conversion marker names them, and
72
+ stays when ``library remove`` deletes the model's record; a converted record (an earlier
73
+ one may lack ``stack_provider``: the main LLM's) names them too. Read only; it never
74
+ converts."""
75
+ from localmodels import library_convert, library_state, stack_verify
76
+ from localmodels.library_model import library_id
77
+
78
+ try:
79
+ marker = json.loads((library_state.root() / library_convert.MARKER).read_text("utf-8"))
80
+ except (OSError, ValueError):
81
+ return set()
82
+ if not isinstance(marker, dict) or marker.get("plan_id") != plan["plan_id"]:
83
+ return set()
84
+ ids = set(marker.get("adopted") or [])
85
+ providers = {
86
+ r.get("stack_provider") or harness.LLM_PROVIDER
87
+ for r in library_state.records()
88
+ if r.get("converted")
89
+ }
90
+ return {
91
+ component
92
+ for component, part in stack_verify.parts(plan)
93
+ if component in library_convert.STACK_LLMS
94
+ and (
95
+ library_id(part["model"]["id"], part["model"]["quant"]) in ids
96
+ or library_convert.STACK_LLMS[component] in providers
97
+ )
98
+ }
99
+
100
+
101
+ def _deployments_ready(
102
+ plan: StackPlan, owned: hosts.Owned, adopted: frozenset[str] | set[str] = frozenset()
103
+ ) -> bool:
104
+ from localmodels import stack_verify
105
+
106
+ library = {part["name"] for component, part in stack_verify.parts(plan) if component in adopted}
107
+ parts = {part["name"]: part for part in deployments(plan) if part["name"] not in library}
69
108
  records = [
70
109
  record for record in hosts.records(hosts.LOCAL_ID) if record["plan"]["name"] in parts
71
110
  ]
@@ -211,6 +250,78 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
211
250
  }
212
251
 
213
252
 
253
+ def _stack_installed(plan: StackPlan, owned: hosts.Owned) -> bool:
254
+ """The Node.js and pi the plan installed are still in the manifest: ``stack remove``
255
+ deletes them and drops them from it. A tool the plan reused is no anchor."""
256
+ paths = [Path(t["path"]) for t in owned["tools"]]
257
+ for tool in plan["harness"]["tools"]:
258
+ if tool["action"] != "install" or tool["tool"] not in ("node", "pi"):
259
+ continue
260
+ wanted = Path(os.path.expanduser(tool["path"]))
261
+ if not any(wanted == path or path in wanted.parents for path in paths):
262
+ return False
263
+ return True
264
+
265
+
266
+ def _library_binding(
267
+ plan: StackPlan, owned: hosts.Owned, adopted: set[str], lang: Lang = "zh"
268
+ ) -> PiBinding | Reason:
269
+ """The stack's pi once the library adopted an LLM: the library unwires that LLM's route and
270
+ unpoints pi when the last stack LLM leaves, so pi's selection is not checked. The gateway
271
+ still is while anything the library did not adopt (the decision model, foundation
272
+ services, the other LLM) routes through it."""
273
+ from localmodels import bifrost_pi, gateway_bifrost, stack_verify
274
+
275
+ if not _stack_installed(plan, owned):
276
+ return _reason("deployment-unavailable", lang)
277
+ gateway = plan["harness"]["gateway"]
278
+ executable = Path(harness.tool_path(plan["harness"], "pi"))
279
+ environment = harness.gateway_environment(plan["harness"])
280
+ # The profile the stack's own binding reads: a Magpie plan on a shared daemon has none
281
+ # (KeyError, unavailable), never the user's ~/.pi/agent.
282
+ profile = (
283
+ bifrost_pi.pi_profile(environment)
284
+ if harness.gateway_kind(gateway) == "bifrost"
285
+ else Path(environment["PI_CODING_AGENT_DIR"]).expanduser()
286
+ )
287
+ if not executable.is_absolute() or not profile.is_absolute():
288
+ raise ValueError("Pi paths must be absolute")
289
+ fingerprint = _profile_fingerprint(executable, profile)
290
+ if any(component not in adopted for component, _ in stack_verify.parts(plan)):
291
+ if harness.gateway_kind(gateway) == "bifrost":
292
+ record = owned["gateway"].get("bifrost")
293
+ if not record or record["addr"] != gateway["addr"]:
294
+ return _reason("gateway-ownership", lang)
295
+ if not gateway_bifrost.owned_listener(record) or not gateway_bifrost.healthy(
296
+ gateway["addr"]
297
+ ):
298
+ return _reason("gateway-unavailable", lang)
299
+ else:
300
+ if owned["gateway"]["group"] != gateway["group"]:
301
+ return _reason("gateway-ownership", lang)
302
+ magpie = harness.tool_path(plan["harness"], "magpie")
303
+ env = {
304
+ **harness.checked_gateway_environment(plan["harness"]),
305
+ "PATH": os.pathsep.join([str(Path(magpie).parent), os.environ.get("PATH", "")]),
306
+ "MAGPIE_ADDR": gateway["addr"],
307
+ }
308
+ state = harness.inspect(
309
+ env=env,
310
+ tools_dir=plan["harness"]["tools_dir"],
311
+ approved=plan["harness"],
312
+ private_clients=True,
313
+ )
314
+ if not state["gateway_up"] or state.get("gateway_other_user"):
315
+ return _reason("gateway-unavailable", lang)
316
+ if _profile_fingerprint(executable, profile) != fingerprint:
317
+ return _reason("pi-config-changed", lang)
318
+ return {
319
+ "executable": str(executable),
320
+ "environment": {"PI_CODING_AGENT_DIR": str(profile)},
321
+ "configFingerprint": fingerprint,
322
+ }
323
+
324
+
214
325
  def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
215
326
  report: BindingReport = {
216
327
  "schema": "localmodels.stack-binding/v1",
@@ -234,12 +345,21 @@ def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
234
345
  report["reasons"] = [_reason("acceptance-unavailable", lang)]
235
346
  return report
236
347
  owned = hosts.load_owned(plan["harness"]["tools_dir"])
237
- if not _deployments_ready(plan, owned):
348
+ adopted = _adopted(plan)
349
+ if not _deployments_ready(plan, owned, adopted):
238
350
  report["reasons"] = [_reason("deployment-unavailable", lang)]
239
351
  return report
240
- binding = _pi_binding(plan, owned, lang)
352
+ binding = (
353
+ _library_binding(plan, owned, adopted, lang)
354
+ if adopted
355
+ else _pi_binding(plan, owned, lang)
356
+ )
241
357
  if "code" in binding:
242
358
  report["reasons"] = [cast(Reason, binding)]
359
+ elif not runtime_discovery.pi_loads_extensions([cast(PiBinding, binding)["executable"]]):
360
+ # localmodels before 0.1.0.dev39 installed pi without jiti; Linger starts pi with an
361
+ # extension on every run. stack apply replaces an owned one.
362
+ report["reasons"] = [_reason("pi-extensions-unavailable", lang)]
243
363
  else:
244
364
  report["ready"] = True
245
365
  report["pi"] = binding
@@ -18,9 +18,9 @@ from localmodels.probe import HostFacts
18
18
  from localmodels.stack_plan import CapacityFit, Hardware, StackOptions
19
19
 
20
20
  WDDM_NOTE = (
21
- "Windows WDDM GPU contexts can include desktop C+G apps; their presence does not "
22
- "identify an inference service, and per-process VRAM may be unavailable. "
23
- "Use current free VRAM for plans; sharing still needs explicit consent and known owners."
21
+ "Windows WDDM GPU contexts of the desktop, games and other apps do not block a plan; only "
22
+ "an inference server's needs --share-gpu, and per-process VRAM may be unavailable. Plans "
23
+ "use the current free VRAM."
24
24
  )
25
25
 
26
26
 
@@ -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,9 +2,13 @@ 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
 
10
+ from localmodels import region
11
+
8
12
  MAX_SAFE_INTEGER = 9_007_199_254_740_991
9
13
  MAX_EVENT_CHARS = 65_536
10
14
  STACK_PLAN_SECTIONS = (
@@ -293,7 +297,65 @@ class ToolEvents(io.StringIO):
293
297
  return
294
298
  if not isinstance(event, dict):
295
299
  return
300
+ region.observe(event)
296
301
  if event.get("event") == "log":
297
302
  self.log(str(event.get("message", "")))
298
303
  elif event.get("event") == "progress":
299
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)
@@ -19,7 +19,13 @@ from localmodels import (
19
19
  stack_warm_store,
20
20
  suite,
21
21
  )
22
- from localmodels.budget import gib, holders, host_ram, placements, sharing_cards, unknown_services
22
+ from localmodels.budget import (
23
+ gib,
24
+ holders,
25
+ host_ram,
26
+ placements,
27
+ sharing_cards,
28
+ )
23
29
  from localmodels.context_policy import AGENT, AgentPosture, cache_floor_bytes, posture_for
24
30
  from localmodels.estimator import (
25
31
  AGENT_VRAM_RESERVE_BYTES,
@@ -126,11 +132,9 @@ def decision_reserve(card_budget_bytes: int, options: StackOptions) -> int:
126
132
 
127
133
 
128
134
  def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False) -> list[int]:
129
- """Single-card choices by free memory; foreign GPU work needs explicit sharing."""
130
- if share_gpu and unknown_services(facts):
131
- raise StackError(
132
- "GPU service owners unknown; explicit sharing cannot skip the unknown-service check"
133
- )
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)."""
134
138
  if metal.device(facts) is not None:
135
139
  if gpu not in (None, 0):
136
140
  raise StackError(f"this computer has one Metal GPU (GPU 0), no GPU {gpu}")
@@ -144,8 +148,6 @@ def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False)
144
148
  raise StackError(
145
149
  f"no placeable GPU {gpu} here (usable cards: {found}; MIG-mode cards excluded)"
146
150
  )
147
- if share_gpu and gpu not in {g["index"] for g in sharing_cards(facts, 0)}:
148
- raise StackError("GPU process owners unknown; cannot share this GPU")
149
151
  return [gpu]
150
152
  allowed = {g["index"] for g in sharing_cards(facts, 0)} if share_gpu else set()
151
153
  free = [
@@ -157,14 +159,12 @@ def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False)
157
159
 
158
160
 
159
161
  def check_shared_start(
160
- part: Plan, facts: HostFacts, *, options: StackOptions | None = None, shared: bool = True
162
+ part: Plan, facts: HostFacts, *, options: StackOptions | None = None
161
163
  ) -> None:
162
- """Recheck free VRAM and ownership before starting; sharing needs all discovery sections."""
163
- 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
164
167
 
165
- services = facts.get("services")
166
- if budget.gpu_users_unknown(facts) or (shared and (unknown_services(facts) or not services)):
167
- raise StackError("GPU service owners unknown; cannot start a model that shares the GPU")
168
168
  for record in hosts.records("local"):
169
169
  if (
170
170
  record["plan"]["model"] == part["model"]
@@ -185,8 +185,6 @@ def check_shared_start(
185
185
  raise StackError("the GPU-sharing model has no VRAM budget or no approved GPU placement")
186
186
  for target in assigned:
187
187
  card = next((g for g in facts.get("gpus") or [] if g["uuid"] == target["uuid"]), None)
188
- if shared and card and card["index"] not in {g["index"] for g in sharing_cards(facts, 0)}:
189
- raise StackError("GPU process owners unknown; cannot start a shared model")
190
188
  reserve = (
191
189
  decision_reserve(component.auto_budget(card["total_bytes"]), options)
192
190
  if card and options
@@ -194,7 +192,12 @@ def check_shared_start(
194
192
  )
195
193
  margin = AGENT_VRAM_RESERVE_BYTES if options is not None else component.VRAM_MARGIN
196
194
  if card is None or card["free_bytes"] < needed + margin + reserve:
197
- 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
+ )
198
201
 
199
202
 
200
203
  def shared_start_guard(
@@ -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:
@@ -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
  )
@@ -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]