@simplexai/localmodels-linux-arm64 0.1.0-dev.57 → 0.1.0-dev.59

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 (68) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +66 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +1 -1
  5. package/modules/localmodels/bifrost_admin.py +53 -8
  6. package/modules/localmodels/bifrost_config.py +103 -4
  7. package/modules/localmodels/bifrost_log.py +166 -0
  8. package/modules/localmodels/budget.py +161 -1
  9. package/modules/localmodels/catalog.json +55 -32
  10. package/modules/localmodels/catalog.py +5 -2
  11. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
  12. package/modules/localmodels/frontend.py +26 -21
  13. package/modules/localmodels/gateway_bifrost.py +30 -6
  14. package/modules/localmodels/gpu_specs.py +38 -13
  15. package/modules/localmodels/hosts.py +99 -12
  16. package/modules/localmodels/library_cli.py +8 -1
  17. package/modules/localmodels/library_convert.py +34 -0
  18. package/modules/localmodels/library_elastic.py +747 -0
  19. package/modules/localmodels/library_gateway.py +101 -10
  20. package/modules/localmodels/library_jobs.py +16 -7
  21. package/modules/localmodels/library_model.py +101 -4
  22. package/modules/localmodels/library_pricing.py +41 -39
  23. package/modules/localmodels/library_serve.py +322 -58
  24. package/modules/localmodels/library_state.py +35 -1
  25. package/modules/localmodels/library_status.py +113 -6
  26. package/modules/localmodels/llm_rank.py +16 -5
  27. package/modules/localmodels/metal.py +141 -0
  28. package/modules/localmodels/metal_probe.py +167 -0
  29. package/modules/localmodels/plan_envelope.py +4 -1
  30. package/modules/localmodels/probe.py +2 -2
  31. package/modules/localmodels/process_identity_linux.py +39 -0
  32. package/modules/localmodels/recommend.py +6 -1
  33. package/modules/localmodels/remote_ops.py +4 -3
  34. package/modules/localmodels/remote_ops_download.py +37 -24
  35. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  36. package/modules/localmodels/remote_ops_service.py +93 -36
  37. package/modules/localmodels/runtime_auth.py +4 -1
  38. package/modules/localmodels/service_wiring.py +238 -12
  39. package/modules/localmodels/setup_inspection.py +47 -70
  40. package/modules/localmodels/setup_inspection_harness.py +159 -15
  41. package/modules/localmodels/setup_text.py +14 -0
  42. package/modules/localmodels/setup_upgrade.py +1 -1
  43. package/modules/localmodels/source_byok.py +6 -2
  44. package/modules/localmodels/source_byok_probe.py +6 -1
  45. package/modules/localmodels/stack.py +9 -1
  46. package/modules/localmodels/stack_binding.py +3 -35
  47. package/modules/localmodels/stack_cleanup.py +4 -0
  48. package/modules/localmodels/stack_compose.py +24 -3
  49. package/modules/localmodels/stack_hardware.py +3 -1
  50. package/modules/localmodels/stack_lifecycle.py +24 -1
  51. package/modules/localmodels/stack_picks.py +16 -2
  52. package/modules/localmodels/stack_plan.py +6 -2
  53. package/modules/localmodels/stack_ports.py +2 -0
  54. package/modules/localmodels/stack_remove.py +10 -1
  55. package/modules/localmodels/stack_up.py +33 -7
  56. package/modules/localmodels/stack_update.py +3 -1
  57. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
  58. package/modules/localmodels/suite.py +43 -27
  59. package/modules/localmodels/transport.py +13 -2
  60. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
  61. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +63 -61
  62. package/package.json +1 -1
  63. package/tool.json +1 -1
  64. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  65. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
  68. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -2,16 +2,36 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import contextlib
5
6
  import copy
6
7
  import json
7
8
  import os
8
9
  import platform
9
10
  from pathlib import Path
11
+ from typing import Any
10
12
  from urllib.parse import urlsplit
11
13
 
12
- from localmodels import gateway, gateway_keys, harness, harness_gateway, hosts, stack
14
+ from localmodels import (
15
+ bifrost_config,
16
+ bifrost_provider,
17
+ gateway,
18
+ gateway_bifrost,
19
+ gateway_keys,
20
+ harness,
21
+ harness_gateway,
22
+ hosts,
23
+ library_convert,
24
+ library_gateway,
25
+ library_model,
26
+ library_serve,
27
+ library_state,
28
+ source_byok,
29
+ stack,
30
+ )
13
31
  from localmodels.gateway import AuxEndpoint
32
+ from localmodels.records import Plan
14
33
  from localmodels.service_jobs import ServiceJobs
34
+ from localmodels.stack_plan import StackPlan
15
35
 
16
36
 
17
37
  def planned_gateway(root: Path, binding: dict[str, str] | None = None) -> harness.ToolPlan:
@@ -73,10 +93,211 @@ def auxiliary_endpoints(bindings: dict[str, dict[str, str]]) -> list[AuxEndpoint
73
93
  ]
74
94
 
75
95
 
96
+ def _library_stack_active(plan: StackPlan) -> bool:
97
+ """Whether every stack LLM in ``plan`` is actively loaded as a converted stack member."""
98
+ parts: list[tuple[Plan, str]] = [(plan["llm"], plan["harness"]["gateway"]["llm_provider"])]
99
+ if fast := plan.get("llm_fast"):
100
+ parts.append((fast, bifrost_config.FAST_PROVIDER))
101
+ for part, expected_provider in parts:
102
+ mid = library_model.library_id(part["model"]["id"], part["model"]["quant"])
103
+ if library_state.job_alive(mid):
104
+ job = library_state.read_job(mid)
105
+ if job is not None and job.get("kind") in ("unload", "remove", "load"):
106
+ return False
107
+ record = library_state.load(mid)
108
+ if record is None or record.get("state") != "loaded":
109
+ return False
110
+ if library_serve.stack_member(record) != expected_provider:
111
+ return False
112
+ reg = record.get("registration")
113
+ if reg is not None and reg.get("kind") not in ("stack", "agent"):
114
+ return False
115
+ return True
116
+
117
+
118
+ def _stack_llm_active(plan: StackPlan) -> bool:
119
+ """Whether ``plan``'s local stack LLM is still active and selected as the model source."""
120
+ try:
121
+ source = source_byok.load_source_state()
122
+ except (OSError, ValueError, source_byok.ByokError):
123
+ source = None
124
+ if source is not None and source["mode"] != "local":
125
+ return False
126
+
127
+ if library_convert.initialized() and not _library_stack_active(plan):
128
+ return False
129
+
130
+ owned_file = hosts.owned_path(plan["harness"]["tools_dir"])
131
+ if owned_file.is_file():
132
+ try:
133
+ owned = hosts.load_owned(plan["harness"]["tools_dir"])
134
+ except (OSError, ValueError):
135
+ owned = None
136
+ if owned is not None:
137
+ entry = owned["deployments"].get(plan["llm"]["name"])
138
+ if entry is not None and entry.get("removed"):
139
+ return False
140
+ key_file = Path(os.path.expanduser(plan["llm"]["service"]["deploy_dir"]), "api-key")
141
+ if entry is None and not key_file.is_file():
142
+ return False
143
+ return True
144
+
145
+
146
+ def _owned_bifrost(tools_dir: str) -> hosts.OwnedBifrost | None:
147
+ """Find an owned Bifrost record from ``tools_dir`` or the default library/BYOK tools root."""
148
+ for candidate in dict.fromkeys((tools_dir, hosts.tools_dir())):
149
+ try:
150
+ record = hosts.load_owned(candidate)["gateway"].get("bifrost")
151
+ except (OSError, ValueError):
152
+ continue
153
+ if record is not None:
154
+ return record
155
+ return None
156
+
157
+
158
+ def _bifrost_needs_inactive_sync(config: dict[str, Any], decision_provider: str) -> bool:
159
+ """Whether an on-disk Bifrost config has stale foundation providers or needs governance repair."""
160
+ providers = config.get("providers")
161
+ foundation_ids = {
162
+ decision_provider,
163
+ bifrost_config.AUX_PROVIDERS["embedding"],
164
+ bifrost_config.AUX_PROVIDERS["rerank"],
165
+ }
166
+ if isinstance(providers, dict) and foundation_ids.intersection(providers):
167
+ return True
168
+ return bifrost_config.sanitize_governance(copy.deepcopy(config))
169
+
170
+
171
+ def _sync_bifrost_foundations(
172
+ record: hosts.OwnedBifrost,
173
+ tools_plan: harness.HarnessPlan,
174
+ bindings: dict[str, dict[str, str]],
175
+ ) -> str | None:
176
+ """Update only foundation providers in an existing owned Bifrost without touching LLM routes.
177
+
178
+ Returns the gateway address while Bifrost remains active, or None when absent or stopped.
179
+ """
180
+ with library_gateway.gateway_locked():
181
+ app = Path(record["app_dir"])
182
+ config = gateway_bifrost.read_config(app)
183
+ if not config:
184
+ return None
185
+ providers = config.setdefault("providers", {})
186
+ decision_pid = tools_plan["gateway"]["decision_provider"]
187
+ if decision := bindings.get("decision"):
188
+ providers[decision_pid] = bifrost_provider.render(
189
+ "decision", decision["baseUrl"], decision["model"], decision["key"], decision_pid
190
+ )
191
+ else:
192
+ providers.pop(decision_pid, None)
193
+ desired_aux: set[str] = set()
194
+ for ep in auxiliary_endpoints(bindings):
195
+ pid = bifrost_config.AUX_PROVIDERS.get(str(ep.get("contract")))
196
+ if pid:
197
+ desired_aux.add(pid)
198
+ providers[pid] = bifrost_provider.render(
199
+ str(ep["contract"]), str(ep["url"]), str(ep["model"]), str(ep["key"]), pid
200
+ )
201
+ for contract in ("embedding", "rerank"):
202
+ pid = bifrost_config.AUX_PROVIDERS[contract]
203
+ if pid not in desired_aux:
204
+ providers.pop(pid, None)
205
+ bifrost_config.sanitize_governance(config)
206
+ library_gateway.apply_config(record, config, library_gateway.read_sheet(app))
207
+ return record["addr"] if config.get("providers") else None
208
+
209
+
76
210
  class Wiring:
77
211
  def __init__(self) -> None:
78
212
  self.last: object = None
79
213
 
214
+ def _sync_inactive_bifrost(
215
+ self,
216
+ signature: object,
217
+ record: hosts.OwnedBifrost | None,
218
+ config_doc: dict[str, Any],
219
+ tools_plan: harness.HarnessPlan,
220
+ bindings: dict[str, dict[str, str]],
221
+ had_bindings: bool,
222
+ jobs: ServiceJobs,
223
+ ) -> None:
224
+ if record is None or not config_doc:
225
+ if not bindings:
226
+ if had_bindings:
227
+ jobs.set_gateway(None)
228
+ self.last = copy.deepcopy(signature)
229
+ return
230
+ decision_pid = tools_plan["gateway"]["decision_provider"]
231
+ if (
232
+ not bindings
233
+ and not had_bindings
234
+ and not _bifrost_needs_inactive_sync(config_doc, decision_pid)
235
+ ):
236
+ self.last = copy.deepcopy(signature)
237
+ return
238
+ addr = _sync_bifrost_foundations(record, tools_plan, bindings)
239
+ if addr is None:
240
+ jobs.set_gateway(None)
241
+ else:
242
+ set_gateway_binding(jobs, addr, "bifrost")
243
+ self.last = copy.deepcopy(signature)
244
+
245
+ def _sync_inactive_magpie(
246
+ self,
247
+ signature: object,
248
+ tools_plan: harness.HarnessPlan,
249
+ kind: str,
250
+ bindings: dict[str, dict[str, str]],
251
+ had_bindings: bool,
252
+ jobs: ServiceJobs,
253
+ ) -> None:
254
+ decision_pid = tools_plan["gateway"]["decision_provider"]
255
+ managed = {*gateway.FOUNDATION_PROVIDERS, decision_pid}
256
+ if not bindings and not had_bindings:
257
+ owned_providers = hosts.load_owned(tools_plan["tools_dir"])["gateway"]["providers"]
258
+ if not managed.intersection(owned_providers):
259
+ self.last = copy.deepcopy(signature)
260
+ return
261
+ decision = bindings.get("decision")
262
+ gateway.wire_foundations(
263
+ tools_plan,
264
+ {"url": decision["baseUrl"], "model": decision["model"]} if decision else None,
265
+ decision["key"] if decision else None,
266
+ auxiliary_endpoints(bindings),
267
+ decision_provider=decision_pid,
268
+ )
269
+ if bindings:
270
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
271
+ else:
272
+ jobs.set_gateway(None)
273
+ self.last = copy.deepcopy(signature)
274
+
275
+ def _sync_inactive(
276
+ self,
277
+ main_plan: Path,
278
+ plan_id: str,
279
+ tools_plan: harness.HarnessPlan,
280
+ kind: str,
281
+ bindings: dict[str, dict[str, str]],
282
+ jobs: ServiceJobs,
283
+ ) -> None:
284
+ signature: object = ("inactive", str(main_plan), plan_id, bindings)
285
+ if self.last == signature:
286
+ return
287
+ had_bindings = isinstance(self.last, tuple) and bool(self.last[-1])
288
+ bifrost_record = _owned_bifrost(tools_plan["tools_dir"])
289
+ bifrost_doc = (
290
+ gateway_bifrost.read_config(Path(bifrost_record["app_dir"]))
291
+ if bifrost_record is not None
292
+ else {}
293
+ )
294
+ if kind == "bifrost" or bifrost_doc:
295
+ self._sync_inactive_bifrost(
296
+ signature, bifrost_record, bifrost_doc, tools_plan, bindings, had_bindings, jobs
297
+ )
298
+ return
299
+ self._sync_inactive_magpie(signature, tools_plan, kind, bindings, had_bindings, jobs)
300
+
80
301
  def sync(self, main_plan: Path | None, jobs: ServiceJobs) -> None:
81
302
  bindings = jobs.bindings()
82
303
  if main_plan is None:
@@ -114,24 +335,29 @@ class Wiring:
114
335
  ready = json.loads(receipt.read_text())
115
336
  if not ready.get("ready") or ready.get("planId") != plan["plan_id"]:
116
337
  return
338
+ tools_plan = copy.deepcopy(plan["harness"])
339
+ kind = harness.gateway_kind(tools_plan["gateway"])
340
+ if not _stack_llm_active(plan):
341
+ self._sync_inactive(main_plan, plan["plan_id"], tools_plan, kind, bindings, jobs)
342
+ return
117
343
  signature = (str(main_plan), plan["plan_id"], receipt.stat().st_mtime_ns, bindings)
118
344
  if self.last == signature:
119
345
  return
120
- tools_plan = copy.deepcopy(plan["harness"])
121
346
  decision = bindings.get("decision")
122
347
  tools_plan["gateway"]["decision"] = (
123
348
  {"url": decision["baseUrl"], "model": decision["model"]} if decision else None
124
349
  )
125
350
  aux = auxiliary_endpoints(bindings)
126
351
  # Only update the owned routing group. Never replace a user's current Pi selection.
127
- gateway.wire(
128
- tools_plan,
129
- stack.service_key(plan["llm"]),
130
- decision["key"] if decision else None,
131
- aux,
132
- select_pi=False,
133
- )
134
- set_gateway_binding(
135
- jobs, tools_plan["gateway"]["addr"], harness.gateway_kind(tools_plan["gateway"])
136
- )
352
+ with library_gateway.gateway_locked() if kind == "bifrost" else contextlib.nullcontext():
353
+ if kind == "bifrost" and not _stack_llm_active(plan):
354
+ return
355
+ gateway.wire(
356
+ tools_plan,
357
+ stack.service_key(plan["llm"]),
358
+ decision["key"] if decision else None,
359
+ aux,
360
+ select_pi=False,
361
+ )
362
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
137
363
  self.last = copy.deepcopy(signature)
@@ -32,35 +32,16 @@ from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
32
32
  from localmodels.plan_envelope import PlanError
33
33
  from localmodels.probe import HostFacts, Services
34
34
  from localmodels.runtime_cli import inspect_runtimes
35
+ from localmodels.setup_inspection_harness import Reason as Reason
35
36
  from localmodels.setup_text import Lang, text
36
37
  from localmodels.stack_plan import (
37
38
  StackError,
38
39
  StackOptions,
39
40
  StackPlan,
40
- deployments,
41
41
  platform_error,
42
42
  )
43
43
 
44
44
 
45
- class _ReasonSince014(TypedDict, total=False):
46
- # Since 0.1.4 (roadmap decision 60), on gpu-memory-required and free-memory-required: the
47
- # memory free now (measured) and the memory the install needs free (the plan's estimate,
48
- # with the planner's safety reserve on a GPU), in bytes; gpuIndex names the card.
49
- gpuIndex: int
50
- freeBytes: int
51
- requiredBytes: int
52
- # On cuda-driver-update-required and cuda-driver-version-unknown: driver and CUDA versions.
53
- detectedCudaVersion: str
54
- requiredCudaVersion: str
55
- requiredDriverVersion: str
56
- driverVersion: str
57
-
58
-
59
- class Reason(_ReasonSince014):
60
- code: str
61
- message: str
62
-
63
-
64
45
  class StackMemory(TypedDict, total=False):
65
46
  """What the plan needs against what is free now, in bytes; VRAM only for discrete GPUs."""
66
47
 
@@ -164,7 +145,10 @@ def _fits_with_required_cuda(options: StackOptions, facts: HostFacts, required_c
164
145
  if _plans_hardware(options, upgraded):
165
146
  return True
166
147
  roomy = _capacity_facts(upgraded)
167
- return roomy is not None and _plans_hardware(options, roomy)
148
+ if roomy is not None and _plans_hardware(options, roomy):
149
+ return True
150
+ alone = setup_inspection_harness.without_other_inference(roomy or upgraded)
151
+ return alone is not None and _plans_hardware(options, alone)
168
152
 
169
153
 
170
154
  def _driver_block(
@@ -184,22 +168,23 @@ def _driver_block(
184
168
  }
185
169
 
186
170
 
187
- def _capacity_availability(
188
- options: StackOptions, facts: HostFacts, lang: Lang
171
+ def _other_inference_availability(
172
+ options: StackOptions, facts: HostFacts, roomy: HostFacts | None, lang: Lang
189
173
  ) -> StackAvailability | None:
190
- roomy = _capacity_facts(facts)
191
- if roomy is None:
174
+ """Hardware fits once foreign inference apps/GPU workloads exit: not counted as freeable
175
+ desktop memory (roadmap decision 43), but reported as blocked-now instead of incapable."""
176
+ alone_facts = setup_inspection_harness.without_other_inference(
177
+ roomy if roomy is not None else facts
178
+ )
179
+ if alone_facts is None:
192
180
  return None
193
181
  try:
194
- plan = stack.build(options, facts=roomy)
195
- except (PlanError, stack.StackError) as roomy_exc:
196
- if blocked := _driver_block(roomy_exc, options, roomy, lang):
197
- return blocked
198
- # The hardware itself is too small and the live refusal stands, unless only another
199
- # inference app on a Mac's GPU stands in the way: that memory is not counted as freeable
200
- # (roadmap decision 43), but the refusal names the app instead of blaming the hardware.
201
- if alone := _fits_without_other_inference(options, roomy):
202
- reason: Reason = {
182
+ plan = stack.build(options, facts=alone_facts, min_prompt_cache=True)
183
+ except (PlanError, stack.StackError) as alone_exc:
184
+ return _driver_block(alone_exc, options, alone_facts, lang)
185
+ if metal.supported(facts):
186
+ reasons: list[Reason] = [
187
+ {
203
188
  "code": "plan-unavailable",
204
189
  "message": text(
205
190
  "inference-app-running",
@@ -207,21 +192,34 @@ def _capacity_availability(
207
192
  apps="; ".join(metal.conflicts(facts)),
208
193
  ),
209
194
  }
195
+ ]
196
+ else:
197
+ reasons = setup_inspection_harness.gpu_conflict_reasons(
198
+ options, facts, roomy, plan, lang, _plans, _free_memory_reason
199
+ )
200
+ return {"available": False, "reasons": reasons, "plan": plan, "basis": "capacity"}
201
+
202
+
203
+ def _capacity_availability(
204
+ options: StackOptions, facts: HostFacts, lang: Lang
205
+ ) -> StackAvailability | None:
206
+ roomy = _capacity_facts(facts)
207
+ if roomy is not None:
208
+ try:
209
+ plan = stack.build(options, facts=roomy, min_prompt_cache=True)
210
+ except (PlanError, stack.StackError) as roomy_exc:
211
+ if blocked := _driver_block(roomy_exc, options, roomy, lang):
212
+ return blocked
213
+ else:
214
+ # Roadmap decision 56: an install now prices the memory free now and would refuse,
215
+ # so the stack is not available; the plan shows what it needs.
210
216
  return {
211
217
  "available": False,
212
- "reasons": [reason],
213
- "plan": alone,
218
+ "reasons": _held_reasons(options, facts, roomy, plan, lang),
219
+ "plan": plan,
214
220
  "basis": "capacity",
215
221
  }
216
- return None
217
- # Roadmap decision 56: an install now prices the memory free now and would refuse, so the stack
218
- # is not available; the plan shows what it needs.
219
- return {
220
- "available": False,
221
- "reasons": _held_reasons(options, facts, roomy, plan, lang),
222
- "plan": plan,
223
- "basis": "capacity",
224
- }
222
+ return _other_inference_availability(options, facts, roomy, lang)
225
223
 
226
224
 
227
225
  def _harness_availability(
@@ -313,18 +311,6 @@ def _stack(
313
311
  return {"available": False, "reasons": [reason], "plan": None}
314
312
 
315
313
 
316
- def _fits_without_other_inference(options: StackOptions, roomy: HostFacts) -> StackPlan | None:
317
- """A Mac's capacity plan once the inference apps this tool does not own on its GPU
318
- (``metal.conflicts``) are quit as well, or None when it still does not fit."""
319
- alone = setup_inspection_harness.without_other_inference(roomy)
320
- if alone is None:
321
- return None
322
- try:
323
- return stack.build(options, facts=alone)
324
- except (PlanError, stack.StackError):
325
- return None
326
-
327
-
328
314
  def _plans(options: StackOptions, facts: HostFacts) -> bool:
329
315
  try:
330
316
  stack.build(options, facts=facts)
@@ -352,7 +338,7 @@ def _held_reasons(
352
338
  reasons: list[Reason] = []
353
339
  if gpu_short:
354
340
  live = {g["index"]: g for g in facts.get("gpus") or []}
355
- for index, vram in _vram_by_card(plan).items():
341
+ for index, vram in setup_inspection_harness.vram_by_card(plan).items():
356
342
  card = live.get(index)
357
343
  required = vram + AGENT_VRAM_RESERVE_BYTES
358
344
  if card is None or card["free_bytes"] >= required:
@@ -379,16 +365,6 @@ def _held_reasons(
379
365
  return reasons
380
366
 
381
367
 
382
- def _vram_by_card(plan: StackPlan) -> dict[int, int]:
383
- """GPU memory the plan's deployments reserve on each card; a split one counts on each."""
384
- found: dict[int, int] = {}
385
- for part in deployments(plan):
386
- for gpu in decode(part["placement"].get("gpus") or [], list[stack_review.SelectedGPU]):
387
- index = gpu["index"]
388
- found[index] = found.get(index, 0) + int(str(part["launch"].get("vram_bytes") or 0))
389
- return found
390
-
391
-
392
368
  def _free_memory_reason(facts: HostFacts, roomy: HostFacts, lang: Lang = "zh") -> Reason:
393
369
  """Names the memory other programs hold now: each reading the capacity plan counted as freed."""
394
370
  gib = budget.gib
@@ -553,8 +529,9 @@ INSPECT_REASONS = (
553
529
  "hardwareCapable true when the hardware fits, but the gateway port is held or tool checks "
554
530
  "failed; free the port or fix the tool issue and check again)\n"
555
531
  "gpu-memory-required (stack.state is blocked-now, stack.basis is capacity: other programs "
556
- "use the GPU memory the plan needs; close them and check again; gpuIndex, freeBytes and "
557
- "requiredBytes give the card and its free and needed VRAM)\n"
532
+ "or another inference app/GPU workload use the GPU memory the plan needs; close them and "
533
+ "check again; gpuIndex, freeBytes and requiredBytes give the card and its free and needed "
534
+ "VRAM)\n"
558
535
  "free-memory-required (the same for RAM, freeBytes and requiredBytes in RAM; stack.memory "
559
536
  "gives the RAM free and needed). On a Mac whose hardware fits only once another inference "
560
537
  "app on its GPU is quit, plan-unavailable (blocked-now) names that app instead of the "
@@ -3,6 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import copy
6
+ from collections.abc import Callable
7
+ from typing import TypedDict
6
8
 
7
9
  from localmodels import (
8
10
  budget,
@@ -13,12 +15,35 @@ from localmodels import (
13
15
  stack_compose,
14
16
  stack_gpu_memory,
15
17
  stack_hardware,
18
+ stack_review,
16
19
  stack_suite,
17
20
  )
21
+ from localmodels.contracts import decode
22
+ from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
18
23
  from localmodels.plan_envelope import PlanError
19
24
  from localmodels.probe import HostFacts
20
25
  from localmodels.setup_text import Lang, text
21
- from localmodels.stack_plan import RAM_FLOOR, StackOptions, platform_error
26
+ from localmodels.stack_plan import RAM_FLOOR, StackOptions, StackPlan, deployments, platform_error
27
+
28
+
29
+ class _ReasonOptional(TypedDict, total=False):
30
+ # Since 0.1.4 (roadmap decision 60), on gpu-memory-required and free-memory-required: the
31
+ # memory free now (measured) and the memory the install needs free (the plan's estimate,
32
+ # with the planner's safety reserve on a GPU), in bytes; gpuIndex names the card.
33
+ gpuIndex: int
34
+ freeBytes: int
35
+ requiredBytes: int
36
+ # On cuda-driver-update-required and cuda-driver-version-unknown: driver and CUDA versions.
37
+ detectedCudaVersion: str
38
+ requiredCudaVersion: str
39
+ requiredDriverVersion: str
40
+ driverVersion: str
41
+
42
+
43
+ class Reason(_ReasonOptional):
44
+ code: str
45
+ message: str
46
+
22
47
 
23
48
  HARNESS_CODES = frozenset({"gateway-port-in-use", "harness-unavailable"})
24
49
  _PORT_CONFLICT_HINTS = (
@@ -104,20 +129,139 @@ def fits_hardware_once(options: StackOptions, facts: HostFacts) -> bool:
104
129
 
105
130
 
106
131
  def without_other_inference(roomy: HostFacts) -> HostFacts | None:
107
- """``roomy`` with foreign Metal inference apps stripped, or None when none are present."""
108
- if not metal.supported(roomy) or not metal.conflicts(roomy):
132
+ """``roomy`` with foreign inference apps/workloads stripped (and conflicted discrete GPUs
133
+ restored to idle VRAM), or None when none are present."""
134
+ if metal.supported(roomy):
135
+ if not metal.conflicts(roomy):
136
+ return None
137
+ alone = copy.deepcopy(roomy)
138
+ services = alone["services"]
139
+ assert services is not None # conflicts come from service discovery
140
+ services["compute_processes"] = [
141
+ p
142
+ for p in services.get("compute_processes") or []
143
+ if p["gpu_uuid"] != metal.METAL_UUID or p["owned"] is True
144
+ ]
145
+ return alone
146
+ served = budget.gpu_conflicts(roomy)
147
+ if not served:
109
148
  return None
110
149
  alone = copy.deepcopy(roomy)
111
- services = alone["services"]
112
- assert services is not None # conflicts come from service discovery
113
- services["compute_processes"] = [
114
- p
115
- for p in services.get("compute_processes") or []
116
- if p["gpu_uuid"] != metal.METAL_UUID or p["owned"] is True
117
- ]
150
+ for gpu in alone.get("gpus") or []:
151
+ if not served.get(gpu["uuid"]):
152
+ continue
153
+ idle = max(0, gpu["total_bytes"] - budget.IDLE_USED_BYTES)
154
+ if gpu["free_bytes"] < idle:
155
+ gpu["free_bytes"], gpu["used_bytes"] = idle, gpu["total_bytes"] - idle
156
+ gpu_services = alone.get("services")
157
+ if gpu_services is not None:
158
+ procs = gpu_services.get("compute_processes")
159
+ if procs is not None:
160
+ gpu_services["compute_processes"] = [
161
+ p for p in procs if not budget.foreign_work(p, alone)
162
+ ]
163
+ boxes = gpu_services.get("containers")
164
+ if boxes is not None:
165
+ conflict_labels = {label for labels in served.values() for label in labels}
166
+ gpu_services["containers"] = [
167
+ box
168
+ for box in boxes
169
+ if f"container {box['name']} ({box['image']})" not in conflict_labels
170
+ ]
118
171
  return alone
119
172
 
120
173
 
174
+ def vram_by_card(plan: StackPlan) -> dict[int, int]:
175
+ """GPU memory the plan's deployments reserve on each card; a split one counts on each."""
176
+ found: dict[int, int] = {}
177
+ for part in deployments(plan):
178
+ for gpu in decode(part["placement"].get("gpus") or [], list[stack_review.SelectedGPU]):
179
+ index = gpu["index"]
180
+ found[index] = found.get(index, 0) + int(str(part["launch"].get("vram_bytes") or 0))
181
+ return found
182
+
183
+
184
+ def gpu_conflict_reasons(
185
+ options: StackOptions,
186
+ facts: HostFacts,
187
+ roomy: HostFacts | None,
188
+ plan: StackPlan,
189
+ lang: Lang,
190
+ plans_fn: Callable[[StackOptions, HostFacts], bool],
191
+ ram_reason_fn: Callable[[HostFacts, HostFacts, Lang], Reason],
192
+ ) -> list[Reason]:
193
+ """Structured capacity reasons when a discrete NVIDIA GPU is held by foreign GPU work."""
194
+ served = budget.gpu_conflicts(facts)
195
+ live = {g["index"]: g for g in facts.get("gpus") or []}
196
+ nvidia = [g for g in facts.get("gpus") or [] if g.get("vendor") == "nvidia"]
197
+ unified_uuid = (
198
+ nvidia[0]["uuid"] if nvidia and budget.unified_pool_bytes(facts) is not None else None
199
+ )
200
+ summary = stack_review.summarize(plan, lang)
201
+ gib = budget.gib
202
+ reasons: list[Reason] = []
203
+ for index, vram in vram_by_card(plan).items():
204
+ card = live.get(index)
205
+ required = vram + AGENT_VRAM_RESERVE_BYTES
206
+ if (
207
+ card is None
208
+ or card["total_bytes"] <= 0
209
+ or card["uuid"] == unified_uuid
210
+ or card["free_bytes"] >= required
211
+ ):
212
+ continue
213
+ apps = "; ".join(served.get(card["uuid"]) or ())
214
+ message = (
215
+ text(
216
+ "gpu-inference-app-running",
217
+ lang,
218
+ index=index,
219
+ free=gib(card["free_bytes"]),
220
+ needed=gib(required),
221
+ apps=apps,
222
+ )
223
+ if apps
224
+ else text(
225
+ "gpu-memory-required",
226
+ lang,
227
+ index=index,
228
+ free=gib(card["free_bytes"]),
229
+ needed=gib(required),
230
+ )
231
+ )
232
+ reasons.append(
233
+ {
234
+ "code": "gpu-memory-required",
235
+ "message": message,
236
+ "gpuIndex": index,
237
+ "freeBytes": card["free_bytes"],
238
+ "requiredBytes": required,
239
+ }
240
+ )
241
+ ram = facts["ram"]["available_bytes"]
242
+ if roomy is not None and ram < roomy["ram"]["available_bytes"]:
243
+ gpu_only = without_other_inference(facts)
244
+ if gpu_only is None or not plans_fn(options, gpu_only):
245
+ ram_only = copy.deepcopy(facts)
246
+ ram_only["ram"] = copy.deepcopy(roomy["ram"])
247
+ reasons.append(
248
+ {
249
+ **ram_reason_fn(facts, ram_only, lang),
250
+ "freeBytes": ram,
251
+ "requiredBytes": summary["memoryBytes"],
252
+ }
253
+ )
254
+ if not reasons:
255
+ all_apps = "; ".join(label for labels in served.values() for label in labels)
256
+ reasons.append(
257
+ {
258
+ "code": "plan-unavailable",
259
+ "message": text("gpu-conflict-running", lang, apps=all_apps),
260
+ }
261
+ )
262
+ return reasons
263
+
264
+
121
265
  def hardware_capable_without_harness(options: StackOptions, facts: HostFacts) -> bool:
122
266
  """True when the computer's hardware fits a stack once gateway/harness blockers clear."""
123
267
  if fits_hardware_once(options, facts):
@@ -129,11 +273,11 @@ def hardware_capable_without_harness(options: StackOptions, facts: HostFacts) ->
129
273
  and fits_hardware_once({**options, "share_gpu": True}, facts)
130
274
  ):
131
275
  return True
132
- if roomy := capacity_facts(facts):
133
- if fits_hardware_once(options, roomy):
134
- return True
135
- if (alone := without_other_inference(roomy)) is not None:
136
- return fits_hardware_once(options, alone)
276
+ roomy = capacity_facts(facts)
277
+ if roomy is not None and fits_hardware_once(options, roomy):
278
+ return True
279
+ if (alone := without_other_inference(roomy or facts)) is not None:
280
+ return fits_hardware_once(options, alone)
137
281
  return False
138
282
 
139
283