@simplexai/localmodels-linux-x64 0.1.0-dev.48 → 0.1.0-dev.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +82 -72
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/budget.py +40 -14
  5. package/modules/localmodels/catalog.json +473 -36
  6. package/modules/localmodels/debug_mode.py +25 -0
  7. package/modules/localmodels/deploy.py +3 -0
  8. package/modules/localmodels/download-mirrors.json +47 -0
  9. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
  10. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  11. package/modules/localmodels/engines.py +31 -6
  12. package/modules/localmodels/gateway.py +23 -6
  13. package/modules/localmodels/gateway_bifrost.py +6 -2
  14. package/modules/localmodels/harness.py +8 -2
  15. package/modules/localmodels/harness_gateway.py +78 -17
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/hosts.py +52 -5
  18. package/modules/localmodels/library_floor.py +76 -0
  19. package/modules/localmodels/library_jobs.py +60 -7
  20. package/modules/localmodels/library_model.py +38 -2
  21. package/modules/localmodels/library_poly.py +272 -0
  22. package/modules/localmodels/library_pricing.py +251 -79
  23. package/modules/localmodels/library_serve.py +27 -4
  24. package/modules/localmodels/library_state.py +16 -0
  25. package/modules/localmodels/library_status.py +46 -18
  26. package/modules/localmodels/library_vram.py +123 -0
  27. package/modules/localmodels/llm_rank.py +42 -1
  28. package/modules/localmodels/magpie_windows.py +312 -0
  29. package/modules/localmodels/probe.py +39 -37
  30. package/modules/localmodels/process_identity.py +26 -33
  31. package/modules/localmodels/process_identity_darwin.py +189 -0
  32. package/modules/localmodels/process_identity_linux.py +62 -30
  33. package/modules/localmodels/recommend.py +3 -1
  34. package/modules/localmodels/remote_ops.py +11 -0
  35. package/modules/localmodels/remote_ops_download.py +30 -5
  36. package/modules/localmodels/remote_ops_service.py +15 -46
  37. package/modules/localmodels/reuse.py +13 -6
  38. package/modules/localmodels/runtime_io.py +32 -18
  39. package/modules/localmodels/service_probe.py +1 -1
  40. package/modules/localmodels/setup_inspection.py +97 -80
  41. package/modules/localmodels/setup_inspection_harness.py +147 -0
  42. package/modules/localmodels/setup_text.py +24 -0
  43. package/modules/localmodels/setup_upgrade.py +155 -0
  44. package/modules/localmodels/stack.py +3 -1
  45. package/modules/localmodels/stack_auto.py +6 -2
  46. package/modules/localmodels/stack_clients.py +1 -1
  47. package/modules/localmodels/stack_compose.py +5 -1
  48. package/modules/localmodels/stack_down.py +25 -16
  49. package/modules/localmodels/stack_hardware.py +17 -3
  50. package/modules/localmodels/stack_picks.py +28 -13
  51. package/modules/localmodels/stack_remove.py +3 -1
  52. package/modules/localmodels/stack_route.py +5 -1
  53. package/modules/localmodels/stack_suite.py +29 -8
  54. package/modules/localmodels/stack_view_access.py +238 -58
  55. package/modules/localmodels/stack_view_hub.py +12 -7
  56. package/modules/localmodels/stack_view_serve.py +13 -6
  57. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  58. package/modules/localmodels/strata_poly_server.py +14 -2
  59. package/modules/localmodels/suite.py +19 -3
  60. package/modules/localmodels/tool_archive.py +4 -0
  61. package/modules/localmodels/transport.py +3 -1
  62. package/modules/localmodels/tui.py +4 -1
  63. package/modules/localmodels/tui_dialogs.py +42 -9
  64. package/modules/localmodels/tui_modals.py +63 -16
  65. package/modules/localmodels/tui_screen.py +80 -53
  66. package/modules/localmodels/tui_views.py +36 -6
  67. package/modules/localmodels/vision.py +4 -2
  68. package/modules/localmodels/web/index.html +996 -300
  69. package/modules/localmodels/web/sizecalc/app.js +616 -88
  70. package/modules/localmodels/web/sizecalc/page.html +239 -106
  71. package/modules/localmodels/web/view/fleet.js +25 -2
  72. package/modules/localmodels/web/view/nav.js +19 -3
  73. package/modules/localmodels/web/view/view.css +110 -22
  74. package/modules/localmodels/web/view/view.js +40 -22
  75. package/modules/localmodels/win_probe.py +204 -0
  76. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/METADATA +1 -1
  77. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/RECORD +79 -69
  78. package/package.json +1 -1
  79. package/tool.json +1 -1
  80. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/WHEEL +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/entry_points.txt +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/NOTICE +0 -0
  83. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,147 @@
