@simplexai/localmodels-linux-x64 0.1.0-dev.35 → 0.1.0-dev.37

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 (126) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +124 -102
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_config.py +188 -0
  7. package/modules/localmodels/budget.py +15 -2
  8. package/modules/localmodels/catalog.json +235 -2
  9. package/modules/localmodels/catalog.py +51 -320
  10. package/modules/localmodels/catalog_add.py +2 -8
  11. package/modules/localmodels/catalog_recipes.py +321 -0
  12. package/modules/localmodels/cli_parser.py +4 -1
  13. package/modules/localmodels/console.py +5 -4
  14. package/modules/localmodels/contracts.py +13 -3
  15. package/modules/localmodels/debug_cli.py +158 -0
  16. package/modules/localmodels/debug_mode.py +727 -0
  17. package/modules/localmodels/debug_stub_server.py +192 -0
  18. package/modules/localmodels/decode_calibration.json +1 -1
  19. package/modules/localmodels/decode_calibration.py +34 -17
  20. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  21. package/modules/localmodels/gateway.py +21 -155
  22. package/modules/localmodels/gateway_accept.py +201 -0
  23. package/modules/localmodels/gateway_bifrost.py +19 -184
  24. package/modules/localmodels/gateway_cli.py +11 -4
  25. package/modules/localmodels/gateway_foundations.py +2 -4
  26. package/modules/localmodels/gateway_probe.py +0 -1
  27. package/modules/localmodels/gateway_server.py +2 -3
  28. package/modules/localmodels/gpu_specs.py +12 -0
  29. package/modules/localmodels/guard.py +2 -7
  30. package/modules/localmodels/harness.py +16 -129
  31. package/modules/localmodels/harness_cleanup.py +135 -0
  32. package/modules/localmodels/harness_gateway.py +16 -14
  33. package/modules/localmodels/harness_probe.py +12 -4
  34. package/modules/localmodels/hosts.py +25 -2
  35. package/modules/localmodels/http_local.py +59 -0
  36. package/modules/localmodels/install.py +23 -8
  37. package/modules/localmodels/library_gateway.py +9 -9
  38. package/modules/localmodels/library_jobs.py +76 -27
  39. package/modules/localmodels/library_serve.py +12 -1
  40. package/modules/localmodels/library_state.py +6 -1
  41. package/modules/localmodels/llm_rank.py +155 -7
  42. package/modules/localmodels/metal_probe.py +11 -7
  43. package/modules/localmodels/probe.py +108 -174
  44. package/modules/localmodels/process_identity.py +109 -154
  45. package/modules/localmodels/process_windows.py +86 -0
  46. package/modules/localmodels/recommend.py +32 -3
  47. package/modules/localmodels/recommend_cli.py +14 -6
  48. package/modules/localmodels/remote_ops.py +65 -0
  49. package/modules/localmodels/remote_ops_download.py +2 -2
  50. package/modules/localmodels/remote_ops_prepare.py +19 -0
  51. package/modules/localmodels/remote_ops_service.py +14 -2
  52. package/modules/localmodels/runtime_args.py +10 -3
  53. package/modules/localmodels/runtime_auth.py +5 -9
  54. package/modules/localmodels/runtime_cli.py +128 -129
  55. package/modules/localmodels/runtime_discovery.py +84 -0
  56. package/modules/localmodels/runtime_install.py +101 -0
  57. package/modules/localmodels/runtime_releases.py +302 -0
  58. package/modules/localmodels/service_stop.py +8 -108
  59. package/modules/localmodels/service_upgrade.py +394 -63
  60. package/modules/localmodels/services_cli.py +24 -14
  61. package/modules/localmodels/setup_inspection.py +97 -9
  62. package/modules/localmodels/setup_text.py +7 -0
  63. package/modules/localmodels/sizecalc.py +0 -1
  64. package/modules/localmodels/stack.py +14 -221
  65. package/modules/localmodels/stack_arena.py +732 -0
  66. package/modules/localmodels/stack_args.py +15 -9
  67. package/modules/localmodels/stack_auto.py +384 -3
  68. package/modules/localmodels/stack_aux_gpu.py +4 -3
  69. package/modules/localmodels/stack_capacity.py +138 -0
  70. package/modules/localmodels/stack_cleanup.py +9 -4
  71. package/modules/localmodels/stack_cli.py +286 -0
  72. package/modules/localmodels/stack_compose.py +76 -32
  73. package/modules/localmodels/stack_console.py +9 -6
  74. package/modules/localmodels/stack_hardware.py +96 -270
  75. package/modules/localmodels/stack_hardware_text.py +263 -0
  76. package/modules/localmodels/stack_journal.py +3 -9
  77. package/modules/localmodels/stack_ledger.py +48 -18
  78. package/modules/localmodels/stack_lifecycle.py +33 -312
  79. package/modules/localmodels/stack_mcp.py +729 -0
  80. package/modules/localmodels/stack_memory.py +0 -2
  81. package/modules/localmodels/stack_picks.py +73 -18
  82. package/modules/localmodels/stack_plan.py +23 -5
  83. package/modules/localmodels/stack_preflight.py +11 -19
  84. package/modules/localmodels/stack_remove.py +373 -0
  85. package/modules/localmodels/stack_route.py +101 -17
  86. package/modules/localmodels/stack_suite.py +16 -10
  87. package/modules/localmodels/stack_summary.py +14 -0
  88. package/modules/localmodels/stack_try.py +238 -24
  89. package/modules/localmodels/stack_try_client.py +53 -15
  90. package/modules/localmodels/stack_try_docs.py +2 -2
  91. package/modules/localmodels/stack_view.py +24 -171
  92. package/modules/localmodels/stack_view_access.py +114 -1
  93. package/modules/localmodels/stack_view_agent.py +3 -13
  94. package/modules/localmodels/stack_view_hub.py +9 -10
  95. package/modules/localmodels/stack_view_llm.py +1 -1
  96. package/modules/localmodels/stack_view_sandbox.py +2 -2
  97. package/modules/localmodels/stack_view_schema.py +183 -0
  98. package/modules/localmodels/stack_view_serve.py +7 -1
  99. package/modules/localmodels/stack_view_service.py +1 -2
  100. package/modules/localmodels/stack_view_text.py +13 -9
  101. package/modules/localmodels/stack_warm.py +3 -0
  102. package/modules/localmodels/stack_warm_store.py +517 -0
  103. package/modules/localmodels/tui.py +28 -4
  104. package/modules/localmodels/tui_dialogs.py +136 -0
  105. package/modules/localmodels/tui_modals.py +279 -0
  106. package/modules/localmodels/tui_screen.py +113 -154
  107. package/modules/localmodels/tui_views.py +134 -203
  108. package/modules/localmodels/web/index.html +510 -101
  109. package/modules/localmodels/web/sizecalc/app.js +363 -10
  110. package/modules/localmodels/web/sizecalc/page.html +27 -3
  111. package/modules/localmodels/web/view/fleet.html +11 -2
  112. package/modules/localmodels/web/view/fleet.js +191 -17
  113. package/modules/localmodels/web/view/i18n.js +3 -2
  114. package/modules/localmodels/web/view/index.html +1 -1
  115. package/modules/localmodels/web/view/nav.js +22 -3
  116. package/modules/localmodels/web/view/view.css +63 -18
  117. package/modules/localmodels/web/view/view.js +169 -32
  118. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  119. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +120 -98
  120. package/package.json +1 -1
  121. package/tool.json +1 -1
  122. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  123. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  124. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  125. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -35,7 +35,7 @@ from localmodels.library_model import (
35
35
  progress,
36
36
  )
37
37
  from localmodels.library_pricing import Model
38
- from localmodels.library_state import JobHandle, Record
38
+ from localmodels.library_state import Job, JobHandle, Record
39
39
  from localmodels.probe import HostFacts
40
40
  from localmodels.records import Plan
41
41
  from localmodels.transport import Executor
@@ -50,8 +50,15 @@ def executor() -> Executor:
50
50
 
51
51
 
52
52
  def cancel_on_sigterm() -> None:
53
- """A cancel's SIGTERM ends this job like Ctrl+C, so its cleanup runs."""
54
- signal.signal(signal.SIGTERM, signal.default_int_handler)
53
+ """A cancel's SIGTERM ends this job like Ctrl+C, so its cleanup runs. Only the first one:
54
+ a second cancel of the same job signals it again, and that SIGTERM must not cut short the
55
+ cleanup the first started (cancel escalates to SIGKILL if the job never ends)."""
56
+
57
+ def once(_signum: int, _frame: object) -> None:
58
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
59
+ raise KeyboardInterrupt
60
+
61
+ signal.signal(signal.SIGTERM, once)
55
62
 
56
63
 
57
64
  def dests(plan: Plan) -> list[str]:
@@ -219,6 +226,55 @@ def _refuse_download(lib: library_status.Library, model: Model) -> library_prici
219
226
  return priced
220
227
 
221
228
 
229
+ def leftovers(job: Job) -> list[str]:
230
+ """Every file a download wrote or relied on: what it claimed, and what it waited for while
231
+ another download fetched it. A cancelled download deletes all of them that nothing else
232
+ needs (``in_use``); deleting only its claims would leave a shared file another cancelled
233
+ download kept for it with no owner at all."""
234
+ return list(dict.fromkeys([*job["files"], *job.get("needs", [])]))
235
+
236
+
237
+ def _give_up(model: str, job: Job, handle: JobHandle) -> None:
238
+ """Under ``locked()``: a cancelled download deletes its files, unless something else needs
239
+ them now, and ends its job in the same step. A job left behind would still claim the files
240
+ it kept, so a remove of a model that shares them would keep them too, for nobody."""
241
+ delete_weights(leftovers(handle.job), in_use(model))
242
+ if library_state.current(job):
243
+ library_state.clear_job(model)
244
+
245
+
246
+ def _fetch_and_commit(
247
+ model: Model,
248
+ plan: Plan,
249
+ handle: JobHandle,
250
+ pool: str,
251
+ memory: int,
252
+ base_dir: str,
253
+ mine: list[str],
254
+ files: list[str],
255
+ ) -> None:
256
+ """Fetch the files this job claimed, wait for the ones another download claimed, then
257
+ record the model as this job, unless a cancel marked it."""
258
+ job = handle.job
259
+ fetch(model.id, plan, handle, executor(), set(mine))
260
+ _shared(model.id, plan, handle, executor(), [f for f in files if f not in mine])
261
+ selector = library_gateway.pi_model(model.id, str(plan["endpoint"]["model"]))
262
+ record: Record = library_state.new_record(
263
+ model.id, model.entry.id, model.variant.quant, pool, plan, selector
264
+ )
265
+ record["memory_bytes"] = memory
266
+ record["base_dir"] = base_dir
267
+ with library_state.locked(): # commit only as this job, and only if not cancelled
268
+ found = library_state.read_job(model.id)
269
+ if found is None or found.get("id") != job["id"] or library_state.cancelled(job):
270
+ _give_up(model.id, job, handle)
271
+ raise LibraryError("CANCELLED", "the download was cancelled")
272
+ # The record and the end of this download are one step: from here the files are
273
+ # the record's, and no download job is left for a cancel to act on.
274
+ library_state.save(record)
275
+ library_state.clear_job(model.id)
276
+
277
+
222
278
  def download(
223
279
  model_id: str,
224
280
  base_dir: str,
@@ -247,27 +303,14 @@ def download(
247
303
  with library_state.held([job]):
248
304
  handle = library_state.JobHandle(job)
249
305
  try:
250
- fetch(model.id, plan, handle, executor(), set(mine))
251
- _shared(model.id, plan, handle, executor(), [f for f in files if f not in mine])
252
- except KeyboardInterrupt: # what it claimed, unless something else needs it now
306
+ _fetch_and_commit(model, plan, handle, priced.pool, memory, base_dir, mine, files)
307
+ except KeyboardInterrupt: # anywhere before the commit (a cancel's SIGTERM may land
308
+ # after the transfer, while waiting to commit): what it claimed, unless the record
309
+ # took the files or something else needs them now
253
310
  with library_state.locked():
254
- delete_weights(handle.job["files"], in_use(model.id))
311
+ if library_state.load(model.id) is None:
312
+ _give_up(model.id, job, handle)
255
313
  raise LibraryError("CANCELLED", "the download was cancelled") from None
256
- selector = library_gateway.pi_model(model.id, str(plan["endpoint"]["model"]))
257
- record: Record = library_state.new_record(
258
- model.id, model.entry.id, model.variant.quant, priced.pool, plan, selector
259
- )
260
- record["memory_bytes"] = memory
261
- record["base_dir"] = base_dir
262
- with library_state.locked(): # commit only as this job, and only if not cancelled
263
- found = library_state.read_job(model.id)
264
- if found is None or found.get("id") != job["id"] or library_state.cancelled(job):
265
- delete_weights(handle.job["files"], in_use(model.id))
266
- raise LibraryError("CANCELLED", "the download was cancelled")
267
- # The record and the end of this download are one step: from here the files are
268
- # the record's, and no download job is left for a cancel to act on.
269
- library_state.save(record)
270
- library_state.clear_job(model.id)
271
314
  if not autoload:
272
315
  return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
273
316
  try:
@@ -275,10 +318,16 @@ def download(
275
318
  except LibraryError as exc:
276
319
  if exc.code != "LOAD_NO_ROOM":
277
320
  raise
278
- record_ = library_state.load(model.id)
279
- if record_ is not None:
280
- record_["note"] = {"code": NO_ROOM_TO_LOAD}
281
- library_state.save(record_)
321
+ with library_state.locked(): # a load or remove admitted since then owns the record now:
322
+ # this note must never put a record it changed back (loaded to idle, removed to present)
323
+ record_ = library_state.load(model.id)
324
+ if (
325
+ record_ is not None
326
+ and record_["state"] == "idle"
327
+ and library_state.read_job(model.id) is None
328
+ ):
329
+ record_["note"] = {"code": NO_ROOM_TO_LOAD}
330
+ library_state.save(record_)
282
331
  return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
283
332
 
284
333
 
@@ -305,7 +354,7 @@ def cancel(model_id: str, base_dir: str) -> Row:
305
354
  with library_state.locked(): # it ended without cleaning up after itself (killed)
306
355
  committed = library_state.load(model.id) is not None
307
356
  if library_state.current(job) and not library_state.job_alive(model.id) and not committed:
308
- delete_weights(job["files"], in_use(model.id))
357
+ delete_weights(leftovers(job), in_use(model.id))
309
358
  library_state.clear_job(model.id)
310
359
  return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
311
360
 
@@ -147,9 +147,20 @@ def _fail(record: Record, error: LibraryError) -> LibraryError:
147
147
 
148
148
  def stop(record: Record, run: Executor) -> None:
149
149
  """Unregister, then stop and remove the model's server; its weights stay. Either failing
150
- raises with the record unchanged, so the next unload or remove tries both again."""
150
+ raises, so the next unload or remove tries again. Once unregistered the record says so
151
+ before the server stops: a process killed in between leaves a failed model with no
152
+ registration, which status shows and the next load registers again, never a loaded one
153
+ the gateway and pi no longer route to."""
151
154
  if registration := record.get("registration"):
152
155
  library_gateway.unregister(registration)
156
+ record.pop("registration")
157
+ if record["state"] == "loaded":
158
+ record["state"] = "failed"
159
+ record["error"] = {
160
+ "code": "ENGINE_START_FAILED",
161
+ "detail": "stopping the model server did not finish; unload or load it again",
162
+ }
163
+ library_state.save(record)
153
164
  if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
154
165
  _remove_service(record["plan"], run)
155
166
  record["state"] = "idle"
@@ -251,7 +251,10 @@ class JobHandle:
251
251
 
252
252
  def refuse_busy(model: str, kind: str) -> None:
253
253
  """Under ``locked()``: refuse when a live process holds ``model``; clear a job whose
254
- process ended (killed, or the machine restarted) so it cannot outlive this operation."""
254
+ process ended (killed, or the machine restarted) so it cannot outlive this operation.
255
+ A download that ended before it recorded the model is kept for anything but a new
256
+ download: its partial files are only reachable through it (status shows it failed, and
257
+ cancel deletes them, or a download resumes them)."""
255
258
  job = read_job(model)
256
259
  if job is None:
257
260
  return
@@ -259,6 +262,8 @@ def refuse_busy(model: str, kind: str) -> None:
259
262
  if job["kind"] == "download" and kind != "download":
260
263
  raise LibraryError("INVALID_STATE", f"{model} is downloading; cancel it first")
261
264
  raise LibraryError("JOB_RUNNING", f"{model} has a running {job['kind']}")
265
+ if job["kind"] == "download" and kind != "download" and load(model) is None:
266
+ return
262
267
  clear_job(model)
263
268
 
264
269
 
@@ -12,19 +12,22 @@ from __future__ import annotations
12
12
 
13
13
  from collections.abc import Iterable, Mapping
14
14
 
15
- from localmodels import metal
15
+ from localmodels import metal, vision
16
+ from localmodels.budget import HARNESS_RAM, RAM_FLOOR, host_ram
16
17
  from localmodels.catalog import (
17
18
  PLEASANT_FLOOR_TOK_S,
18
19
  CatalogEntry,
20
+ DecisionRecipe,
19
21
  QuantVariant,
20
22
  VariantChoice,
23
+ decision_components,
21
24
  hardware_key,
22
25
  predicted_decode_tok_s,
23
26
  select_variant,
24
27
  validated_here,
25
28
  )
26
29
  from localmodels.context_policy import AGENT, AgentPosture
27
- from localmodels.estimator import HardwareBudget, PhysicsRefusal
30
+ from localmodels.estimator import HardwareBudget, PhysicsRefusal, llama_host_bytes
28
31
  from localmodels.probe import HostFacts
29
32
 
30
33
  # Installed SimplexAI scores closer than this are a tie (model-scoring.md; AIHOT: 3 points or more
@@ -32,6 +35,25 @@ from localmodels.probe import HostFacts
32
35
  TIE_BAND = 3
33
36
  # --prefer fast: the fastest fitting model whose score is within this many points of the best.
34
37
  FAST_QUALITY_BAND = 5
38
+ WINDOWS_FALLBACK_ID = "spark-x2.6-4b"
39
+ WINDOWS_FALLBACK_WARNING = (
40
+ "Spark-X2.6-4B Q8_0 is the Windows NVIDIA candidate product fallback when no "
41
+ "validated LLM fits; no SimplexAI score. Catalog 72 is a vendor-reported editorial "
42
+ "anchor, not an installed score; physical 8/12 GB full product acceptance pending"
43
+ )
44
+
45
+
46
+ def windows_fallback(entry: CatalogEntry, facts: HostFacts) -> bool:
47
+ """The one candidate admitted by the native Windows NVIDIA fallback policy."""
48
+ return (
49
+ facts["platform"] == "win32"
50
+ and facts.get("arch") in (None, "", "x64")
51
+ and any(g["vendor"] == "nvidia" for g in facts.get("gpus") or [])
52
+ and entry.id == WINDOWS_FALLBACK_ID
53
+ and entry.status == "candidate"
54
+ and entry.runtime == "llama.cpp"
55
+ and entry.variants[-1].quant == "Q8_0"
56
+ )
35
57
 
36
58
 
37
59
  def strata_bar(llama_score: int, options: Mapping[str, object]) -> int:
@@ -76,9 +98,11 @@ def listed_default(facts: HostFacts, fits: list[tuple[str, int]]) -> str | None:
76
98
 
77
99
 
78
100
  def automatic_here(entry: CatalogEntry, facts: HostFacts) -> bool:
79
- """Validated entries, plus the one explicitly selected small-Mac candidate."""
80
- return (entry.status != "deprecated" and entry.id == mac_default(facts)) or validated_here(
81
- entry, facts["platform"]
101
+ """Validated entries and the scoped Mac default / Windows fallback candidates."""
102
+ return (
103
+ (entry.status != "deprecated" and entry.id == mac_default(facts))
104
+ or windows_fallback(entry, facts)
105
+ or validated_here(entry, facts["platform"])
82
106
  )
83
107
 
84
108
 
@@ -107,6 +131,123 @@ def agent_ready(
107
131
  )
108
132
 
109
133
 
134
+ DECISION_HOST_RAM = 2 << 30 # GPU decision llama-server host memory (stack_decision.py)
135
+ DECISION_FRONT_CGROUP_RAM = 1 << 30 # FRONT_LIMITS MemoryMax on Linux cgroups
136
+ _DECISION_VRAM_MARGIN = 256 << 20
137
+ _DECISION_FLOOR_BYTES = 1 << 30
138
+ _DECISION_CEILING_BYTES = 12 << 30
139
+ _DECISION_NEAR_INDEX = 2.0
140
+
141
+
142
+ def _picked_decision_recipe(
143
+ pool: list[DecisionRecipe],
144
+ facts: HostFacts,
145
+ options: Mapping[str, object],
146
+ card_total_bytes: int,
147
+ ) -> DecisionRecipe | None:
148
+ forced = int(str(options.get("decision_vram_gib") or 0))
149
+ if forced > 0:
150
+ budget_bytes = forced << 30
151
+ else:
152
+ largest = max(
153
+ (g["total_bytes"] for g in facts.get("gpus") or [] if g["vendor"] == "nvidia"),
154
+ default=0,
155
+ )
156
+ total = card_total_bytes if card_total_bytes > 0 and largest > 0 else largest
157
+ if total < 6 << 30:
158
+ return None
159
+ budget_bytes = max(_DECISION_FLOOR_BYTES, min(_DECISION_CEILING_BYTES, total // 2))
160
+ fitting = sorted(
161
+ (
162
+ (r, t)
163
+ for r in pool
164
+ for t in r["tiers"]
165
+ if t["vram_bytes"] + _DECISION_VRAM_MARGIN <= budget_bytes
166
+ ),
167
+ key=lambda rt: (rt[1]["index"], rt[1]["context"]),
168
+ reverse=True,
169
+ )
170
+ if not fitting:
171
+ return None
172
+ best = fitting[0][1]["index"]
173
+ near = [(r, t) for r, t in fitting if t["index"] >= best - _DECISION_NEAR_INDEX]
174
+ picked, _ = min(
175
+ near,
176
+ key=lambda rt: (rt[1]["vram_bytes"] + _DECISION_VRAM_MARGIN, -rt[1]["index"]),
177
+ )
178
+ return picked
179
+
180
+
181
+ def _decision_ram(
182
+ facts: HostFacts, options: Mapping[str, object], card_total_bytes: int = 0
183
+ ) -> int:
184
+ """Minimum host RAM a requested GPU decision component adds beside a discrete LLM."""
185
+ requested = str(options.get("decision") or "none")
186
+ if requested == "none" or options.get("defer_services"):
187
+ return 0
188
+ recipes = decision_components()
189
+ pool = recipes if requested == "auto" else [r for r in recipes if r["id"] == requested]
190
+ if not pool:
191
+ return DECISION_HOST_RAM
192
+ recipe = _picked_decision_recipe(pool, facts, options, card_total_bytes)
193
+ if recipe is None:
194
+ return 0
195
+ front = recipe.get("frontend")
196
+ if front is None:
197
+ return DECISION_HOST_RAM
198
+ front_ram = (
199
+ int(front["memory_estimate_bytes"])
200
+ if facts["platform"] == "win32"
201
+ else DECISION_FRONT_CGROUP_RAM
202
+ )
203
+ return DECISION_HOST_RAM + front_ram
204
+
205
+
206
+ def automatic_fit(
207
+ entry: CatalogEntry,
208
+ facts: HostFacts,
209
+ budget: HardwareBudget,
210
+ posture: AgentPosture,
211
+ options: Mapping[str, object],
212
+ *,
213
+ reclaimed_ram: int = 0,
214
+ decision_ram: int | None = None,
215
+ ) -> bool:
216
+ """The agent gate, plus discrete host RAM for the LLM, base stack and requested decision."""
217
+ if entry.runtime != "llama.cpp":
218
+ return False
219
+ variant = entry.variants[-1]
220
+ decision = entry.launch_plan(variant, budget, agent=posture).decision
221
+ if isinstance(decision, PhysicsRefusal):
222
+ return False
223
+ if budget.uma:
224
+ return True
225
+ cache_floor = (posture.prompt_cache_min_mib << 20) if posture.prompt_cache_mib > 0 else 0
226
+ projector_ram = 0
227
+ if entry.mmproj is not None and vision.llama_reader_enabled(entry.mmproj, posture.vision):
228
+ mode = (
229
+ decision.vision_reader
230
+ if decision.vision_reader != "off"
231
+ else vision.reader(posture.vision, budget.total_device_bytes, unified=budget.uma)
232
+ )
233
+ if mode == "cpu":
234
+ projector_ram = entry.mmproj.size_bytes
235
+ decision_bytes = (
236
+ _decision_ram(facts, options, budget.total_device_bytes)
237
+ if decision_ram is None
238
+ else decision_ram
239
+ )
240
+ needed = (
241
+ llama_host_bytes(entry.profile(variant), slots=posture.slots, kv_types=decision.kv_types)
242
+ + projector_ram
243
+ + cache_floor
244
+ + HARNESS_RAM
245
+ + RAM_FLOOR
246
+ + decision_bytes
247
+ )
248
+ return needed <= host_ram(facts, reclaimed_bytes=reclaimed_ram)[1]
249
+
250
+
110
251
  def rank_key(
111
252
  entry: CatalogEntry, variant: QuantVariant, budget: HardwareBudget, *, backend: str = "auto"
112
253
  ) -> tuple[int, float]:
@@ -118,13 +259,20 @@ def rank_key(
118
259
 
119
260
 
120
261
  def choose(
121
- ranked: list[tuple[tuple[int, float], str, int]], prefer: str, default: str | None = None
262
+ ranked: list[tuple[tuple[int, float], str, int]],
263
+ prefer: str,
264
+ default: str | None = None,
265
+ *,
266
+ fallback_ids: Iterable[str] = (),
122
267
  ) -> tuple[str, int]:
123
268
  """(entry id, card index) out of ``(rank_key, id, card)`` triples for one scenario: fastest
124
269
  takes the highest decode speed whatever the score (the score breaks ties); otherwise the
125
270
  small-Mac ``default`` when it fits and keeps_default holds for the others; else smartest and
126
271
  concurrent take the best score (speed breaks ties); fast takes the fastest whose score is
127
- within FAST_QUALITY_BAND of the best."""
272
+ within FAST_QUALITY_BAND of the best. Scoped ``fallback_ids`` are considered only when
273
+ no primary fits on any eligible card."""
274
+ fallback = set(fallback_ids)
275
+ ranked = [row for row in ranked if row[1] not in fallback] or ranked
128
276
  if prefer == "fastest":
129
277
  _, entry_id, index = max(ranked, key=lambda t: (t[0][1], t[0][0]))
130
278
  return entry_id, index
@@ -25,14 +25,18 @@ METAL = "/System/Library/Frameworks/Metal.framework/Metal"
25
25
 
26
26
 
27
27
  def available_memory(total_text: str, vm_stat: str) -> tuple[int, int]:
28
- """Conservative available RAM: purgeable/speculative counters can overlap these pages."""
29
- page = re.search(r"page size of (\d+)", vm_stat)
30
- free = re.search(r"Pages free:\s+(\d+)\.", vm_stat)
31
- inactive = re.search(r"Pages inactive:\s+(\d+)\.", vm_stat)
32
- if not page or not free or not inactive:
28
+ """Available RAM from vm_stat's disjoint free, inactive and speculative page counts."""
29
+ page = re.search(r"page size of (\d+) bytes\)", vm_stat)
30
+ free = re.search(r"^Pages free:[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE)
31
+ inactive = re.search(r"^Pages inactive:[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE)
32
+ speculative = re.search(r"^Pages speculative:[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE)
33
+ if not page or not free or not inactive or not speculative:
33
34
  raise OSError("RAM measurement unavailable")
34
- total = int(total_text.strip())
35
- available = (int(free[1]) + int(inactive[1])) * int(page[1])
35
+ try:
36
+ total = int(total_text.strip())
37
+ except ValueError:
38
+ raise OSError("RAM measurement unavailable") from None
39
+ available = (int(free[1]) + int(inactive[1]) + int(speculative[1])) * int(page[1])
36
40
  if total <= 0 or int(page[1]) <= 0 or available > total:
37
41
  raise OSError("RAM measurement unavailable")
38
42
  return total, available