@simplexai/localmodels-win32-x64 0.1.0-dev.63 → 0.1.0-dev.65

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 (142) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +140 -130
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/app.py +15 -2
  6. package/modules/localmodels/approval.py +5 -3
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +36 -0
  9. package/modules/localmodels/catalog.py +28 -5
  10. package/modules/localmodels/catalog_recipes.py +40 -1
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +7 -2
  13. package/modules/localmodels/custom_probe.py +5 -5
  14. package/modules/localmodels/debug_mode.py +85 -103
  15. package/modules/localmodels/deploy.py +129 -18
  16. package/modules/localmodels/deployment_lifecycle.py +167 -0
  17. package/modules/localmodels/download-mirrors.json +126 -6
  18. package/modules/localmodels/draft_spec.py +164 -0
  19. package/modules/localmodels/engine_adapters/__init__.py +4 -0
  20. package/modules/localmodels/engine_adapters/auxiliary.py +27 -0
  21. package/modules/localmodels/engine_adapters/base.py +40 -0
  22. package/modules/localmodels/engine_adapters/strata_poly.py +57 -0
  23. package/modules/localmodels/engine_adapters/suite_plan.py +394 -0
  24. package/modules/localmodels/engines-prism-b12178-03ec600.json +7 -7
  25. package/modules/localmodels/gateway.py +124 -13
  26. package/modules/localmodels/gateway_accept.py +1 -6
  27. package/modules/localmodels/gateway_cli.py +13 -24
  28. package/modules/localmodels/gateway_ops.py +185 -0
  29. package/modules/localmodels/gateway_server.py +3 -2
  30. package/modules/localmodels/harness.py +13 -16
  31. package/modules/localmodels/harness_core.py +4 -9
  32. package/modules/localmodels/harness_gateway.py +4 -3
  33. package/modules/localmodels/hosts.py +22 -34
  34. package/modules/localmodels/install.py +15 -0
  35. package/modules/localmodels/library_convert.py +5 -11
  36. package/modules/localmodels/library_custom.py +6 -6
  37. package/modules/localmodels/library_elastic.py +24 -127
  38. package/modules/localmodels/library_jobs.py +14 -5
  39. package/modules/localmodels/library_order.py +4 -3
  40. package/modules/localmodels/library_poly.py +5 -4
  41. package/modules/localmodels/library_pricing.py +80 -255
  42. package/modules/localmodels/library_serve.py +13 -14
  43. package/modules/localmodels/library_smoke.py +8 -1
  44. package/modules/localmodels/library_status.py +16 -16
  45. package/modules/localmodels/llm_rank.py +1 -1
  46. package/modules/localmodels/magpie_legacy.py +160 -0
  47. package/modules/localmodels/magpie_setup.py +6 -1
  48. package/modules/localmodels/memcalc_cli.py +2 -2
  49. package/modules/localmodels/pi_profile.py +3 -7
  50. package/modules/localmodels/plan_envelope.py +1 -1
  51. package/modules/localmodels/planning/__init__.py +3 -0
  52. package/modules/localmodels/{budget.py → planning/budget.py} +48 -30
  53. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  54. package/modules/localmodels/{memcalc_load.py → planning/memcalc_load.py} +1 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/{sizecalc.py → planning/sizecalc.py} +1 -1
  57. package/modules/localmodels/recommend.py +1 -1
  58. package/modules/localmodels/recommend_cli.py +3 -4
  59. package/modules/localmodels/residency_host.py +1 -1
  60. package/modules/localmodels/service_control.py +4 -4
  61. package/modules/localmodels/service_deployment.py +3 -2
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +1 -1
  64. package/modules/localmodels/setup_inspection_harness.py +1 -1
  65. package/modules/localmodels/setup_upgrade.py +3 -12
  66. package/modules/localmodels/sizecalc_cli.py +10 -2
  67. package/modules/localmodels/speech_admission.py +1 -1
  68. package/modules/localmodels/speech_jobs.py +2 -1
  69. package/modules/localmodels/speech_model.py +2 -0
  70. package/modules/localmodels/speech_server.py +130 -9
  71. package/modules/localmodels/speech_state.py +11 -0
  72. package/modules/localmodels/speech_worker_sensevoice.py +38 -0
  73. package/modules/localmodels/speech_workers.py +5 -1
  74. package/modules/localmodels/stack.py +4 -9
  75. package/modules/localmodels/stack_arena.py +2 -2
  76. package/modules/localmodels/stack_auto.py +5 -5
  77. package/modules/localmodels/stack_aux_gpu.py +5 -3
  78. package/modules/localmodels/stack_binding.py +24 -143
  79. package/modules/localmodels/stack_capacity.py +1 -1
  80. package/modules/localmodels/stack_card.py +3 -3
  81. package/modules/localmodels/stack_cleanup.py +6 -5
  82. package/modules/localmodels/stack_client_settings.py +9 -2
  83. package/modules/localmodels/stack_compose.py +43 -6
  84. package/modules/localmodels/stack_console.py +2 -2
  85. package/modules/localmodels/stack_debug.py +1 -1
  86. package/modules/localmodels/stack_decision.py +1 -1
  87. package/modules/localmodels/stack_doctor.py +10 -7
  88. package/modules/localmodels/stack_down.py +3 -3
  89. package/modules/localmodels/stack_gpu_memory.py +1 -1
  90. package/modules/localmodels/stack_hardware.py +3 -3
  91. package/modules/localmodels/stack_hardware_text.py +1 -1
  92. package/modules/localmodels/stack_ledger.py +2 -1
  93. package/modules/localmodels/stack_lifecycle.py +7 -7
  94. package/modules/localmodels/stack_mcp.py +1 -1
  95. package/modules/localmodels/stack_memory.py +4 -4
  96. package/modules/localmodels/stack_mlx.py +1 -1
  97. package/modules/localmodels/stack_plan.py +18 -13
  98. package/modules/localmodels/stack_ports.py +2 -2
  99. package/modules/localmodels/stack_preflight.py +4 -3
  100. package/modules/localmodels/stack_remove.py +13 -6
  101. package/modules/localmodels/stack_review.py +3 -5
  102. package/modules/localmodels/stack_rollback.py +1 -1
  103. package/modules/localmodels/stack_route.py +5 -4
  104. package/modules/localmodels/stack_run.py +16 -0
  105. package/modules/localmodels/stack_suite.py +14 -6
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +10 -14
  108. package/modules/localmodels/stack_up.py +25 -39
  109. package/modules/localmodels/stack_update.py +2 -1
  110. package/modules/localmodels/stack_verify.py +4 -30
  111. package/modules/localmodels/stack_view.py +6 -4
  112. package/modules/localmodels/stack_view_apply.py +2 -2
  113. package/modules/localmodels/stack_view_llm.py +12 -7
  114. package/modules/localmodels/stack_view_text.py +2 -6
  115. package/modules/localmodels/stack_view_tick.py +2 -2
  116. package/modules/localmodels/stack_view_words.py +5 -2
  117. package/modules/localmodels/stack_warm.py +7 -4
  118. package/modules/localmodels/stack_whatif.py +1 -1
  119. package/modules/localmodels/suite.py +6 -334
  120. package/modules/localmodels/tui_views.py +28 -7
  121. package/modules/localmodels/web/index.html +595 -226
  122. package/modules/localmodels/web/sizecalc/app.js +34 -40
  123. package/modules/localmodels/web/sizecalc/calc.js +3 -3
  124. package/modules/localmodels/web/sizecalc/page.html +4 -3
  125. package/modules/localmodels/web/view/fleet.html +18 -3
  126. package/modules/localmodels/web/view/fleet.js +135 -14
  127. package/modules/localmodels/web/view/i18n.js +4 -0
  128. package/modules/localmodels/web/view/index.html +16 -0
  129. package/modules/localmodels/web/view/nav.js +49 -0
  130. package/modules/localmodels/web/view/theme.js +1 -1
  131. package/modules/localmodels/web/view/view.css +51 -15
  132. package/modules/localmodels/web/view/view.js +22 -4
  133. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/METADATA +1 -1
  134. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/RECORD +137 -127
  135. package/package.json +1 -1
  136. package/tool.json +1 -1
  137. package/modules/localmodels/library_vram.py +0 -123
  138. /package/modules/localmodels/{memcalc.py → planning/memcalc.py} +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/WHEEL +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/entry_points.txt +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/NOTICE +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,403 @@
1
+ """The model library's memory pools and what each holds on this computer.
2
+
3
+ A pool is where one library model runs: a discrete NVIDIA card (``gpu:N``), Apple Silicon or CUDA
4
+ unified memory (``unified``), else host RAM (``system``), each named after the stack planner's
5
+ placement (``budget.placements``). Here are each pool's total, free memory and reserve, the
6
+ host-facts projections the planner prices a model on (loadable capacity, live free memory, a
7
+ target budget), the pool and memory a deployment plan takes, and the desktop/WDDM VRAM guidance
8
+ library status and Quick Install share. Pure functions of host facts and plans, except that
9
+ ``visible`` reads ``CUDA_VISIBLE_DEVICES``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import copy
15
+ import math
16
+ import os
17
+ from collections.abc import Callable, Mapping, Sequence
18
+ from typing import Any
19
+
20
+ from localmodels import metal, plan_envelope, win_probe
21
+ from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES, METAL_VRAM_RESERVE_BYTES
22
+ from localmodels.library_model import ExternalHolder
23
+ from localmodels.planning import budget
24
+ from localmodels.probe import GPU, HostFacts
25
+ from localmodels.records import Plan
26
+
27
+ POOL_RAM_FRACTION = 0.8 # a "system" pool's budget: RAM x 0.8 (contract v2)
28
+ UNIFIED_RESERVE_BYTES = metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
29
+
30
+
31
+ def visible(facts: HostFacts) -> set[int] | None:
32
+ """The NVIDIA cards ``CUDA_VISIBLE_DEVICES`` (indices or UUIDs) leaves to the library;
33
+ None when it is not set. The library never places a model on a card hidden from it."""
34
+ given = os.environ.get("CUDA_VISIBLE_DEVICES")
35
+ if given is None:
36
+ return None
37
+ names = {part.strip() for part in given.split(",") if part.strip()}
38
+ return {
39
+ g["index"]
40
+ for g in facts.get("gpus") or []
41
+ if str(g["index"]) in names or g["uuid"] in names
42
+ }
43
+
44
+
45
+ def cuda_uma_bytes(facts: HostFacts) -> int | None:
46
+ """Allocator pool bytes for an NVIDIA unified-memory device (e.g. Grace/GB10), else None;
47
+ None on a Mac, whose unified memory is Metal's."""
48
+ if metal.supported(facts):
49
+ return None
50
+ return budget.unified_pool_bytes(facts)
51
+
52
+
53
+ def pools(facts: HostFacts) -> dict[str, str]:
54
+ """Pool id -> the planner's placement id: one per discrete NVIDIA card (``gpu:N``),
55
+ Apple Silicon or CUDA unified memory (``unified``), and ``system`` for host RAM."""
56
+ found: dict[str, str] = {}
57
+ shown = visible(facts)
58
+ for p in budget.placements(facts, planning=True):
59
+ if p.pooled:
60
+ continue
61
+ if p.backend == "metal":
62
+ found["unified"] = p.id
63
+ elif p.backend == "cuda" and p.budget.uma:
64
+ if not p.gpu_indices or shown is None or p.gpu_indices[0] in shown:
65
+ found["unified"] = p.id
66
+ elif p.backend == "cuda" and not p.budget.uma and len(p.gpu_indices) == 1:
67
+ if shown is None or p.gpu_indices[0] in shown:
68
+ found[f"gpu:{p.gpu_indices[0]}"] = p.id
69
+ if "unified" not in found:
70
+ found["system"] = "cpu"
71
+ return found
72
+
73
+
74
+ def gpu_index(pool: str) -> int | None:
75
+ return int(pool.split(":", 1)[1]) if pool.startswith("gpu:") else None
76
+
77
+
78
+ def pool_total(facts: HostFacts, pool: str) -> int:
79
+ index = gpu_index(pool)
80
+ if index is not None:
81
+ return next(g["total_bytes"] for g in facts["gpus"] if g["index"] == index)
82
+ if pool == "unified":
83
+ if (unified := cuda_uma_bytes(facts)) is not None:
84
+ return budget.cuda_uma_agent_bytes(unified)
85
+ return max(0, facts["ram"]["total_bytes"] - budget.metal_reserve_bytes(facts))
86
+ return int(facts["ram"]["total_bytes"] * POOL_RAM_FRACTION)
87
+
88
+
89
+ def _unified_live(facts: HostFacts) -> tuple[int, int]:
90
+ """(free_bytes, reserve_bytes) on a unified pool: the admission budget's soft budget and
91
+ reserve (``budget.admission_budget``). A CUDA pool the driver reports as empty is priced on
92
+ the host's RAM instead."""
93
+ if (unified := cuda_uma_bytes(facts)) is not None:
94
+ base = unified or facts["ram"]["total_bytes"]
95
+ free = budget.cuda_uma_agent_bytes(budget.cuda_uma_live_bytes(facts, base))
96
+ return free, max(0, base - budget.cuda_uma_agent_bytes(base))
97
+ adm = budget.admission_budget(facts, "unified")
98
+ if adm is None:
99
+ return 0, budget.metal_reserve_bytes(facts)
100
+ return adm.soft_budget_bytes, adm.reserve_bytes
101
+
102
+
103
+ def pool_free(facts: HostFacts, pool: str) -> int:
104
+ index = gpu_index(pool)
105
+ if index is not None:
106
+ return next(g["free_bytes"] for g in facts["gpus"] if g["index"] == index)
107
+ if pool == "unified":
108
+ return _unified_live(facts)[0]
109
+ used = facts["ram"]["total_bytes"] - facts["ram"]["available_bytes"]
110
+ return max(0, pool_total(facts, pool) - used)
111
+
112
+
113
+ def pool_reserve(facts: HostFacts, pool: str) -> int:
114
+ """Memory kept back from models on ``pool`` for OS, display, or safety margins."""
115
+ if gpu_index(pool) is not None:
116
+ return AGENT_VRAM_RESERVE_BYTES
117
+ if pool == "unified":
118
+ return _unified_live(facts)[1]
119
+ return max(0, facts["ram"]["total_bytes"] - pool_total(facts, pool))
120
+
121
+
122
+ def pool_of(plan: Plan) -> str:
123
+ """The pool a deployment plan runs in: its card, unified memory, else RAM."""
124
+ placement: dict[str, Any] = dict(plan.get("placement") or {})
125
+ gpus: list[dict[str, Any]] = list(placement.get("gpus") or [])
126
+ if placement.get("id") == "host" or (gpus and gpus[0].get("uuid") == metal.METAL_UUID):
127
+ return "unified"
128
+ if gpus:
129
+ return f"gpu:{gpus[0]['index']}"
130
+ return "system"
131
+
132
+
133
+ def memory_bytes(plan: Plan) -> int:
134
+ """The memory a deployment plan takes in its pool: its unified bytes, else its VRAM."""
135
+ launch = plan["launch"]
136
+ value = launch.get("unified_bytes") or launch.get("vram_bytes") or 0
137
+ return int(str(value))
138
+
139
+
140
+ # ---------------------------------------------------------------------------- host projections
141
+
142
+
143
+ def capacity(facts: HostFacts, *, reclaimable: Mapping[str, int] | None = None) -> HostFacts:
144
+ """``facts`` at loadable capacity once loaded library models are unloaded: keeps macOS's
145
+ idle baseline (``metal.in_use``) on Apple Silicon and observed desktop/WDDM baseline VRAM
146
+ on Windows and display-active GPUs instead of pretending zero OS/desktop overhead."""
147
+ seen = copy.deepcopy(facts)
148
+ for gpu in seen.get("gpus") or []:
149
+ free = gpu_capacity_free(facts, gpu, reclaimable)
150
+ gpu["free_bytes"], gpu["used_bytes"] = free, max(0, gpu["total_bytes"] - free)
151
+ ram = seen["ram"]
152
+ if metal.supported(seen):
153
+ total = ram["total_bytes"]
154
+ idle = max(0, total - metal.in_use(total))
155
+ ram["available_bytes"] = min(total, max(ram["available_bytes"], idle))
156
+ if ram.get("pressure_level") is not None:
157
+ ram["pressure_level"] = 1
158
+ ram.pop("pressure_kept_bytes", None)
159
+ else:
160
+ ram["available_bytes"] = ram["total_bytes"]
161
+ if cgroup := seen.get("cgroup_memory"):
162
+ cgroup["usage_bytes"] = 0
163
+ seen["llama_servers"] = []
164
+ seen["disk"] = {**seen["disk"], "free_bytes": None}
165
+ if services := seen.get("services"):
166
+ services["compute_processes"], services["containers"] = [], []
167
+ services["systemd_units"] = []
168
+ return seen
169
+
170
+
171
+ def live(
172
+ facts: HostFacts, reserved: dict[str, int], freed: dict[str, int] | None = None
173
+ ) -> HostFacts:
174
+ """``facts`` less what loading models reserved and plus what ``freed`` gives back, per pool;
175
+ ports and disk are left to the load (a download plan is not bound to them)."""
176
+ seen = copy.deepcopy(facts)
177
+ change = dict(reserved)
178
+ for pool, n in (freed or {}).items():
179
+ change[pool] = change.get(pool, 0) - n
180
+ for gpu in seen.get("gpus") or []:
181
+ delta = change.get(f"gpu:{gpu['index']}", 0)
182
+ gpu["free_bytes"] = max(0, min(gpu["total_bytes"], gpu["free_bytes"] - delta))
183
+ ram = seen["ram"]
184
+ unified_delta = change.get("unified", 0)
185
+ system_delta = change.get("system", 0)
186
+ if (unified := cuda_uma_bytes(seen)) is not None and unified_delta:
187
+ cards = budget.nvidia_cards(seen)
188
+ first = cards[0] if cards else None
189
+ first_free = first["free_bytes"] if first is not None else 0
190
+ current_live = min(unified, first_free + ram["available_bytes"])
191
+ scaled = int(round(unified_delta / (1 - budget.UMA_HEADROOM_FRACTION)))
192
+ target = max(0, min(unified, current_live - scaled))
193
+ if first is not None and first_free > target:
194
+ first["free_bytes"], ram["available_bytes"] = target, 0
195
+ else:
196
+ ram["available_bytes"] = max(0, min(ram["total_bytes"], target - first_free))
197
+ if system_delta:
198
+ ram["available_bytes"] = max(
199
+ 0, min(ram["total_bytes"], ram["available_bytes"] - system_delta)
200
+ )
201
+ else:
202
+ delta = unified_delta + system_delta
203
+ ram["available_bytes"] = max(0, min(ram["total_bytes"], ram["available_bytes"] - delta))
204
+ if metal.supported(seen) and unified_delta:
205
+ gpu_reading = metal.gpu_in_use_reading(seen)
206
+ metal_doc = seen.get("metal")
207
+ if isinstance(metal_doc, dict):
208
+ cur_in_use = metal.gpu_in_use_bytes(seen)
209
+ metal_doc["gpu_in_use_bytes"] = max(0, cur_in_use + unified_delta)
210
+ wired_ram = ram.get("wired_bytes")
211
+ if isinstance(wired_ram, int) and not isinstance(wired_ram, bool) and wired_ram >= 0:
212
+ wired_delta = (
213
+ max(unified_delta, -gpu_reading)
214
+ if unified_delta < 0 and gpu_reading is not None
215
+ else unified_delta
216
+ )
217
+ ram["wired_bytes"] = max(0, min(ram["total_bytes"], wired_ram + wired_delta))
218
+ seen["llama_servers"] = []
219
+ seen["disk"] = {**seen["disk"], "free_bytes": None}
220
+ return seen
221
+
222
+
223
+ def _project_cuda_uma(
224
+ facts: HostFacts, unified: int, target: int, *, bypass_working_set: bool
225
+ ) -> HostFacts:
226
+ seen = copy.deepcopy(facts)
227
+ need = target + AGENT_VRAM_RESERVE_BYTES
228
+ raw = int(math.ceil(need / (1 - budget.UMA_HEADROOM_FRACTION)))
229
+ while budget.uma_usable(raw) < need:
230
+ raw += 1
231
+ raw = raw if bypass_working_set else min(unified, raw)
232
+ if bypass_working_set and isinstance(cuda_pool := seen.get("cuda_pool"), dict):
233
+ cuda_pool["total_bytes"], cuda_pool["integrated"] = max(unified, raw), True
234
+ if cards := budget.nvidia_cards(seen):
235
+ cards[0]["free_bytes"], cards[0]["used_bytes"] = 0, cards[0]["total_bytes"]
236
+ ram = seen["ram"]
237
+ if bypass_working_set:
238
+ ram["total_bytes"] = max(int(ram["total_bytes"]), raw)
239
+ if (cgroup := seen.get("cgroup_memory")) is not None:
240
+ if (limit := cgroup.get("limit_bytes")) is not None and limit < raw:
241
+ cgroup["limit_bytes"] = raw
242
+ cgroup["usage_bytes"] = 0
243
+ ram["available_bytes"] = min(int(ram["total_bytes"]), raw)
244
+ return seen
245
+
246
+
247
+ def facts_for_budget(
248
+ facts: HostFacts,
249
+ pool: str,
250
+ target_bytes: int,
251
+ *,
252
+ wired_cap_bytes: int | None = None,
253
+ bypass_working_set: bool = False,
254
+ ) -> HostFacts:
255
+ """Project ``facts`` so ``deploy.build_plan`` prices ``pool`` against ``target_bytes``
256
+ (unified/total) and optional ``wired_cap_bytes`` (Metal GPU wired headroom)."""
257
+ target = max(0, target_bytes)
258
+ if pool == "unified" and metal.supported(facts):
259
+ seen = copy.deepcopy(facts)
260
+ ram = seen["ram"]
261
+ needed_avail = target + metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
262
+ ram["available_bytes"] = (
263
+ needed_avail if bypass_working_set else min(int(ram["total_bytes"]), needed_avail)
264
+ )
265
+ ram["pressure_level"] = metal.PRESSURE_NORMAL
266
+ ram.pop("pressure_kept_bytes", None)
267
+ if isinstance(metal_doc := seen.get("metal"), dict):
268
+ ceiling = (
269
+ max(0, wired_cap_bytes) + METAL_VRAM_RESERVE_BYTES
270
+ if wired_cap_bytes is not None
271
+ else max(metal.wired_ceiling_bytes(facts), target + METAL_VRAM_RESERVE_BYTES)
272
+ if bypass_working_set
273
+ else metal.wired_ceiling_bytes(facts)
274
+ )
275
+ metal_doc["recommended_max_working_set_bytes"] = ceiling
276
+ return seen
277
+ if pool == "unified" and (unified := budget.unified_pool_bytes(facts)) is not None:
278
+ return _project_cuda_uma(facts, unified, target, bypass_working_set=bypass_working_set)
279
+ if (idx := gpu_index(pool)) is not None:
280
+ seen = copy.deepcopy(facts)
281
+ for gpu in seen.get("gpus") or []:
282
+ if gpu["index"] == idx:
283
+ free = target + AGENT_VRAM_RESERVE_BYTES
284
+ gpu["free_bytes"] = free if bypass_working_set else min(gpu["total_bytes"], free)
285
+ gpu["used_bytes"] = max(0, gpu["total_bytes"] - gpu["free_bytes"])
286
+ break
287
+ return seen
288
+ return facts
289
+
290
+
291
+ # ---------------------------------------------------------------------------- desktop VRAM
292
+
293
+
294
+ def _owned_gpu_bytes(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
295
+ pool = f"gpu:{gpu['index']}"
296
+ from_records = max(0, int((reclaimable or {}).get(pool, 0)))
297
+ services = facts.get("services")
298
+ procs = (services.get("compute_processes") if services else None) or []
299
+ from_procs = sum(
300
+ int(p.get("used_bytes") or 0)
301
+ for p in procs
302
+ if p["gpu_uuid"] == gpu["uuid"] and p.get("owned") is True
303
+ )
304
+ return max(from_records, from_procs)
305
+
306
+
307
+ def _foreign_gpu_bytes(facts: HostFacts, gpu: GPU) -> int:
308
+ services = facts.get("services")
309
+ procs = (services.get("compute_processes") if services else None) or []
310
+ return sum(
311
+ int(p.get("used_bytes") or 0)
312
+ for p in procs
313
+ if p["gpu_uuid"] == gpu["uuid"] and budget.foreign_work(p, facts)
314
+ )
315
+
316
+
317
+ def gpu_capacity_free(
318
+ facts: HostFacts,
319
+ gpu: GPU,
320
+ reclaimable: Mapping[str, int] | None,
321
+ ) -> int:
322
+ """Loadable VRAM on ``gpu`` once owned models and transient foreign work clear, keeping
323
+ observed desktop/WDDM baseline occupancy on Windows and display-active GPUs."""
324
+ total = gpu["total_bytes"]
325
+ if facts.get("platform") != "win32" and not gpu.get("display_active"):
326
+ return total
327
+ taken = max(gpu["used_bytes"], max(0, total - gpu["free_bytes"]))
328
+ desktop_used = max(
329
+ 0, taken - _owned_gpu_bytes(facts, gpu, reclaimable) - _foreign_gpu_bytes(facts, gpu)
330
+ )
331
+ baseline = min(desktop_used, budget.DESKTOP_VRAM_BASELINE_CAP_BYTES)
332
+ return min(total, max(gpu["free_bytes"], total - baseline))
333
+
334
+
335
+ def closeable_gpu_apps(facts: HostFacts) -> list[win_probe.GpuAppMemory]:
336
+ """Closeable desktop GPU apps from Windows CIM, excluding owned localmodels PIDs."""
337
+ raw_procs = facts.get("gpu_processes") or []
338
+ if not raw_procs:
339
+ return []
340
+ services = facts.get("services")
341
+ owned_pids = {
342
+ int(p["pid"])
343
+ for p in ((services.get("compute_processes") if services else None) or [])
344
+ if p.get("owned") is True
345
+ }
346
+ found: list[win_probe.GpuAppMemory] = []
347
+ for proc in raw_procs:
348
+ pids = [int(pid) for pid in proc["pids"] if int(pid) not in owned_pids]
349
+ if pids and proc["bytes"] > 0:
350
+ found.append({"name": proc["name"], "pids": pids, "bytes": int(proc["bytes"])})
351
+ return found
352
+
353
+
354
+ def pool_external_holders(facts: HostFacts, pool: str, gpu_pool_count: int) -> list[ExternalHolder]:
355
+ """External closeable desktop GPU apps attributable to ``pool`` (single GPU or display GPU)."""
356
+ if not pool.startswith("gpu:"):
357
+ return []
358
+ index = int(pool.split(":", 1)[1])
359
+ gpu = next((g for g in facts.get("gpus") or [] if g["index"] == index), None)
360
+ if gpu is None or (gpu_pool_count > 1 and not gpu.get("display_active")):
361
+ return []
362
+ return [
363
+ {"name": app["name"], "bytes": app["bytes"], "pids": app["pids"]}
364
+ for app in closeable_gpu_apps(facts)
365
+ ]
366
+
367
+
368
+ def idle_desktop_capacity(facts: HostFacts, cap: HostFacts) -> HostFacts | None:
369
+ """``cap`` with desktop/WDDM discrete GPUs raised to the 1 GiB idle floor, or None when no
370
+ card gains headroom over ``cap``."""
371
+ if facts.get("platform") != "win32" and not any(
372
+ g.get("display_active") for g in facts.get("gpus") or []
373
+ ):
374
+ return None
375
+ roomy = copy.deepcopy(cap)
376
+ gained = False
377
+ for gpu in roomy.get("gpus") or []:
378
+ idle = max(0, gpu["total_bytes"] - budget.IDLE_USED_BYTES)
379
+ if gpu["free_bytes"] < idle:
380
+ gpu["free_bytes"], gpu["used_bytes"] = idle, gpu["total_bytes"] - idle
381
+ gained = True
382
+ return roomy if gained else None
383
+
384
+
385
+ def fits_idle_desktop(
386
+ facts: HostFacts,
387
+ cap: HostFacts,
388
+ pools: Sequence[str],
389
+ try_price: Callable[[HostFacts, str], object],
390
+ ) -> bool:
391
+ """True when ``try_price`` succeeds on any discrete GPU once desktop VRAM nears 1 GiB idle."""
392
+ roomy = idle_desktop_capacity(facts, cap)
393
+ if roomy is None:
394
+ return False
395
+ for pool in pools:
396
+ if not pool.startswith("gpu:"):
397
+ continue
398
+ try:
399
+ try_price(roomy, pool)
400
+ return True
401
+ except plan_envelope.PlanError:
402
+ continue
403
+ return False
@@ -18,7 +18,7 @@ from dataclasses import dataclass
18
18
  from typing import Any
19
19
 
20
20
  from localmodels import estimator, metal, quant_formats
21
- from localmodels.memcalc import GIB, KIB, MemcalcError
21
+ from localmodels.planning.memcalc import GIB, KIB, MemcalcError
22
22
  from localmodels.quant_formats import QuantFormat
23
23
 
24
24
  SCHEMA = "localmodels.sizecalc/v1"
@@ -11,9 +11,9 @@ from typing import Literal, TypedDict
11
11
 
12
12
  from localmodels import catalog as cat
13
13
  from localmodels import llm_rank, stack_warm_store
14
- from localmodels.budget import Placement, agent_budget, gib, placements
15
14
  from localmodels.context_policy import AGENT, window_k
16
15
  from localmodels.estimator import PhysicsRefusal
16
+ from localmodels.planning.budget import Placement, agent_budget, gib, placements
17
17
  from localmodels.probe import HostFacts
18
18
 
19
19
  FitReason = Literal["fits", "insufficient-memory", "unsupported-platform", "unsupported-runtime"]
@@ -11,6 +11,7 @@ from localmodels import (
11
11
  deploy,
12
12
  harness,
13
13
  hosts,
14
+ magpie_legacy,
14
15
  plan_envelope,
15
16
  stack,
16
17
  stack_capacity,
@@ -20,7 +21,7 @@ from localmodels import (
20
21
  suite,
21
22
  )
22
23
  from localmodels import catalog as cat
23
- from localmodels.budget import gib, gpu_conflicts, unknown_services
24
+ from localmodels.planning.budget import gib, gpu_conflicts, unknown_services
24
25
  from localmodels.probe import HostFacts
25
26
  from localmodels.records import Plan
26
27
  from localmodels.stack_compose import agent_posture
@@ -132,9 +133,7 @@ def _show_parts(
132
133
  f"{p['endpoint']['contract']} {p['model']['id']}({p['placement']['label']})"
133
134
  for p in plan["aux"]
134
135
  ]
135
- gateway = (
136
- "Bifrost" if harness.gateway_kind(plan["harness"]["gateway"]) == "bifrost" else "Magpie"
137
- )
136
+ gateway = magpie_legacy.of(plan["harness"]["gateway"]).label
138
137
  print("默认组合:" + " + ".join([*pieces, gateway, "pi"]))
139
138
  print(" 按上面的硬件快照规划,不是已批准的安装计划。")
140
139
  print(
@@ -8,7 +8,6 @@ from pathlib import Path
8
8
 
9
9
  from localmodels import (
10
10
  app,
11
- budget,
12
11
  deploy,
13
12
  hosts,
14
13
  probe,
@@ -17,6 +16,7 @@ from localmodels import (
17
16
  stack_lifecycle,
18
17
  )
19
18
  from localmodels.contracts import decode
19
+ from localmodels.planning import budget
20
20
  from localmodels.probe import HostFacts, Services
21
21
  from localmodels.records import FinishedRecord
22
22
  from localmodels.residency import ROLES, Binding, Member, Resources, Role
@@ -18,7 +18,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
18
18
  from pathlib import Path
19
19
  from typing import Any, cast
20
20
 
21
- from localmodels import runtime_io
21
+ from localmodels import magpie_legacy, runtime_io
22
22
  from localmodels.residency import Residency
23
23
  from localmodels.service_jobs import RetryConflictError, ServiceJobs, selected_roles
24
24
 
@@ -135,9 +135,9 @@ class Handler(BaseHTTPRequestHandler):
135
135
  self.send_json(503, {"error": "invalid_local_gateway"})
136
136
  return
137
137
  target = binding["baseUrl"] + self.path.removeprefix("/gateway/v1")
138
- if binding.get("kind") == "bifrost" and self.path == "/gateway/v1/systemone":
139
- # Bifrost serves the typesafe decision API under its own prefix.
140
- target = f"http://127.0.0.1:{base.port}/typesafe/v1/systemone"
138
+ decision_path = magpie_legacy.of(binding).decision_path
139
+ if decision_path and self.path == "/gateway/v1/systemone":
140
+ target = f"http://127.0.0.1:{base.port}{decision_path}"
141
141
  headers = {
142
142
  "Authorization": "Bearer " + binding["key"],
143
143
  "Content-Type": "application/json",
@@ -12,7 +12,6 @@ from typing import Any, cast
12
12
  from localmodels import (
13
13
  app,
14
14
  approval,
15
- budget,
16
15
  catalog,
17
16
  component,
18
17
  deploy,
@@ -30,7 +29,9 @@ from localmodels import (
30
29
  from localmodels import stack_decision as decision
31
30
  from localmodels import stack_lifecycle as lifecycle
32
31
  from localmodels.contracts import decode
32
+ from localmodels.engine_adapters import suite_plan
33
33
  from localmodels.plan_envelope import PlanError, deployment
34
+ from localmodels.planning import budget
34
35
  from localmodels.probe import HostFacts, Services
35
36
  from localmodels.records import FinishedRecord, Plan
36
37
  from localmodels.service_jobs import (
@@ -86,7 +87,7 @@ def plan_component(
86
87
  )
87
88
  except PlanError as exc:
88
89
  raise WaitingForResourcesError("port") from exc
89
- built = suite.build_plan(
90
+ built = suite_plan.build_plan(
90
91
  "local",
91
92
  facts,
92
93
  recipe,
@@ -13,6 +13,7 @@ from urllib.parse import urlsplit
13
13
 
14
14
  from localmodels import (
15
15
  bifrost_config,
16
+ deployment_lifecycle,
16
17
  gateway,
17
18
  gateway_bifrost,
18
19
  gateway_keys,
@@ -24,6 +25,7 @@ from localmodels import (
24
25
  library_model,
25
26
  library_serve,
26
27
  library_state,
28
+ magpie_legacy,
27
29
  source_byok,
28
30
  stack,
29
31
  )
@@ -70,13 +72,8 @@ def prepare_gateway(root: Path, binding: dict[str, str] | None = None) -> harnes
70
72
  return plan
71
73
 
72
74
 
73
- def set_gateway_binding(jobs: ServiceJobs, addr: str, kind: str = "magpie") -> None:
74
- # Magpie's documented local client key is an app identity, not a remote gateway secret;
75
- # this tool's Bifrost checks no key on loopback inference.
76
- binding = {"baseUrl": f"http://{addr}/v1", "key": "magpie-simplex"}
77
- if kind == "bifrost":
78
- binding = {"baseUrl": f"http://{addr}/v1", "key": gateway_keys.CALLER_KEY, "kind": kind}
79
- jobs.set_gateway(binding)
75
+ def set_gateway_binding(jobs: ServiceJobs, addr: str, kind: str = magpie_legacy.MAGPIE) -> None:
76
+ jobs.set_gateway(magpie_legacy.for_kind(kind).binding(addr, gateway_keys.CALLER_KEY))
80
77
 
81
78
 
82
79
  def auxiliary_endpoints(bindings: dict[str, dict[str, str]]) -> list[AuxEndpoint]:
@@ -134,7 +131,7 @@ def _stack_llm_active(plan: StackPlan) -> bool:
134
131
  owned = None
135
132
  if owned is not None:
136
133
  entry = owned["deployments"].get(plan["llm"]["name"])
137
- if entry is not None and entry.get("removed"):
134
+ if deployment_lifecycle.is_removed(entry):
138
135
  return False
139
136
  key_file = Path(os.path.expanduser(plan["llm"]["service"]["deploy_dir"]), "api-key")
140
137
  if entry is None and not key_file.is_file():
@@ -238,14 +235,13 @@ class Wiring:
238
235
  if addr is None:
239
236
  jobs.set_gateway(None)
240
237
  else:
241
- set_gateway_binding(jobs, addr, "bifrost")
238
+ set_gateway_binding(jobs, addr, magpie_legacy.BIFROST)
242
239
  self.last = copy.deepcopy(signature)
243
240
 
244
241
  def _sync_inactive_magpie(
245
242
  self,
246
243
  signature: object,
247
244
  tools_plan: harness.HarnessPlan,
248
- kind: str,
249
245
  bindings: dict[str, dict[str, str]],
250
246
  had_bindings: bool,
251
247
  jobs: ServiceJobs,
@@ -266,7 +262,7 @@ class Wiring:
266
262
  decision_provider=decision_pid,
267
263
  )
268
264
  if bindings:
269
- set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
265
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"])
270
266
  else:
271
267
  jobs.set_gateway(None)
272
268
  self.last = copy.deepcopy(signature)
@@ -276,7 +272,7 @@ class Wiring:
276
272
  main_plan: Path,
277
273
  plan_id: str,
278
274
  tools_plan: harness.HarnessPlan,
279
- kind: str,
275
+ adapter: magpie_legacy.GatewayAdapter,
280
276
  bindings: dict[str, dict[str, str]],
281
277
  jobs: ServiceJobs,
282
278
  ) -> None:
@@ -290,12 +286,13 @@ class Wiring:
290
286
  if bifrost_record is not None
291
287
  else {}
292
288
  )
293
- if kind == "bifrost" or bifrost_doc:
289
+ # A Magpie plan still syncs the foundations into a Bifrost config this tool keeps.
290
+ if not adapter.legacy or bifrost_doc:
294
291
  self._sync_inactive_bifrost(
295
292
  signature, bifrost_record, bifrost_doc, tools_plan, bindings, had_bindings, jobs
296
293
  )
297
294
  return
298
- self._sync_inactive_magpie(signature, tools_plan, kind, bindings, had_bindings, jobs)
295
+ self._sync_inactive_magpie(signature, tools_plan, bindings, had_bindings, jobs)
299
296
 
300
297
  def sync(self, main_plan: Path | None, jobs: ServiceJobs) -> None:
301
298
  bindings = jobs.bindings()
@@ -335,9 +332,9 @@ class Wiring:
335
332
  if not ready.get("ready") or ready.get("planId") != plan["plan_id"]:
336
333
  return
337
334
  tools_plan = copy.deepcopy(plan["harness"])
338
- kind = harness.gateway_kind(tools_plan["gateway"])
335
+ adapter = magpie_legacy.of(tools_plan["gateway"])
339
336
  if not _stack_llm_active(plan):
340
- self._sync_inactive(main_plan, plan["plan_id"], tools_plan, kind, bindings, jobs)
337
+ self._sync_inactive(main_plan, plan["plan_id"], tools_plan, adapter, bindings, jobs)
341
338
  return
342
339
  signature = (str(main_plan), plan["plan_id"], receipt.stat().st_mtime_ns, bindings)
343
340
  if self.last == signature:
@@ -348,8 +345,9 @@ class Wiring:
348
345
  )
349
346
  aux = auxiliary_endpoints(bindings)
350
347
  # Only update the owned routing group. Never replace a user's current Pi selection.
351
- with library_gateway.gateway_locked() if kind == "bifrost" else contextlib.nullcontext():
352
- if kind == "bifrost" and not _stack_llm_active(plan):
348
+ shared = adapter.shares_config
349
+ with library_gateway.gateway_locked() if shared else contextlib.nullcontext():
350
+ if shared and not _stack_llm_active(plan):
353
351
  return
354
352
  gateway.wire(
355
353
  tools_plan,
@@ -358,5 +356,5 @@ class Wiring:
358
356
  aux,
359
357
  select_pi=False,
360
358
  )
361
- set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
359
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"], adapter.kind)
362
360
  self.last = copy.deepcopy(signature)
@@ -12,7 +12,6 @@ from typing import Any, Literal, TypedDict
12
12
 
13
13
  from localmodels import (
14
14
  app,
15
- budget,
16
15
  cli_help,
17
16
  harness,
18
17
  metal,
@@ -30,6 +29,7 @@ from localmodels.contracts import decode
30
29
  from localmodels.engines import CudaDriverError
31
30
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
32
31
  from localmodels.plan_envelope import PlanError
32
+ from localmodels.planning import budget
33
33
  from localmodels.probe import HostFacts, Services
34
34
  from localmodels.runtime_cli import inspect_runtimes
35
35
  from localmodels.setup_inspection_harness import Reason as Reason
@@ -7,7 +7,6 @@ from collections.abc import Callable
7
7
  from typing import TypedDict
8
8
 
9
9
  from localmodels import (
10
- budget,
11
10
  deploy,
12
11
  harness,
13
12
  metal,
@@ -21,6 +20,7 @@ from localmodels import (
21
20
  from localmodels.contracts import decode
22
21
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
23
22
  from localmodels.plan_envelope import PlanError
23
+ from localmodels.planning import budget
24
24
  from localmodels.probe import HostFacts
25
25
  from localmodels.setup_text import Lang, text
26
26
  from localmodels.stack_plan import RAM_FLOOR, StackOptions, StackPlan, deployments, platform_error