1
+ """Classify ``HarnessError`` in ``setup inspect`` separately from hardware incapability."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+
7
+ from localmodels import (
8
+ budget,
9
+ deploy,
10
+ harness,
11
+ metal,
12
+ stack,
13
+ stack_compose,
14
+ stack_gpu_memory,
15
+ stack_hardware,
16
+ stack_suite,
17
+ )
18
+ from localmodels.plan_envelope import PlanError
19
+ from localmodels.probe import HostFacts
20
+ from localmodels.setup_text import Lang, text
21
+ from localmodels.stack_plan import RAM_FLOOR, StackOptions, platform_error
22
+
23
+ HARNESS_CODES = frozenset({"gateway-port-in-use", "harness-unavailable"})
24
+ _PORT_CONFLICT_HINTS = (
25
+ "is held by",
26
+ "ports 3425..3456 are all in use",
27
+ "port still listening",
28
+ )
29
+
30
+
31
+ def capacity_facts(facts: HostFacts) -> HostFacts | None:
32
+ """``facts`` once the user's other programs are closed, or None when that frees nothing.
33
+
34
+ A Mac keeps what an idle one leaves to macOS and applications (``metal.in_use``) and is at
35
+ normal pressure; a Linux host keeps the planner's own floor a second time for its desktop.
36
+ An NVIDIA card keeps an idle driver context, unless serving work this tool does not own
37
+ runs on it: that memory needs sharing consent, and closing applications does not free it.
38
+ """
39
+ roomy = copy.deepcopy(facts)
40
+ ram = roomy["ram"]
41
+ total = ram["total_bytes"]
42
+ if metal.supported(facts):
43
+ room = total - metal.in_use(total)
44
+ ram["pressure_level"] = 1
45
+ ram.pop("pressure_kept_bytes", None)
46
+ else:
47
+ room = total - RAM_FLOOR
48
+ ram["available_bytes"] = max(ram["available_bytes"], room)
49
+ served = budget.gpu_conflicts(facts)
50
+ for gpu in roomy.get("gpus") or []:
51
+ if served.get(gpu["uuid"]):
52
+ continue
53
+ idle = max(0, gpu["total_bytes"] - budget.IDLE_USED_BYTES)
54
+ if gpu["free_bytes"] < idle:
55
+ gpu["free_bytes"], gpu["used_bytes"] = idle, gpu["total_bytes"] - idle
56
+ return None if roomy == facts else roomy
57
+
58
+
59
+ def harness_code(error: harness.HarnessError) -> str:
60
+ if error.code in HARNESS_CODES:
61
+ return error.code
62
+ lowered = str(error).lower()
63
+ if any(hint in lowered for hint in _PORT_CONFLICT_HINTS):
64
+ return "gateway-port-in-use"
65
+ return "harness-unavailable"
66
+
67
+
68
+ def fits_hardware_once(options: StackOptions, facts: HostFacts) -> bool:
69
+ """Whether ``facts`` can fit a verified local stack ignoring gateway/harness conflicts."""
70
+ try:
71
+ seen = stack_hardware.assumed(facts, options.get("unified_memory"))
72
+ if platform_error(seen["platform"], options.get("profile"), seen["arch"]):
73
+ return False
74
+ if options.get("profile") != "macos-mlx-preview" and metal.problem(seen):
75
+ return False
76
+ if metal.supported(seen) and options.get("profile") != "macos-mlx-preview":
77
+ seen = metal.reclaimed(seen)
78
+ seen, _ = metal.pressured(seen)
79
+ seen, _ = stack_gpu_memory.capped(seen, options)
80
+ resolver = deploy.catalog_pins if options.get("offline") else deploy.resolve_files
81
+ parts, chosen = stack_compose.choose_parts(
82
+ seen,
83
+ options,
84
+ resolver=resolver,
85
+ listening=lambda _port: False,
86
+ previous=lambda _name, _port: None,
87
+ existing=lambda _recipes: [],
88
+ owned_ram=lambda: 0,
89
+ )
90
+ if chosen.get("defer_services"):
91
+ parts["decision"] = {
92
+ **parts["decision"],
93
+ "plan": None,
94
+ "front": None,
95
+ "existing": None,
96
+ "options": [],
97
+ }
98
+ named = stack_suite.named_foundations(chosen)
99
+ parts["aux"] = [p for p in parts["aux"] if stack_suite.task_of(p) not in named]
100
+ stack_compose.ram_budget(parts)
101
+ except (PlanError, stack.StackError):
102
+ return False
103
+ return True
104
+
105
+
106
+ 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):
109
+ return None
110
+ 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
+ ]
118
+ return alone
119
+
120
+
121
+ def hardware_capable_without_harness(options: StackOptions, facts: HostFacts) -> bool:
122
+ """True when the computer's hardware fits a stack once gateway/harness blockers clear."""
123
+ if fits_hardware_once(options, facts):
124
+ return True
125
+ if (
126
+ not options.get("share_gpu")
127
+ and budget.holders(facts)
128
+ and (not budget.unknown_services(facts) or not metal.supported(facts))
129
+ and fits_hardware_once({**options, "share_gpu": True}, facts)
130
+ ):
131
+ 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)
137
+ return False
138
+
139
+
140
+ def classify_harness_error(
141
+ options: StackOptions, facts: HostFacts, exc: harness.HarnessError, lang: Lang
142
+ ) -> tuple[str, bool, str]:
143
+ """Return ``(reason_code, hardware_capable, message)`` for a gateway/tool ``HarnessError``."""
144
+ code = harness_code(exc)
145
+ capable = hardware_capable_without_harness(options, facts)
146
+ message = text(code, lang, detail=str(exc)) if capable else str(exc)
147
+ return code, capable, message
@@ -53,6 +53,18 @@ MESSAGES: dict[str, tuple[str, str]] = {
53
53
  ),
54
54
  "free-gpu": ("GPU {index} 空闲显存 {free}", "GPU {index} has {free} free"),
55
55
  "free-ram": ("可用内存 {free}", "{free} of RAM is available"),
56
+ "upgrade-gpu-memory": (
57
+ "关闭部分占用 GPU {index} 显存的程序(当前空闲 {free},约需 {needed})并重新检查,"
58
+ "可升级安装更强的本地模型 {model};本工具不会停止任何进程。",
59
+ "Close programs using GPU {index} memory ({free} free; about {needed} needed) and "
60
+ "check again to install a stronger local model ({model}); this tool stops no process.",
61
+ ),
62
+ "upgrade-free-memory": (
63
+ "关闭其他占用内存的程序(当前可用 {free},约需 {needed})并重新检查,"
64
+ "可升级安装更强的本地模型 {model};本工具不会停止任何进程。",
65
+ "Close other programs using memory ({free} available; about {needed} needed) and "
66
+ "check again to install a stronger local model ({model}); this tool stops no process.",
67
+ ),
56
68
  "inference-app-running": (
57
69
  "这台电脑的硬件可以运行本地模型,但另一个推理程序正占用这台 Mac 的 GPU 与统一内存({apps})。"
58
70
  "本工具不会把它的内存算作可释放;请退出该程序后重新检查。",
@@ -74,6 +86,18 @@ MESSAGES: dict[str, tuple[str, str]] = {
74
86
  "(requires CUDA {required} or newer). Update or reinstall the NVIDIA driver and check "
75
87
  "again.",
76
88
  ),
89
+ "gateway-port-in-use": (
90
+ "这台电脑的硬件可以运行本地模型,但网关端口当前被其他程序占用({detail})。"
91
+ "请停止占用该端口的程序,或设置其他网关地址后重新检查。",
92
+ "This computer's hardware can run local models, but the gateway port is currently in use "
93
+ "({detail}). Stop that program or set another gateway address, then check again.",
94
+ ),
95
+ "harness-unavailable": (
96
+ "这台电脑的硬件可以运行本地模型,但网关或工具环境检查未通过({detail})。"
97
+ "请先处理该问题后重新检查。",
98
+ "This computer's hardware can run local models, but gateway or tool preparation is "
99
+ "currently blocked ({detail}). Resolve this issue and check again.",
100
+ ),
77
101
  "plan-invalid": (
78
102
  "批准计划不存在、无效或摘要不一致。",
79
103
  "The approved plan is missing or invalid, or its digest does not match.",
@@ -0,0 +1,155 @@
1
+ """Optional upgrade hint for ``setup inspect`` when freeing desktop memory unlocks a stronger LLM."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import TypedDict
7
+
8
+ from localmodels import (
9
+ budget,
10
+ catalog,
11
+ catalog_recipes,
12
+ harness,
13
+ library_vram,
14
+ llm_rank,
15
+ stack,
16
+ stack_review,
17
+ win_probe,
18
+ )
19
+ from localmodels.contracts import decode
20
+ from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
21
+ from localmodels.plan_envelope import PlanError
22
+ from localmodels.probe import HostFacts
23
+ from localmodels.setup_text import Lang, text
24
+ from localmodels.stack_plan import StackError, StackOptions, StackPlan, deployments
25
+
26
+
27
+ class _ReasonFields(TypedDict, total=False):
28
+ gpuIndex: int
29
+ freeBytes: int
30
+ requiredBytes: int
31
+ detectedCudaVersion: str
32
+ requiredCudaVersion: str
33
+ driverVersion: str
34
+
35
+
36
+ class UpgradeReason(_ReasonFields):
37
+ code: str
38
+ message: str
39
+
40
+
41
+ class _UpgradeOptional(TypedDict, total=False):
42
+ gpuApps: list[win_probe.GpuAppMemory]
43
+
44
+
45
+ class StackUpgrade(_UpgradeOptional):
46
+ plan: StackPlan
47
+ summary: stack_review.PlanSummary
48
+ reasons: list[UpgradeReason]
49
+
50
+
51
+ def _llm_rank_tier(model_id: str, facts: HostFacts) -> tuple[int, int]:
52
+ """(tier, score) for comparing live vs idle-capacity picks: fallback/ladder rungs sit below
53
+ all primary validated models regardless of unranked editorial catalog anchors."""
54
+ if entry := catalog.find_entry(model_id):
55
+ if llm_rank.windows_fallback(entry, facts) or llm_rank.mac_rung(entry, facts):
56
+ return (0, 0)
57
+ return (1, entry.quality)
58
+ for comp in catalog_recipes.components():
59
+ if comp["id"] == model_id:
60
+ quality = comp.get("quality")
61
+ score = quality.get("score") if isinstance(quality, dict) else None
62
+ return (1, int(score) if isinstance(score, int) else 0)
63
+ return (0, 0)
64
+
65
+
66
+ def _vram_by_card(plan: StackPlan) -> dict[int, int]:
67
+ found: dict[int, int] = {}
68
+ for part in deployments(plan):
69
+ for gpu in decode(part["placement"].get("gpus") or [], list[stack_review.SelectedGPU]):
70
+ index = gpu["index"]
71
+ found[index] = found.get(index, 0) + int(str(part["launch"].get("vram_bytes") or 0))
72
+ return found
73
+
74
+
75
+ def upgrade_hint(
76
+ options: StackOptions,
77
+ facts: HostFacts,
78
+ live_plan: StackPlan,
79
+ lang: Lang,
80
+ capacity_facts: Callable[[HostFacts], HostFacts | None],
81
+ ) -> StackUpgrade | None:
82
+ """When freeing desktop memory toward the idle baseline unlocks a strictly stronger LLM,
83
+ return that idle plan, its summary, quantitative reasons, and any closeable GPU apps."""
84
+ roomy = capacity_facts(facts)
85
+ if roomy is None:
86
+ return None
87
+ try:
88
+ roomy_plan = stack.build(options, facts=roomy)
89
+ except (PlanError, StackError, harness.HarnessError):
90
+ return None
91
+ live_id = str(live_plan["llm"]["model"]["id"])
92
+ roomy_id = str(roomy_plan["llm"]["model"]["id"])
93
+ if live_id == roomy_id or _llm_rank_tier(roomy_id, facts) <= _llm_rank_tier(live_id, facts):
94
+ return None
95
+ summary = stack_review.summarize(roomy_plan, lang)
96
+ gib = budget.gib
97
+ reasons: list[UpgradeReason] = []
98
+ live_gpus = {g["index"]: g for g in facts.get("gpus") or []}
99
+ is_strata = str(roomy_plan["llm"]["engine"].get("build") or "").startswith("strata")
100
+ idle_cap = (
101
+ budget.DESKTOP_VRAM_BASELINE_CAP_BYTES
102
+ if facts.get("platform") == "win32" and facts.get("services") is not None
103
+ else budget.IDLE_USED_BYTES
104
+ )
105
+ for index, vram in _vram_by_card(roomy_plan).items():
106
+ card = live_gpus.get(index)
107
+ if card is None:
108
+ continue
109
+ required = vram + AGENT_VRAM_RESERVE_BYTES
110
+ if is_strata and not options.get("share_gpu"):
111
+ required = max(required, max(0, card["total_bytes"] - idle_cap))
112
+ if card["free_bytes"] >= required:
113
+ continue
114
+ reasons.append(
115
+ {
116
+ "code": "gpu-memory-required",
117
+ "message": text(
118
+ "upgrade-gpu-memory",
119
+ lang,
120
+ model=summary["llmName"],
121
+ index=index,
122
+ free=gib(card["free_bytes"]),
123
+ needed=gib(required),
124
+ ),
125
+ "gpuIndex": index,
126
+ "freeBytes": card["free_bytes"],
127
+ "requiredBytes": required,
128
+ }
129
+ )
130
+ ram_free = facts["ram"]["available_bytes"]
131
+ ram_required = summary["memoryBytes"]
132
+ if (not reasons or ram_free < ram_required) and ram_free < min(
133
+ ram_required, roomy["ram"]["available_bytes"]
134
+ ):
135
+ reasons.append(
136
+ {
137
+ "code": "free-memory-required",
138
+ "message": text(
139
+ "upgrade-free-memory",
140
+ lang,
141
+ model=summary["llmName"],
142
+ free=gib(ram_free),
143
+ needed=gib(ram_required),
144
+ ),
145
+ "freeBytes": ram_free,
146
+ "requiredBytes": ram_required,
147
+ }
148
+ )
149
+ if not reasons:
150
+ return None
151
+ hint: StackUpgrade = {"plan": roomy_plan, "summary": summary, "reasons": reasons}
152
+ if any(r["code"] == "gpu-memory-required" for r in reasons):
153
+ if apps := library_vram.closeable_gpu_apps(facts):
154
+ hint["gpuApps"] = apps
155
+ return hint
@@ -112,7 +112,9 @@ def build(
112
112
  == Path(options["base_dir"]).expanduser()
113
113
  ):
114
114
  context = accepted
115
- tools_dir = context["harness"]["tools_dir"] if context else harness.DEFAULT_TOOLS_DIR
115
+ tools_dir = hosts.tools_dir(
116
+ context["harness"]["tools_dir"] if context else harness.DEFAULT_TOOLS_DIR
117
+ )
116
118
  tools = harness.inspect(
117
119
  tools_dir=tools_dir, approved=context["harness"] if context else None, private_clients=True
118
120
  )
@@ -77,7 +77,9 @@ def strata_parts(
77
77
  added to ``passed_over`` for the llama.cpp plan's warnings."""
78
78
  bar, llama_id = llama
79
79
  skipped: list[str] = []
80
- for recipe in stack_suite.auto_strata_candidates(facts, llm_rank.strata_bar(bar, options)):
80
+ for recipe in stack_suite.auto_strata_candidates(
81
+ facts, llm_rank.strata_bar(bar, options), llama_score=bar, options=options
82
+ ):
81
83
  score = recipe["quality"]["score"]
82
84
  why = (
83
85
  f"LLM: auto picks Strata {recipe['id']} (installed SimplexAI score {score}"
@@ -154,7 +156,9 @@ def card_fits(
154
156
  share = bool(options.get("share_gpu", False) or gpu_conflicts(facts).get(gpu["uuid"]))
155
157
  bar = llm_rank.strata_bar(llama_score, probe_opts)
156
158
  fits: list[LlmFit] = []
157
- for recipe in stack_suite.auto_strata_candidates(facts, bar):
159
+ for recipe in stack_suite.auto_strata_candidates(
160
+ facts, bar, llama_score=llama_score, options=probe_opts
161
+ ):
158
162
  candidate_options: StackOptions = {
159
163
  **probe_opts,
160
164
  "gpu": index,
@@ -95,7 +95,7 @@ def plan_tools(
95
95
  actions: list[harness.ToolAction] = []
96
96
  native: dict[str, dict[str, Any]] = {}
97
97
  native_arch = {"x86_64": "x64", "aarch64": "arm64"}.get(arch, arch)
98
- root = Path(tools_dir).expanduser().absolute() / "clients"
98
+ root = Path(hosts.tools_dir(tools_dir)).expanduser().absolute() / "clients"
99
99
  owned = {tool["path"]: tool for tool in hosts.load_owned(tools_dir)["tools"]}
100
100
  for client, seen in planned_clients(state).items():
101
101
  wrapper = Path(harness.BIN_DIR).expanduser() / client
@@ -382,7 +382,11 @@ def _no_fit_reason(
382
382
  if mac or not gpus:
383
383
  return ""
384
384
  if not cards:
385
- eligible = [p for p in placements(facts) if not p.pooled and len(p.gpu_indices) == 1]
385
+ eligible = [
386
+ p
387
+ for p in placements(facts)
388
+ if not p.pooled and not p.budget.uma and len(p.gpu_indices) == 1
389
+ ]
386
390
  if not eligible:
387
391
  return ": no supported single-card GPU placement"
388
392
  if not all(p.conflicts for p in eligible):
@@ -57,16 +57,24 @@ def _bifrost(record: hosts.OwnedBifrost) -> str:
57
57
  return f"failed: {exc}"
58
58
 
59
59
 
60
- def _magpie(doc: hosts.Owned, plan: StackPlan, notes: list[str]) -> str:
60
+ def _magpie(doc: hosts.Owned, plan: StackPlan | None, notes: list[str]) -> str:
61
61
  started = doc["gateway"]["started"]
62
+ owned_magpie = doc["gateway"].get("magpie")
62
63
  if started == "daemon":
63
64
  notes.append("the global magpie.service is not proven to be this tool's; left running")
64
65
  return "kept: global magpie.service"
65
- if started != "serve":
66
+ if started != "serve" and owned_magpie is None:
66
67
  return "none"
67
- magpie = gateway.magpie_binary(doc)
68
- tools_dir = plan["harness"]["tools_dir"]
69
- target = harness_gateway.magpie_target(tools_dir) or plan["harness"]
68
+ if owned_magpie is not None:
69
+ tools_dir = owned_magpie["tools_dir"]
70
+ target = harness_gateway.owned_magpie_target(owned_magpie)
71
+ magpie = owned_magpie["binary"] or gateway.magpie_binary(doc)
72
+ elif plan is not None:
73
+ tools_dir = plan["harness"]["tools_dir"]
74
+ target = harness_gateway.magpie_target(tools_dir) or plan["harness"]
75
+ magpie = gateway.magpie_binary(doc)
76
+ else:
77
+ return "failed: saved stack plan unavailable; gateway left untouched"
70
78
  if magpie is None:
71
79
  return "failed: the Magpie binary this tool installed is missing"
72
80
  check = gateway.stop_gateway(magpie, "serve", tools_dir, plan=target, forget=False)
@@ -76,21 +84,22 @@ def _magpie(doc: hosts.Owned, plan: StackPlan, notes: list[str]) -> str:
76
84
 
77
85
 
78
86
  def _gateway(plan: StackPlan | None, notes: list[str]) -> tuple[str, str]:
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."""
87
+ """Stop the gateway this tool started. Bifrost's own record and a recorded private Magpie
88
+ instance each prove themselves ours even without a saved stack plan (Linger's quit and
89
+ uninstall, GitHub linger#178 / WHI-887). A legacy Magpie manifest without an instance record
90
+ still needs the saved plan's tools directory and is left untouched without it."""
83
91
  doc = hosts.load_owned(plan["harness"]["tools_dir"] if plan else hosts.TOOLS_DIR)
84
92
  record = doc["gateway"].get("bifrost")
85
93
  results: list[tuple[str, str]] = []
86
94
  if record:
87
95
  results.append((_bifrost(record), "Bifrost"))
88
- if doc["gateway"]["started"]:
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
- )
96
+ if doc["gateway"]["started"] or doc["gateway"].get("magpie"):
97
+ if plan is not None or doc["gateway"].get("magpie") is not None:
98
+ results.append((_magpie(doc, plan, notes), "Magpie"))
99
+ else:
100
+ results.append(
101
+ ("failed: saved stack plan unavailable; gateway left untouched", "unknown")
102
+ )
94
103
  for prefix in ("failed", "stopped", "kept", "not-running"):
95
104
  found = next((r for r in results if r[0].startswith(prefix)), None)
96
105
  if found:
@@ -120,7 +129,7 @@ def _down(out: Out) -> DownReport:
120
129
  records = [r for r in hosts.records(hosts.LOCAL_ID) if r["plan"]["name"] in members]
121
130
  notes: list[str] = []
122
131
  # The gateway first: it routes to the services, as up starts it after them.
123
- gate, kind = _gateway(_latest() if members else None, notes)
132
+ gate, kind = _gateway(_latest(), notes)
124
133
  if gate in ("stopped", "not-running") and _library_loaded():
125
134
  notes.append(
126
135
  "models the library loaded keep running without the gateway; unload them "
@@ -140,8 +140,11 @@ def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False)
140
140
  raise StackError(f"this computer has one Metal GPU (GPU 0), no GPU {gpu}")
141
141
  return [0]
142
142
  by_free = {g["index"]: g["free_bytes"] for g in facts.get("gpus") or []}
143
- singles = [p for p in placements(facts, planning=True) if not p.pooled]
144
- singles = [p for p in singles if len(p.gpu_indices) == 1]
143
+ singles = [
144
+ p
145
+ for p in placements(facts, planning=True)
146
+ if not p.pooled and not p.budget.uma and len(p.gpu_indices) == 1
147
+ ]
145
148
  if gpu is not None:
146
149
  if not any(p.gpu_indices == (gpu,) for p in singles):
147
150
  found = ", ".join(str(p.gpu_indices[0]) for p in singles) or "none"
@@ -351,9 +354,20 @@ def llm_fits(
351
354
  llama_score = max(
352
355
  (f["quality"] for _, f in found if not f.get("candidate_fallback")), default=-1
353
356
  )
357
+ preferred_strata = {
358
+ c["id"]
359
+ for c in catalog_recipes.components()
360
+ if c["runtime"] in ("strata", "strata-poly") and c.get("prefer_over_llama")
361
+ }
362
+ strata_vram = {
363
+ c["id"]: int(str(c.get("vram_bytes") or 0))
364
+ for c in catalog_recipes.components()
365
+ if c["runtime"] in ("strata", "strata-poly")
366
+ }
354
367
  for fit in stack_auto.card_fits(facts, index, options, llama_score):
355
368
  _apply_fit_measurement(facts, index, fit)
356
- found.append(((fit["quality"], -1.0), fit))
369
+ tie = (1e9 if fit["id"] in preferred_strata else -1e9) + strata_vram.get(fit["id"], 0) / GIB
370
+ found.append(((fit["quality"], tie), fit))
357
371
  found = [row for row in found if not row[1].get("candidate_fallback")] or found
358
372
  default_id = llm_rank.listed_default(facts, [(f["id"], f["quality"]) for _, f in found])
359
373
  return [
@@ -70,8 +70,17 @@ def picks(cards: Sequence[CardFits], ladder: llm_rank.MacLadder | None = None) -
70
70
  found.setdefault(
71
71
  fit["id"], {**fit, "role": "", "card": card["index"], "shared": not free}
72
72
  )
73
- strata_ids = {
74
- c["id"] for c in catalog_recipes.components() if c["runtime"] in ("strata", "strata-poly")
73
+ components = catalog_recipes.components()
74
+ strata_ids = {c["id"] for c in components if c["runtime"] in ("strata", "strata-poly")}
75
+ preferred_strata = {
76
+ c["id"]
77
+ for c in components
78
+ if c["runtime"] in ("strata", "strata-poly") and c.get("prefer_over_llama")
79
+ }
80
+ strata_vram = {
81
+ c["id"]: int(str(c.get("vram_bytes") or 0))
82
+ for c in components
83
+ if c["runtime"] in ("strata", "strata-poly")
75
84
  }
76
85
  llama_scores = [
77
86
  p["quality"]
@@ -80,25 +89,31 @@ def picks(cards: Sequence[CardFits], ladder: llm_rank.MacLadder | None = None) -
80
89
  and p["id"] not in strata_ids
81
90
  and not p.get("candidate_fallback")
82
91
  ]
83
- bar = llm_rank.strata_bar(max(llama_scores, default=-1), {})
92
+ best_llama = max(llama_scores, default=-1)
84
93
  eligible = [
85
94
  p
86
95
  for p in found.values()
87
- if (p["decode_tok_s"] is not None and p["id"] not in strata_ids) or p["quality"] >= bar
96
+ if (p["decode_tok_s"] is not None and p["id"] not in strata_ids)
97
+ or p["quality"]
98
+ >= llm_rank.strata_recipe_bar(best_llama, {}, prefer_over_llama=p["id"] in preferred_strata)
88
99
  ]
89
100
  if not eligible:
90
101
  return []
91
- ranked = [
92
- (
93
- (p["quality"], -1.0 if p["decode_tok_s"] is None else p["decode_tok_s"]),
94
- p["id"],
95
- p["card"],
96
- )
97
- for p in eligible
98
- ]
102
+
103
+ def _smart_tie(p: Pick) -> float:
104
+ if p["id"] in strata_ids:
105
+ gib_rank = strata_vram.get(p["id"], 0) / (1 << 30)
106
+ return (1e9 if p["id"] in preferred_strata else -1e9) + gib_rank
107
+ return -1.0 if p["decode_tok_s"] is None else p["decode_tok_s"]
108
+
109
+ ranked = [((p["quality"], _smart_tie(p)), p["id"], p["card"]) for p in eligible]
99
110
  fallback_ids = {p["id"] for p in eligible if p.get("candidate_fallback")}
100
111
  smartest = found[llm_rank.choose(ranked, "smartest", ladder, fallback_ids=fallback_ids)[0]]
101
- llama_ranked = [row for row in ranked if row[1] not in strata_ids]
112
+ llama_ranked = [
113
+ ((p["quality"], float(p["decode_tok_s"])), p["id"], p["card"])
114
+ for p in eligible
115
+ if p["id"] not in strata_ids and p["decode_tok_s"] is not None
116
+ ]
102
117
  fastest = (
103
118
  found[llm_rank.choose(llama_ranked, "fastest", ladder, fallback_ids=fallback_ids)[0]]
104
119
  if llama_ranked
@@ -201,10 +201,12 @@ def remove_tools(
201
201
  checks: list[gateway.Check] = []
202
202
  notes: list[str] = []
203
203
  started = doc["gateway"]["started"]
204
- ours = next((t for t in doc["tools"] if Path(t["path"]).name == "magpie"), None)
204
+ ours = next((t for t in doc["tools"] if Path(t["path"]).name in ("magpie", "magpie.exe")), None)
205
205
  drift = harness.changed(ours) if ours and os.path.lexists(ours["path"]) else None
206
206
  if started and magpie and ours and drift:
207
207
  hosts.own_gateway(hosts.TOOLS_DIR, "started", None)
208
+ if doc["gateway"].get("magpie") is not None:
209
+ hosts.own_magpie(hosts.TOOLS_DIR, None)
208
210
  notes.append(
209
211
  f"- gateway ({started}) kept: {ours['path']} {drift}; it may serve other providers"
210
212
  )
@@ -191,7 +191,11 @@ def reads_images(part: Plan) -> bool:
191
191
 
192
192
 
193
193
  def _target_vram(facts: HostFacts, placement: str, primary: Plan) -> int:
194
- candidates = [p for p in placements(facts, planning=True) if not p.pooled and p.gpu_indices]
194
+ candidates = [
195
+ p
196
+ for p in placements(facts, planning=True)
197
+ if not p.pooled and not p.budget.uma and p.gpu_indices
198
+ ]
195
199
  if placement != "auto":
196
200
  matched = [p for p in candidates if p.id == placement]
197
201
  return max((p.budget.total_device_bytes for p in matched), default=0)
@@ -9,11 +9,11 @@ from __future__ import annotations
9
9
 
10
10
  import argparse
11
11
  import json
12
- from collections.abc import Callable
12
+ from collections.abc import Callable, Mapping
13
13
  from dataclasses import replace
14
14
 
15
15
  from localmodels import catalog as cat
16
- from localmodels import cli_help, hosts, metal, stack_ports, suite, vision
16
+ from localmodels import cli_help, hosts, llm_rank, metal, stack_ports, suite, vision
17
17
  from localmodels import stack_decision as decide
18
18
  from localmodels import stack_gpu_memory as gpu_memory
19
19
  from localmodels import stack_hardware as hardware
@@ -179,21 +179,42 @@ def built_for(recipe: suite.SuiteRecipe, platform: str) -> bool:
179
179
  return any(b["platform"] == platform for b in lock["builds"])
180
180
 
181
181
 
182
- def auto_strata_candidates(facts: HostFacts, at_least: int) -> list[suite.SuiteRecipe]:
183
- """Validated Strata LLM recipes with an installed SimplexAI score of at least ``at_least``,
184
- best first, on a computer with the RAM they are recommended for and an engine build for
185
- its platform."""
182
+ def auto_strata_candidates(
183
+ facts: HostFacts,
184
+ at_least: int,
185
+ *,
186
+ llama_score: int | None = None,
187
+ options: Mapping[str, object] | None = None,
188
+ ) -> list[suite.SuiteRecipe]:
189
+ """Validated Strata LLM recipes eligible against the llama.cpp pick, best first, on a
190
+ computer with the RAM they are recommended for and an engine build for its platform."""
186
191
  total = facts["ram"]["total_bytes"]
192
+ opts = options or {}
193
+
194
+ def _bar(r: suite.SuiteRecipe) -> int:
195
+ if llama_score is None:
196
+ return at_least
197
+ return llm_rank.strata_recipe_bar(
198
+ llama_score, opts, prefer_over_llama=bool(r.get("prefer_over_llama"))
199
+ )
200
+
187
201
  found = [
188
202
  r
189
203
  for r in strata_recipes()
190
204
  if r.get("status") == "validated"
191
205
  and "quality" in r
192
- and r["quality"]["score"] >= at_least
206
+ and r["quality"]["score"] >= _bar(r)
193
207
  and total >= r.get("min_ram_total_bytes", 0)
194
208
  and built_for(r, facts["platform"])
195
209
  ]
196
- return sorted(found, key=lambda r: -r["quality"]["score"])
210
+ return sorted(
211
+ found,
212
+ key=lambda r: (
213
+ -r["quality"]["score"],
214
+ -int(bool(r.get("prefer_over_llama"))),
215
+ -r.get("vram_bytes", 0),
216
+ ),
217
+ )
197
218
 
198
219
 
199
220
  def strata_recipe(facts: HostFacts, requested: str) -> tuple[suite.SuiteRecipe | None, list[str]]: