@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.36

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 (143) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +141 -99
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +7 -1
  11. package/modules/localmodels/catalog.json +286 -12
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  22. package/modules/localmodels/engines.json +57 -1
  23. package/modules/localmodels/engines.py +6 -2
  24. package/modules/localmodels/estimator.py +21 -7
  25. package/modules/localmodels/frontend.py +4 -4
  26. package/modules/localmodels/gateway.py +14 -4
  27. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  28. package/modules/localmodels/gateway_bifrost.py +70 -57
  29. package/modules/localmodels/gateway_probe.py +3 -4
  30. package/modules/localmodels/gguf.py +7 -0
  31. package/modules/localmodels/harness.py +24 -25
  32. package/modules/localmodels/harness_gateway.py +19 -10
  33. package/modules/localmodels/harness_probe.py +33 -6
  34. package/modules/localmodels/hosts.py +73 -9
  35. package/modules/localmodels/install.py +36 -6
  36. package/modules/localmodels/library_cli.py +179 -0
  37. package/modules/localmodels/library_convert.py +132 -0
  38. package/modules/localmodels/library_gateway.py +471 -0
  39. package/modules/localmodels/library_jobs.py +314 -0
  40. package/modules/localmodels/library_model.py +246 -0
  41. package/modules/localmodels/library_pricing.py +347 -0
  42. package/modules/localmodels/library_serve.py +348 -0
  43. package/modules/localmodels/library_state.py +373 -0
  44. package/modules/localmodels/library_status.py +349 -0
  45. package/modules/localmodels/llm_rank.py +77 -8
  46. package/modules/localmodels/memcalc.py +7 -30
  47. package/modules/localmodels/metal.py +26 -0
  48. package/modules/localmodels/metal_probe.py +11 -7
  49. package/modules/localmodels/plan_envelope.py +4 -1
  50. package/modules/localmodels/preparation.py +49 -0
  51. package/modules/localmodels/probe.py +8 -8
  52. package/modules/localmodels/process_identity.py +536 -9
  53. package/modules/localmodels/quant_formats.py +123 -0
  54. package/modules/localmodels/recommend.py +32 -3
  55. package/modules/localmodels/recommend_cli.py +8 -4
  56. package/modules/localmodels/records.py +1 -0
  57. package/modules/localmodels/remote_ops.py +104 -6
  58. package/modules/localmodels/remote_ops_download.py +17 -2
  59. package/modules/localmodels/remote_ops_prepare.py +425 -0
  60. package/modules/localmodels/remote_ops_remove.py +40 -7
  61. package/modules/localmodels/remote_ops_service.py +110 -8
  62. package/modules/localmodels/remote_ops_verify.py +15 -2
  63. package/modules/localmodels/runtime_auth.py +31 -1
  64. package/modules/localmodels/runtime_cli.py +3 -4
  65. package/modules/localmodels/runtime_io.py +50 -6
  66. package/modules/localmodels/service_autostart.py +45 -1
  67. package/modules/localmodels/service_control.py +13 -0
  68. package/modules/localmodels/service_deployment.py +12 -3
  69. package/modules/localmodels/service_jobs.py +33 -4
  70. package/modules/localmodels/service_probe.py +67 -13
  71. package/modules/localmodels/service_stop.py +152 -0
  72. package/modules/localmodels/service_worker.py +9 -1
  73. package/modules/localmodels/services_cli.py +50 -6
  74. package/modules/localmodels/setup_inspection.py +34 -25
  75. package/modules/localmodels/setup_text.py +118 -0
  76. package/modules/localmodels/sizecalc.py +625 -0
  77. package/modules/localmodels/sizecalc_cli.py +249 -0
  78. package/modules/localmodels/stack.py +69 -17
  79. package/modules/localmodels/stack_args.py +91 -19
  80. package/modules/localmodels/stack_auto.py +78 -0
  81. package/modules/localmodels/stack_binding.py +23 -35
  82. package/modules/localmodels/stack_card.py +195 -0
  83. package/modules/localmodels/stack_cleanup.py +379 -0
  84. package/modules/localmodels/stack_clients.py +4 -1
  85. package/modules/localmodels/stack_compose.py +173 -206
  86. package/modules/localmodels/stack_console.py +2 -0
  87. package/modules/localmodels/stack_decision.py +3 -2
  88. package/modules/localmodels/stack_down.py +189 -0
  89. package/modules/localmodels/stack_events.py +54 -0
  90. package/modules/localmodels/stack_hardware.py +30 -34
  91. package/modules/localmodels/stack_journal.py +29 -8
  92. package/modules/localmodels/stack_ledger.py +411 -0
  93. package/modules/localmodels/stack_lifecycle.py +162 -167
  94. package/modules/localmodels/stack_llm_ram.py +57 -5
  95. package/modules/localmodels/stack_memory.py +721 -0
  96. package/modules/localmodels/stack_picks.py +147 -0
  97. package/modules/localmodels/stack_plan.py +143 -25
  98. package/modules/localmodels/stack_ports.py +22 -0
  99. package/modules/localmodels/stack_preflight.py +699 -0
  100. package/modules/localmodels/stack_review.py +123 -5
  101. package/modules/localmodels/stack_rollback.py +2 -0
  102. package/modules/localmodels/stack_route.py +256 -0
  103. package/modules/localmodels/stack_run.py +11 -0
  104. package/modules/localmodels/stack_suite.py +107 -20
  105. package/modules/localmodels/stack_summary.py +65 -4
  106. package/modules/localmodels/stack_try.py +354 -0
  107. package/modules/localmodels/stack_try_client.py +194 -0
  108. package/modules/localmodels/stack_try_docs.py +139 -0
  109. package/modules/localmodels/stack_up.py +8 -1
  110. package/modules/localmodels/stack_update.py +29 -4
  111. package/modules/localmodels/stack_verify.py +3 -1
  112. package/modules/localmodels/stack_view.py +10 -11
  113. package/modules/localmodels/stack_view_apply.py +4 -2
  114. package/modules/localmodels/stack_view_events.py +2 -1
  115. package/modules/localmodels/stack_view_serve.py +3 -0
  116. package/modules/localmodels/stack_view_text.py +1 -1
  117. package/modules/localmodels/stack_view_words.py +4 -1
  118. package/modules/localmodels/stack_warm.py +574 -0
  119. package/modules/localmodels/stack_whatif.py +558 -0
  120. package/modules/localmodels/suite.py +48 -39
  121. package/modules/localmodels/tool_archive.py +40 -0
  122. package/modules/localmodels/tools.json +8 -0
  123. package/modules/localmodels/transport.py +1 -0
  124. package/modules/localmodels/vision.py +8 -1
  125. package/modules/localmodels/web/sizecalc/app.js +431 -0
  126. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  127. package/modules/localmodels/web/sizecalc/page.html +362 -0
  128. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  129. package/modules/localmodels/web/view/i18n.js +1 -1
  130. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  131. package/modules/localmodels/web/view/logo-codex.png +0 -0
  132. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  133. package/modules/localmodels/web/view/view.css +4 -0
  134. package/modules/localmodels/web/view/view.js +15 -6
  135. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/METADATA +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev36.dist-info/RECORD +242 -0
  137. package/package.json +1 -1
  138. package/tool.json +1 -1
  139. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/WHEEL +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/entry_points.txt +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/NOTICE +0 -0
  143. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,349 @@
1
+ """``library status``: one ``localmodels.library-status/v1`` document from fresh host facts, the
2
+ library's records and its jobs. Every byte figure is the planner's (library_pricing) or the
3
+ probe's; the web formats them and infers nothing."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import datetime as dt
8
+ import urllib.request
9
+ from dataclasses import dataclass, field
10
+
11
+ from localmodels import (
12
+ __version__,
13
+ hosts,
14
+ library_gateway,
15
+ library_pricing,
16
+ library_state,
17
+ plan_envelope,
18
+ suite,
19
+ vision,
20
+ )
21
+ from localmodels import catalog as cat
22
+ from localmodels.library_model import (
23
+ STATUS_SCHEMA,
24
+ Availability,
25
+ Holder,
26
+ Host,
27
+ Pool,
28
+ Problem,
29
+ Row,
30
+ Status,
31
+ )
32
+ from localmodels.library_pricing import Model, Priced
33
+ from localmodels.library_state import Job, Record
34
+ from localmodels.probe import HostFacts
35
+ from localmodels.records import Plan
36
+
37
+ ARCH = {
38
+ "x64": "x86_64",
39
+ "x86_64": "x86_64",
40
+ "amd64": "x86_64",
41
+ "arm64": "arm64",
42
+ "aarch64": "arm64",
43
+ }
44
+ HEALTH_TIMEOUT_S = 2.0
45
+
46
+
47
+ def platform_name(facts: HostFacts) -> str:
48
+ value = facts["platform"]
49
+ return "linux" if value.startswith("linux") else "windows" if value == "win32" else value
50
+
51
+
52
+ def answering(base_url: str) -> bool:
53
+ """llama-server's ``/health`` answers 200 without a key once the model is loaded."""
54
+ url = base_url.removesuffix("/").removesuffix("/v1") + "/health"
55
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
56
+ try:
57
+ with opener.open(url, timeout=HEALTH_TIMEOUT_S) as response:
58
+ return bool(response.status == 200)
59
+ except OSError:
60
+ return False
61
+
62
+
63
+ @dataclass
64
+ class Library:
65
+ """What status reads: facts, records and jobs, and the catalog."""
66
+
67
+ facts: HostFacts
68
+ base_dir: str
69
+ records: dict[str, Record]
70
+ jobs: dict[str, tuple[Job, bool]]
71
+ catalog: tuple[cat.CatalogEntry, ...]
72
+ priced: dict[str, Priced] = field(default_factory=dict)
73
+
74
+ @classmethod
75
+ def read(cls, facts: HostFacts, base_dir: str) -> Library:
76
+ return cls(
77
+ facts,
78
+ base_dir,
79
+ {r["id"]: r for r in library_state.records()},
80
+ library_state.jobs(),
81
+ library_pricing.entries(),
82
+ )
83
+
84
+ def healthy(self, base_url: str) -> bool:
85
+ return answering(base_url)
86
+
87
+ def reserved(self) -> dict[str, int]:
88
+ """Memory loading models hold before the probe can see it, per pool."""
89
+ found: dict[str, int] = {}
90
+ for job, alive in self.jobs.values():
91
+ if alive and job["kind"] == "load":
92
+ found[job["pool"]] = found.get(job["pool"], 0) + job["memory_bytes"]
93
+ return found
94
+
95
+ def models(self) -> list[Model]:
96
+ rows = library_pricing.shown(self.facts, self.catalog)
97
+ known = {m.id for m in rows}
98
+ for model_id in self.records:
99
+ if model_id not in known:
100
+ try:
101
+ rows.append(library_pricing.find(model_id, self.catalog))
102
+ except ValueError:
103
+ continue
104
+ return rows
105
+
106
+ def judge(self, model: Model) -> Priced:
107
+ if model.id not in self.priced:
108
+ self.priced[model.id] = library_pricing.judge(
109
+ self.facts, model, self.base_dir, self.catalog, self.reserved()
110
+ )
111
+ return self.priced[model.id]
112
+
113
+
114
+ def _state(lib: Library, model: str, record: Record | None) -> tuple[str, Problem | None]:
115
+ job, alive = lib.jobs.get(model, (None, False))
116
+ if job is not None and alive:
117
+ return ("downloading" if job["kind"] == "download" else "loading"), None
118
+ if job is not None: # its process ended without clearing it
119
+ code = "DOWNLOAD_FAILED" if job["kind"] == "download" else "ENGINE_START_FAILED"
120
+ return "failed", {"code": code, "detail": f"the {job['kind']} process ended early"}
121
+ if record is None:
122
+ return "absent", None
123
+ if record["state"] == "loaded":
124
+ if lib.healthy(str(record["plan"]["endpoint"]["base_url"])):
125
+ return "loaded", None
126
+ return "failed", {
127
+ "code": "HEALTH_CHECK_FAILED",
128
+ "detail": "the model server does not answer; load it again",
129
+ }
130
+ if record["state"] == "starting": # its load ended before the server was recorded
131
+ return "failed", {
132
+ "code": "ENGINE_START_FAILED",
133
+ "detail": "the load ended before its server was recorded; unload or load it again",
134
+ }
135
+ if record["state"] == "failed":
136
+ return "failed", record.get("error") or {"code": "ENGINE_START_FAILED", "detail": ""}
137
+ return "idle", None
138
+
139
+
140
+ def _plan_of(lib: Library, model: Model, record: Record | None, priced: Priced) -> Plan | None:
141
+ """The plan a row shows: its record's; for a model a live job is downloading, the price on
142
+ the pool that job recorded (status never moves a running download to another card)."""
143
+ if record is not None:
144
+ return record["plan"]
145
+ job, alive = lib.jobs.get(model.id, (None, False))
146
+ if job is not None and alive and job["pool"] != priced.pool:
147
+ try:
148
+ return library_pricing.price(
149
+ library_pricing.capacity(lib.facts), model, job["pool"], lib.base_dir, lib.catalog
150
+ )
151
+ except plan_envelope.PlanError:
152
+ return priced.plan
153
+ return priced.plan
154
+
155
+
156
+ def pi_model_of(model: Model, record: Record | None) -> str | None:
157
+ """The pi selector the model gets when loaded: the one its record fixed (every command
158
+ upgrades older records first), or for a download that has no record yet what the gateway
159
+ will register for it."""
160
+ if record is not None:
161
+ return record.get("pi_model")
162
+ return library_gateway.pi_model(model.id, model.variant.model_id)
163
+
164
+
165
+ def row(lib: Library, model: Model) -> Row:
166
+ record = lib.records.get(model.id)
167
+ priced = lib.judge(model)
168
+ state, problem = _state(lib, model.id, record)
169
+ plan = _plan_of(lib, model, record, priced)
170
+ job, alive = lib.jobs.get(model.id, (None, False))
171
+ memory = library_pricing.memory_bytes(plan) if plan is not None else 0
172
+ if record is None and job is not None and alive:
173
+ memory = job["memory_bytes"] or memory
174
+ if record is not None and record["state"] != "loaded" and record.get("memory_bytes"):
175
+ memory = record["memory_bytes"]
176
+ availability: Availability = {"downloadable": True}
177
+ if record is None:
178
+ reason = library_pricing.download_reason(
179
+ lib.facts, priced, library_pricing.base_free(lib.base_dir)
180
+ )
181
+ if reason is not None:
182
+ availability = {"downloadable": False, "reason": reason}
183
+ launch: dict[str, object] = dict(plan["launch"]) if plan is not None else {}
184
+ found: Row = {
185
+ "id": model.id,
186
+ "name": model.name,
187
+ "description": model.entry.description,
188
+ "quant": model.variant.quant,
189
+ "context_tokens": int(str(launch.get("window") or 0)),
190
+ "vision": vision.reads_pictures(launch),
191
+ "download_bytes": sum(f["size_bytes"] for f in plan["files"])
192
+ if plan is not None
193
+ else sum(f.size_bytes for f in model.variant.files),
194
+ "memory_bytes": memory,
195
+ "fit": priced.fit, # type: ignore[typeddict-item]
196
+ "recommended": False,
197
+ "availability": availability,
198
+ "pool": record["pool"]
199
+ if record is not None
200
+ else job["pool"]
201
+ if job is not None and alive
202
+ else priced.pool,
203
+ "state": state, # type: ignore[typeddict-item]
204
+ }
205
+ job, alive = lib.jobs.get(model.id, (None, False))
206
+ if state == "downloading" and job is not None and alive:
207
+ found["download"] = {
208
+ "step": "verify" if job["phase"] == "verify" else "download",
209
+ "done_bytes": job["done"],
210
+ "total_bytes": job["total"],
211
+ "bytes_per_second": job["bytes_per_second"],
212
+ }
213
+ if state != "absent":
214
+ if (selector := pi_model_of(model, record)) is not None:
215
+ found["pi_model"] = selector
216
+ if record is not None:
217
+ if state == "loaded" and (reg := record.get("registration")):
218
+ found["endpoint"] = {
219
+ "base_url": str(record["plan"]["endpoint"]["base_url"]),
220
+ "gateway_model": reg["model"],
221
+ }
222
+ if (speed := record.get("tokens_per_second")) is not None:
223
+ found["tokens_per_second"] = round(speed, 1)
224
+ if state == "idle" and (note := record.get("note")):
225
+ found["note"] = note
226
+ if state == "failed" and problem is not None:
227
+ found["error"] = problem
228
+ return found
229
+
230
+
231
+ def _component_bytes(plan: Plan, pool: str) -> int:
232
+ launch = plan.get("launch") or {}
233
+ if pool != "system":
234
+ return library_pricing.memory_bytes(plan)
235
+ try:
236
+ return suite.bounded_ram(plan)
237
+ except (KeyError, ValueError, IndexError):
238
+ return int(str(launch.get("memory_estimate_bytes") or 0))
239
+
240
+
241
+ def pools(lib: Library, rows: list[Row]) -> list[Pool]:
242
+ """Every pool with what holds it: loaded and loading library models, and the services this
243
+ tool runs that are not library models (foundation components)."""
244
+ holders: dict[str, list[Holder]] = {p: [] for p in library_pricing.pools(lib.facts)}
245
+ library_names = {r["plan"]["name"] for r in lib.records.values() if r["state"] != "idle"}
246
+ for row_ in rows:
247
+ if row_["state"] in ("loaded", "loading") and row_["pool"] in holders:
248
+ holders[row_["pool"]].append(
249
+ {
250
+ "kind": "model",
251
+ "id": row_["id"],
252
+ "name": row_["name"],
253
+ "bytes": row_["memory_bytes"],
254
+ }
255
+ )
256
+ for record in hosts.records(hosts.LOCAL_ID):
257
+ plan = record["plan"]
258
+ if plan["name"] in library_names or not record.get("ok"):
259
+ continue
260
+ pool = library_pricing.pool_of(plan)
261
+ if pool not in holders:
262
+ if pool.startswith("gpu:"):
263
+ continue # a card hidden from the library (CUDA_VISIBLE_DEVICES)
264
+ pool = "unified" if "unified" in holders else "system"
265
+ holders[pool].append(
266
+ {
267
+ "kind": "component",
268
+ "id": plan["name"],
269
+ "name": str(plan["model"].get("display_name") or plan["model"]["id"]),
270
+ "bytes": _component_bytes(plan, pool),
271
+ }
272
+ )
273
+ reserved = lib.reserved()
274
+ found: list[Pool] = []
275
+ for pool, held in holders.items():
276
+ total = library_pricing.pool_total(lib.facts, pool)
277
+ used = total - library_pricing.pool_free(lib.facts, pool) + reserved.get(pool, 0)
278
+ found.append(
279
+ {
280
+ "id": pool,
281
+ "total_bytes": total,
282
+ "used_bytes": min(total, max(0, used)),
283
+ "holders": held,
284
+ }
285
+ )
286
+ return found
287
+
288
+
289
+ def host(lib: Library) -> Host:
290
+ facts = lib.facts
291
+ shown = library_pricing.visible(facts) # the cards the pools may use
292
+ os_info = facts.get("os") or {}
293
+ os_label = str(
294
+ os_info.get("distro")
295
+ or " ".join(str(os_info.get(k) or "") for k in ("system", "release")).strip()
296
+ )
297
+ engine = next((p.plan["engine"] for p in lib.priced.values() if p.plan is not None), None)
298
+ backend = {"cuda": "CUDA", "metal": "Metal", "cpu": "CPU"}
299
+ engine_label = "llama.cpp"
300
+ if engine is not None:
301
+ engine_label = f"llama.cpp {engine.get('build') or ''}".strip()
302
+ if (kind := engine.get("backend")) in backend:
303
+ engine_label += f" · {backend[str(kind)]}"
304
+ return {
305
+ "platform": platform_name(facts),
306
+ "arch": ARCH.get(str(facts.get("arch")), str(facts.get("arch"))),
307
+ "os_label": os_label,
308
+ "engine_label": engine_label,
309
+ "ram_total_bytes": facts["ram"]["total_bytes"],
310
+ "disk_free_bytes": library_pricing.base_free(lib.base_dir),
311
+ "gpus": [
312
+ {
313
+ "index": g["index"],
314
+ "uuid": g["uuid"],
315
+ "name": g["name"],
316
+ "total_bytes": g["total_bytes"],
317
+ "free_bytes": g["free_bytes"],
318
+ }
319
+ for g in facts.get("gpus") or []
320
+ if g.get("vendor") == "nvidia" and (shown is None or g["index"] in shown)
321
+ ],
322
+ }
323
+
324
+
325
+ def build(lib: Library) -> Status:
326
+ models = lib.models()
327
+ rows = [row(lib, m) for m in models]
328
+ candidates = [
329
+ (m, r["pool"])
330
+ for m, r in zip(models, rows, strict=True)
331
+ if r["state"] == "absent" and r["availability"]["downloadable"]
332
+ ]
333
+ chosen = library_pricing.recommend(lib.facts, candidates)
334
+ for r in rows:
335
+ r["recommended"] = r["id"] == chosen
336
+ return {
337
+ "schema": STATUS_SCHEMA,
338
+ "tool_version": __version__,
339
+ "observed_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
340
+ "host": host(lib),
341
+ "pools": pools(lib, rows),
342
+ "models": rows,
343
+ }
344
+
345
+
346
+ def model_row(lib: Library, model_id: str) -> Row:
347
+ """One model's row, as status shows it (with the recommendation left out)."""
348
+ model = library_pricing.find(model_id, lib.catalog)
349
+ return row(lib, model)
@@ -10,21 +10,23 @@ stay in ``catalog``.
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
- from collections.abc import Iterable
13
+ from collections.abc import Iterable, Mapping
14
14
 
15
15
  from localmodels import metal
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,
19
20
  QuantVariant,
20
21
  VariantChoice,
22
+ components,
21
23
  hardware_key,
22
24
  predicted_decode_tok_s,
23
25
  select_variant,
24
26
  validated_here,
25
27
  )
26
28
  from localmodels.context_policy import AGENT, AgentPosture
27
- from localmodels.estimator import HardwareBudget, PhysicsRefusal
29
+ from localmodels.estimator import HardwareBudget, PhysicsRefusal, llama_host_bytes
28
30
  from localmodels.probe import HostFacts
29
31
 
30
32
  # Installed SimplexAI scores closer than this are a tie (model-scoring.md; AIHOT: 3 points or more
@@ -32,6 +34,35 @@ from localmodels.probe import HostFacts
32
34
  TIE_BAND = 3
33
35
  # --prefer fast: the fastest fitting model whose score is within this many points of the best.
34
36
  FAST_QUALITY_BAND = 5
37
+ WINDOWS_FALLBACK_ID = "spark-x2.6-4b"
38
+ WINDOWS_FALLBACK_WARNING = (
39
+ "Spark-X2.6-4B Q8_0 is the Windows NVIDIA candidate product fallback when no "
40
+ "validated LLM fits; no SimplexAI score. Catalog 72 is a vendor-reported editorial "
41
+ "anchor, not an installed score; physical 8/12 GB full product acceptance pending"
42
+ )
43
+
44
+
45
+ def windows_fallback(entry: CatalogEntry, facts: HostFacts) -> bool:
46
+ """The one candidate admitted by the native Windows NVIDIA fallback policy."""
47
+ return (
48
+ facts["platform"] == "win32"
49
+ and facts.get("arch") in (None, "", "x64")
50
+ and any(g["vendor"] == "nvidia" for g in facts.get("gpus") or [])
51
+ and entry.id == WINDOWS_FALLBACK_ID
52
+ and entry.status == "candidate"
53
+ and entry.runtime == "llama.cpp"
54
+ and entry.variants[-1].quant == "Q8_0"
55
+ )
56
+
57
+
58
+ def strata_bar(llama_score: int, options: Mapping[str, object]) -> int:
59
+ """The installed score a Strata recipe must reach to replace the llama.cpp pick: TIE_BAND
60
+ above it. Under ``--prefer fastest`` a llama.cpp model that fits always stands: Strata keeps
61
+ the experts in RAM, which buys intelligence, never speed."""
62
+ if options.get("prefer") == "fastest" and llama_score >= 0:
63
+ return 1 << 30
64
+ return llama_score + TIE_BAND
65
+
35
66
 
36
67
  PRODUCT_DEFAULTS = {
37
68
  ("win32", "cuda", "NVIDIA RTX Spark N1X"): "qwen3.8-27b",
@@ -66,9 +97,11 @@ def listed_default(facts: HostFacts, fits: list[tuple[str, int]]) -> str | None:
66
97
 
67
98
 
68
99
  def automatic_here(entry: CatalogEntry, facts: HostFacts) -> bool:
69
- """Validated entries, plus the one explicitly selected small-Mac candidate."""
70
- return (entry.status != "deprecated" and entry.id == mac_default(facts)) or validated_here(
71
- entry, facts["platform"]
100
+ """Validated entries and the scoped Mac default / Windows fallback candidates."""
101
+ return (
102
+ (entry.status != "deprecated" and entry.id == mac_default(facts))
103
+ or windows_fallback(entry, facts)
104
+ or validated_here(entry, facts["platform"])
72
105
  )
73
106
 
74
107
 
@@ -97,6 +130,31 @@ def agent_ready(
97
130
  )
98
131
 
99
132
 
133
+ def automatic_fit(
134
+ entry: CatalogEntry,
135
+ facts: HostFacts,
136
+ budget: HardwareBudget,
137
+ posture: AgentPosture,
138
+ options: Mapping[str, object],
139
+ ) -> bool:
140
+ """The agent gate, plus the Windows candidate's base-stack RAM and requested search."""
141
+ variant = entry.variants[-1]
142
+ if not windows_fallback(entry, facts):
143
+ return agent_ready(entry, variant, budget, posture)
144
+ decision = entry.launch_plan(variant, budget, agent=posture).decision
145
+ if isinstance(decision, PhysicsRefusal):
146
+ return False
147
+ needed = (
148
+ llama_host_bytes(entry.profile(variant), slots=posture.slots, kv_types=decision.kv_types)
149
+ + (min(posture.prompt_cache_mib, posture.prompt_cache_min_mib) << 20)
150
+ + HARNESS_RAM
151
+ + RAM_FLOOR
152
+ )
153
+ if options.get("search", True):
154
+ needed += sum(r["memory_estimate_bytes"] for r in components() if r["task"] == "search")
155
+ return needed <= host_ram(facts)[1]
156
+
157
+
100
158
  def rank_key(
101
159
  entry: CatalogEntry, variant: QuantVariant, budget: HardwareBudget, *, backend: str = "auto"
102
160
  ) -> tuple[int, float]:
@@ -108,12 +166,23 @@ def rank_key(
108
166
 
109
167
 
110
168
  def choose(
111
- ranked: list[tuple[tuple[int, float], str, int]], prefer: str, default: str | None = None
169
+ ranked: list[tuple[tuple[int, float], str, int]],
170
+ prefer: str,
171
+ default: str | None = None,
172
+ *,
173
+ fallback_ids: Iterable[str] = (),
112
174
  ) -> tuple[str, int]:
113
- """(entry id, card index) out of ``(rank_key, id, card)`` triples for one scenario: the
175
+ """(entry id, card index) out of ``(rank_key, id, card)`` triples for one scenario: fastest
176
+ takes the highest decode speed whatever the score (the score breaks ties); otherwise the
114
177
  small-Mac ``default`` when it fits and keeps_default holds for the others; else smartest and
115
178
  concurrent take the best score (speed breaks ties); fast takes the fastest whose score is
116
- within FAST_QUALITY_BAND of the best."""
179
+ within FAST_QUALITY_BAND of the best. Scoped ``fallback_ids`` are considered only when
180
+ no primary fits on any eligible card."""
181
+ fallback = set(fallback_ids)
182
+ ranked = [row for row in ranked if row[1] not in fallback] or ranked
183
+ if prefer == "fastest":
184
+ _, entry_id, index = max(ranked, key=lambda t: (t[0][1], t[0][0]))
185
+ return entry_id, index
117
186
  mine = [(entry_id, index) for _, entry_id, index in ranked if entry_id == default]
118
187
  if mine and keeps_default(key[0] for key, entry_id, _ in ranked if entry_id != default):
119
188
  return mine[0]
@@ -17,39 +17,15 @@ from collections.abc import Mapping, Sequence
17
17
  from dataclasses import dataclass, field, replace
18
18
  from typing import Any
19
19
 
20
- from localmodels import estimator
20
+ from localmodels import estimator, quant_formats
21
21
  from localmodels.estimator import LayerKind, ModelProfile
22
22
 
23
23
  SCHEMA = "localmodels.memcalc/v1"
24
24
  KIB, MIB, GIB = 1 << 10, 1 << 20, 1 << 30
25
25
  _F16 = 2
26
26
 
27
- # Average bits per weight of common builds, embeddings and norms included. GGUF k-quants keep
28
- # some tensors at higher precision, so these are typical file sizes over parameter count, not
29
- # the nominal bit width. MLX 4-bit stores an f16 scale and bias per 64 weights: 4 + 32/64.
30
- QUANT_BITS: dict[str, float] = {
31
- "F32": 32.0,
32
- "BF16": 16.0,
33
- "F16": 16.0,
34
- "FP8": 8.0,
35
- "Q8_0": 8.5,
36
- "MLX-8BIT": 8.5,
37
- "Q6_K": 6.56,
38
- "Q5_K_M": 5.69,
39
- "Q5_K_S": 5.54,
40
- "Q4_K_M": 4.85,
41
- "Q4_K_S": 4.58,
42
- "MLX-4BIT": 4.5,
43
- "IQ4_XS": 4.25,
44
- "MXFP4": 4.25,
45
- "Q4_0": 4.5,
46
- "Q3_K_M": 3.91,
47
- "IQ3_S": 3.44,
48
- "IQ3_XXS": 3.06,
49
- "Q2_K": 2.96,
50
- "IQ2_XS": 2.31,
51
- "IQ2_XXS": 2.06,
52
- }
27
+ # Average bits per weight of common builds (quant_formats: typical file size over parameters).
28
+ QUANT_BITS: dict[str, float] = quant_formats.QUANT_BITS
53
29
  KV_TYPES = ("f16", "q8_0", "q4_0")
54
30
  # HF model_type -> the GGUF architecture name the estimator's measured tables use.
55
31
  _GGUF_ARCH = {
@@ -338,6 +314,7 @@ def profile_from_config(
338
314
  ssm_d_state=dims.get("d_state", 0),
339
315
  ssm_d_conv=dims.get("d_conv", 0),
340
316
  ssm_n_group=dims.get("n_group", 0),
317
+ kv_k_only=bool(_int(cfg.get("kv_lora_rank"))), # MLA keeps the latent as K only
341
318
  )
342
319
  return profile, notes
343
320
 
@@ -373,12 +350,12 @@ def quant_bits(text: str) -> float:
373
350
  return float(text)
374
351
  except ValueError:
375
352
  pass
376
- key = text.strip().upper().replace("UD-", "")
377
- if key not in QUANT_BITS:
353
+ found = quant_formats.lookup(text)
354
+ if found is None:
378
355
  raise MemcalcError(
379
356
  f"unknown quant {text!r}; use bits per weight or one of {list(QUANT_BITS)}"
380
357
  )
381
- return QUANT_BITS[key]
358
+ return found.bits
382
359
 
383
360
 
384
361
  def parse_tokens(text: str) -> int:
@@ -252,6 +252,32 @@ def reclaimed(facts: HostFacts) -> HostFacts:
252
252
  return seen
253
253
 
254
254
 
255
+ def stable_ceiling(facts: HostFacts) -> int | None:
256
+ """A whole-GiB ``--unified-memory`` size whose priced room is at most the RAM free now.
257
+
258
+ A Mac plan without ``--unified-memory`` follows the live free memory, so another program's
259
+ allocation changes its prompt cache and ``stack apply`` then refuses the re-planned plan.
260
+ ``assume`` prices a Mac of ``C`` bytes at ``C - in_use(C)``. The largest whole GiB ``C``
261
+ below this Mac's memory whose room fits in the RAM free now pins the plan without pricing
262
+ memory this Mac does not have. None off Apple Silicon, below 1 GiB, or when the whole Mac's
263
+ reserved room already fits in what is free.
264
+ """
265
+ if not supported(facts):
266
+ return None
267
+ available = int(facts["ram"]["available_bytes"])
268
+ total = int(facts["ram"]["total_bytes"])
269
+ if total - in_use(total) <= available:
270
+ return None
271
+ size = total - (total % GIB)
272
+ if size == total:
273
+ size -= GIB
274
+ while size >= GIB:
275
+ if size - in_use(size) <= available:
276
+ return size
277
+ size -= GIB
278
+ return None
279
+
280
+
255
281
  def pressured(facts: HostFacts) -> tuple[HostFacts, list[str]]:
256
282
  """``facts`` with WARN_KEEP_FRACTION of the RAM available held back under warning pressure,
257
283
  and the notes on the memory the plan prices: that share, and the command that raises a GPU
@@ -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
@@ -223,7 +223,10 @@ def plan_envelope(
223
223
  "created_at": utc_now(),
224
224
  "facts_collected_at": facts["collected_at"],
225
225
  "hostname": facts["hostname"],
226
- "model": {**model, "download_bytes": sum(f["size_bytes"] for f in files)},
226
+ "model": {
227
+ **model,
228
+ "download_bytes": sum(f["size_bytes"] for f in files if not f.get("generated")),
229
+ },
227
230
  "files": [_with_mirrors(f) for f in files],
228
231
  "engine": engine,
229
232
  "placement": placement,
@@ -0,0 +1,49 @@
1
+ """Additional network and peak disk estimates for pinned artifact preparation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from localmodels.contracts import decode
8
+ from localmodels.plan_envelope import verified_in_place
9
+ from localmodels.records import Plan, ReusableFile
10
+ from localmodels.remote_ops import StrataPreparation
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Cost:
15
+ download_bytes: int = 0
16
+ disk_bytes: int = 0
17
+ generated_bytes: int = 0
18
+
19
+
20
+ def ready(file: ReusableFile) -> bool:
21
+ """An output has a matching download receipt here or at its reusable source."""
22
+ return verified_in_place(file) or bool(
23
+ file.get("reuse") and verified_in_place({**file, "dest": file["reuse"]})
24
+ )
25
+
26
+
27
+ def cost(plan: Plan) -> Cost:
28
+ """A missing group is staged in full; raw downloads live inside the scratch estimate."""
29
+ raw = plan["launch"].get("preparation")
30
+ if not raw:
31
+ return Cost()
32
+ spec = decode(raw, StrataPreparation)
33
+ outputs = [f for f in plan["files"] if f.get("generated")]
34
+ # Reuse is a size-matched candidate, not a verified output. If its hash fails at apply,
35
+ # conversion still needs the full budget; only destination receipts establish readiness.
36
+ missing = [f for f in outputs if not verified_in_place(f)]
37
+ if not missing:
38
+ return Cost()
39
+
40
+ def group(file: ReusableFile) -> str:
41
+ return "mtp" if file["local_name"].startswith("mtp/rt/") else "pack"
42
+
43
+ groups = {group(f) for f in missing}
44
+ staged = sum(f["size_bytes"] for f in outputs if group(f) in groups)
45
+ return Cost(
46
+ download_bytes=spec["download_bytes"],
47
+ disk_bytes=staged + spec["scratch_bytes"],
48
+ generated_bytes=sum(f["size_bytes"] for f in missing),
49
+ )