@simplexai/localmodels-win32-x64 0.1.0-dev.64 → 0.1.0-dev.66

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 (127) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +125 -121
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/approval.py +5 -3
  6. package/modules/localmodels/auth_proxy.py +34 -2
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +504 -18
  9. package/modules/localmodels/catalog.py +2 -1
  10. package/modules/localmodels/catalog_recipes.py +3 -0
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +1 -1
  13. package/modules/localmodels/custom_hub.py +54 -6
  14. package/modules/localmodels/custom_probe.py +33 -5
  15. package/modules/localmodels/debug_stub_server.py +34 -1
  16. package/modules/localmodels/deploy.py +45 -285
  17. package/modules/localmodels/deployment_lifecycle.py +167 -0
  18. package/modules/localmodels/download-mirrors.json +43 -3
  19. package/modules/localmodels/draft_spec.py +43 -1
  20. package/modules/localmodels/engine_adapters/__init__.py +4 -2
  21. package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
  22. package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
  23. package/modules/localmodels/engines-b11583.json +9 -5
  24. package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
  25. package/modules/localmodels/engines.json +9 -5
  26. package/modules/localmodels/gateway.py +124 -13
  27. package/modules/localmodels/gateway_accept.py +1 -6
  28. package/modules/localmodels/gateway_cli.py +13 -24
  29. package/modules/localmodels/gateway_ops.py +185 -0
  30. package/modules/localmodels/gateway_server.py +3 -2
  31. package/modules/localmodels/harness.py +13 -16
  32. package/modules/localmodels/harness_core.py +4 -9
  33. package/modules/localmodels/harness_gateway.py +18 -6
  34. package/modules/localmodels/harness_probe.py +64 -3
  35. package/modules/localmodels/hosts.py +22 -34
  36. package/modules/localmodels/library_convert.py +3 -3
  37. package/modules/localmodels/library_custom.py +15 -13
  38. package/modules/localmodels/library_elastic.py +27 -13
  39. package/modules/localmodels/library_jobs.py +151 -28
  40. package/modules/localmodels/library_model.py +22 -2
  41. package/modules/localmodels/library_order.py +5 -4
  42. package/modules/localmodels/library_poly.py +2 -2
  43. package/modules/localmodels/library_pricing.py +34 -318
  44. package/modules/localmodels/library_serve.py +20 -12
  45. package/modules/localmodels/library_smoke.py +8 -1
  46. package/modules/localmodels/library_state.py +12 -0
  47. package/modules/localmodels/library_status.py +26 -16
  48. package/modules/localmodels/llm_rank.py +1 -1
  49. package/modules/localmodels/magpie_legacy.py +160 -0
  50. package/modules/localmodels/magpie_setup.py +6 -1
  51. package/modules/localmodels/pi_profile.py +3 -7
  52. package/modules/localmodels/plan_envelope.py +1 -1
  53. package/modules/localmodels/{budget.py → planning/budget.py} +56 -33
  54. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/recommend.py +1 -1
  57. package/modules/localmodels/recommend_cli.py +3 -4
  58. package/modules/localmodels/remote_ops_mirrors.py +55 -19
  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 +4 -4
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +29 -2
  64. package/modules/localmodels/setup_inspection_harness.py +5 -2
  65. package/modules/localmodels/setup_text.py +6 -0
  66. package/modules/localmodels/setup_upgrade.py +3 -12
  67. package/modules/localmodels/slot_cache.py +1 -3
  68. package/modules/localmodels/speech_admission.py +17 -5
  69. package/modules/localmodels/speech_catalog.py +5 -1
  70. package/modules/localmodels/speech_cli.py +5 -5
  71. package/modules/localmodels/speech_jobs.py +103 -20
  72. package/modules/localmodels/speech_model.py +2 -0
  73. package/modules/localmodels/speech_server.py +132 -9
  74. package/modules/localmodels/speech_state.py +11 -0
  75. package/modules/localmodels/speech_worker_sensevoice.py +215 -19
  76. package/modules/localmodels/speech_workers.py +79 -7
  77. package/modules/localmodels/stack.py +15 -6
  78. package/modules/localmodels/stack_auto.py +10 -4
  79. package/modules/localmodels/stack_aux_gpu.py +1 -1
  80. package/modules/localmodels/stack_binding.py +24 -143
  81. package/modules/localmodels/stack_capacity.py +4 -4
  82. package/modules/localmodels/stack_card.py +1 -1
  83. package/modules/localmodels/stack_cleanup.py +3 -3
  84. package/modules/localmodels/stack_cli.py +3 -0
  85. package/modules/localmodels/stack_client_settings.py +9 -2
  86. package/modules/localmodels/stack_compose.py +42 -9
  87. package/modules/localmodels/stack_console.py +2 -2
  88. package/modules/localmodels/stack_debug.py +1 -1
  89. package/modules/localmodels/stack_decision.py +1 -1
  90. package/modules/localmodels/stack_doctor.py +10 -7
  91. package/modules/localmodels/stack_down.py +3 -3
  92. package/modules/localmodels/stack_gpu_memory.py +1 -1
  93. package/modules/localmodels/stack_hardware.py +3 -3
  94. package/modules/localmodels/stack_hardware_text.py +1 -1
  95. package/modules/localmodels/stack_lifecycle.py +7 -7
  96. package/modules/localmodels/stack_memory.py +1 -1
  97. package/modules/localmodels/stack_mlx.py +1 -1
  98. package/modules/localmodels/stack_plan.py +18 -13
  99. package/modules/localmodels/stack_ports.py +60 -29
  100. package/modules/localmodels/stack_preflight.py +4 -3
  101. package/modules/localmodels/stack_remove.py +13 -6
  102. package/modules/localmodels/stack_review.py +3 -5
  103. package/modules/localmodels/stack_rollback.py +1 -1
  104. package/modules/localmodels/stack_route.py +5 -4
  105. package/modules/localmodels/stack_suite.py +17 -4
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +8 -13
  108. package/modules/localmodels/stack_up.py +10 -9
  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_text.py +2 -6
  114. package/modules/localmodels/stack_view_tick.py +2 -2
  115. package/modules/localmodels/stack_view_words.py +5 -2
  116. package/modules/localmodels/stack_warm.py +1 -1
  117. package/modules/localmodels/suite.py +1 -1
  118. package/modules/localmodels/tui_views.py +11 -5
  119. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/METADATA +1 -1
  120. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/RECORD +122 -118
  121. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/NOTICE +3 -0
  122. package/package.json +1 -1
  123. package/tool.json +1 -1
  124. package/modules/localmodels/library_vram.py +0 -123
  125. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/WHEEL +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/entry_points.txt +0 -0
  127. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.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
@@ -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(
@@ -208,6 +208,35 @@ discard = remote_ops_common.discard
208
208
  clear_link = remote_ops_common.clear_link
209
209
 
210
210
 
211
+ def _lock_once(lock: object, *, block: bool = False) -> bool:
212
+ """Take the engines-root lock on an open lock file: one attempt, or (POSIX ``block``) wait
213
+ for it. Windows has no blocking form; its callers poll."""
214
+ try:
215
+ if os.name == "nt":
216
+ import msvcrt
217
+
218
+ lock.seek(0) # type: ignore[attr-defined]
219
+ msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
220
+ else:
221
+ import fcntl
222
+
223
+ flags = fcntl.LOCK_EX if block else fcntl.LOCK_EX | fcntl.LOCK_NB
224
+ fcntl.flock(lock, flags) # type: ignore[arg-type]
225
+ except OSError:
226
+ return False
227
+ return True
228
+
229
+
230
+ def _unlock(lock: object) -> None:
231
+ if os.name == "nt":
232
+ import msvcrt
233
+
234
+ with contextlib.suppress(OSError):
235
+ lock.seek(0) # type: ignore[attr-defined]
236
+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
237
+ # POSIX: closing the file releases the flock.
238
+
239
+
211
240
  @contextlib.contextmanager
212
241
  def engine_lock(directory: str) -> Iterator[None]:
213
242
  """Serialize concurrent engine fetches and unpacks under the same engines root so parallel
@@ -216,27 +245,34 @@ def engine_lock(directory: str) -> Iterator[None]:
216
245
  os.makedirs(parent, exist_ok=True)
217
246
  lock_path = os.path.join(parent, ".engine.lock")
218
247
  with open(lock_path, "a+") as lock:
219
- if os.name == "nt":
220
- import msvcrt
248
+ while not _lock_once(lock, block=True):
249
+ time.sleep(0.1)
250
+ try:
251
+ yield
252
+ finally:
253
+ _unlock(lock)
221
254
 
222
- lock.seek(0)
223
- while True:
224
- try:
225
- msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
226
- break
227
- except OSError:
228
- time.sleep(0.1)
229
- try:
230
- yield
231
- finally:
232
- with contextlib.suppress(OSError):
233
- lock.seek(0)
234
- msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
235
- else:
236
- import fcntl
237
255
 
238
- fcntl.flock(lock, fcntl.LOCK_EX)
239
- yield
256
+ @contextlib.contextmanager
257
+ def try_engine_lock(directory: str, wait_s: float = 0.0) -> Iterator[bool]:
258
+ """``engine_lock`` that gives up after ``wait_s``: yields whether it holds the lock. A
259
+ cleanup that must not touch another download's ``.archives/*.part`` uses it."""
260
+ parent = os.path.dirname(directory) or "."
261
+ if not os.path.isdir(parent):
262
+ yield False
263
+ return
264
+ lock_path = os.path.join(parent, ".engine.lock")
265
+ with open(lock_path, "a+") as lock:
266
+ deadline = time.monotonic() + max(0.0, wait_s)
267
+ held = _lock_once(lock)
268
+ while not held and time.monotonic() < deadline:
269
+ time.sleep(0.1)
270
+ held = _lock_once(lock)
271
+ try:
272
+ yield held
273
+ finally:
274
+ if held:
275
+ _unlock(lock)
240
276
 
241
277
 
242
278
  def npm_transfer(
@@ -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,
@@ -32,6 +31,7 @@ from localmodels import stack_lifecycle as lifecycle
32
31
  from localmodels.contracts import decode
33
32
  from localmodels.engine_adapters import suite_plan
34
33
  from localmodels.plan_envelope import PlanError, deployment
34
+ from localmodels.planning import budget
35
35
  from localmodels.probe import HostFacts, Services
36
36
  from localmodels.records import FinishedRecord, Plan
37
37
  from localmodels.service_jobs import (
@@ -75,7 +75,7 @@ def plan_component(
75
75
  options = {**stack.default_options(), "base_dir": str(root)}
76
76
  try:
77
77
  return decision.gpu_plans(facts, options, choice, card)
78
- except stack_ports.PortUnavailableError as exc:
78
+ except (stack_ports.PortUnavailableError, stack_ports.PortProbeError) as exc:
79
79
  raise WaitingForResourcesError("port") from exc
80
80
  raise WaitingForResourcesError("gpu")
81
81
  if role not in ("embedding", "reranker"):
@@ -85,7 +85,7 @@ def plan_component(
85
85
  port = stack_ports.default_port(
86
86
  facts, stack_ports.AUXILIARY_PORTS[role], stack_ports.loopback_listening
87
87
  )
88
- except PlanError as exc:
88
+ except (PlanError, stack_ports.PortProbeError) as exc:
89
89
  raise WaitingForResourcesError("port") from exc
90
90
  built = suite_plan.build_plan(
91
91
  "local",
@@ -394,7 +394,7 @@ class Deployment:
394
394
  offset=component.FRONT_OFFSET if template_front is not None else 0,
395
395
  reserved=(main["llm"]["service"]["port"],),
396
396
  )
397
- except PlanError as exc:
397
+ except (PlanError, stack_ports.PortProbeError) as exc:
398
398
  raise WaitingForResourcesError("port") from exc
399
399
  built, front = _decision_endpoint(template, template_front, port)
400
400
  else: