@simplexai/localmodels-linux-arm64 0.1.0-dev.56 → 0.1.0-dev.58

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 (55) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +54 -52
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_admin.py +2 -1
  5. package/modules/localmodels/bifrost_checks.py +11 -8
  6. package/modules/localmodels/bifrost_models.py +2 -1
  7. package/modules/localmodels/budget.py +161 -1
  8. package/modules/localmodels/catalog.json +10 -8
  9. package/modules/localmodels/catalog.py +5 -2
  10. package/modules/localmodels/gateway_accept.py +4 -3
  11. package/modules/localmodels/gateway_bifrost.py +2 -1
  12. package/modules/localmodels/gateway_cli.py +4 -3
  13. package/modules/localmodels/gateway_server.py +3 -1
  14. package/modules/localmodels/gpu_specs.py +38 -13
  15. package/modules/localmodels/harness.py +2 -2
  16. package/modules/localmodels/hf_repo.py +27 -4
  17. package/modules/localmodels/library_cli.py +8 -1
  18. package/modules/localmodels/library_elastic.py +720 -0
  19. package/modules/localmodels/library_model.py +101 -4
  20. package/modules/localmodels/library_pricing.py +31 -39
  21. package/modules/localmodels/library_serve.py +238 -42
  22. package/modules/localmodels/library_state.py +31 -0
  23. package/modules/localmodels/library_status.py +95 -2
  24. package/modules/localmodels/llm_rank.py +16 -5
  25. package/modules/localmodels/metal.py +141 -0
  26. package/modules/localmodels/metal_probe.py +167 -0
  27. package/modules/localmodels/probe.py +2 -2
  28. package/modules/localmodels/recommend.py +6 -1
  29. package/modules/localmodels/remote_ops_download.py +36 -261
  30. package/modules/localmodels/remote_ops_ranges.py +447 -0
  31. package/modules/localmodels/runtime_auth.py +2 -1
  32. package/modules/localmodels/runtime_cli.py +1 -1
  33. package/modules/localmodels/runtime_install.py +5 -2
  34. package/modules/localmodels/runtime_io.py +3 -2
  35. package/modules/localmodels/runtime_pi.py +2 -1
  36. package/modules/localmodels/runtime_windows_acl.py +39 -0
  37. package/modules/localmodels/source_byok_probe.py +2 -1
  38. package/modules/localmodels/stack.py +13 -3
  39. package/modules/localmodels/stack_cli.py +1 -0
  40. package/modules/localmodels/stack_compose.py +6 -1
  41. package/modules/localmodels/stack_events.py +15 -0
  42. package/modules/localmodels/stack_hardware.py +3 -1
  43. package/modules/localmodels/stack_picks.py +16 -2
  44. package/modules/localmodels/stack_plan.py +5 -1
  45. package/modules/localmodels/stack_progress.py +30 -5
  46. package/modules/localmodels/stack_run.py +117 -0
  47. package/modules/localmodels/transport.py +1 -0
  48. package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev58.dist-info}/METADATA +1 -1
  49. package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev58.dist-info}/RECORD +51 -49
  50. package/package.json +1 -1
  51. package/tool.json +1 -1
  52. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev58.dist-info}/WHEEL +0 -0
  53. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev58.dist-info}/entry_points.txt +0 -0
  54. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev58.dist-info}/licenses/NOTICE +0 -0
  55. /package/modules/{simplex_localmodels-0.1.0.dev56.dist-info → simplex_localmodels-0.1.0.dev58.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -13,8 +13,11 @@ Two short requests measure its decode speed (stack_warm), and the gateway and pi
13
13
  from __future__ import annotations
14
14
 
15
15
  import contextlib
16
+ import contextvars
16
17
  import os
17
18
  import shutil
19
+ from collections.abc import Iterator
20
+ from dataclasses import dataclass
18
21
  from pathlib import Path
19
22
 
20
23
  from localmodels import (
@@ -24,27 +27,73 @@ from localmodels import (
24
27
  frontend,
25
28
  harness,
26
29
  hosts,
30
+ library_elastic,
27
31
  library_gateway,
28
32
  library_jobs,
29
33
  library_kept,
30
34
  library_pricing,
31
35
  library_state,
32
36
  library_status,
37
+ metal,
33
38
  plan_envelope,
34
39
  stack_lifecycle,
35
40
  stack_ports,
36
41
  stack_verify,
37
42
  stack_warm,
38
43
  )
39
- from localmodels.library_model import LibraryError, LoadStep, Row, progress
44
+ from localmodels.library_elastic import ElasticPlan, ElasticRoomError
45
+ from localmodels.library_model import LibraryError, LoadStep, Row, problem_from_error, progress
40
46
  from localmodels.library_pricing import Model
41
- from localmodels.library_state import Job, JobHandle, Record
47
+ from localmodels.library_state import Job, JobHandle, LoadPosture, PostureSnapshot, Record
42
48
  from localmodels.probe import HostFacts
43
49
  from localmodels.records import FinishedRecord, Plan
44
50
  from localmodels.transport import Executor
45
51
 
46
52
  LOAD_STEPS = deploy.STEPS
47
- OOM = ("out of memory", "cudamalloc failed", "failed to allocate", "unable to allocate")
53
+ MAX_OOM_RETRIES = 2
54
+ OOM = (
55
+ "out of memory",
56
+ "cudamalloc failed",
57
+ "failed to allocate",
58
+ "unable to allocate",
59
+ "ggml_metal_buffer_init",
60
+ "metal_buffer_init",
61
+ "newbufferwithlength",
62
+ "failed to create metal",
63
+ "metal allocation failed",
64
+ "ggml_backend_metal_buffer",
65
+ "kioreturnnomemory",
66
+ "not enough memory",
67
+ "insufficient memory",
68
+ "std::bad_alloc",
69
+ "bad_alloc",
70
+ )
71
+
72
+
73
+ @dataclass
74
+ class _ElasticLoadContext:
75
+ """Active load parameters for runtime OOM self-healing retries inside ``_start``."""
76
+
77
+ elastic: ElasticPlan
78
+ base: str
79
+ pool: str
80
+ port: int
81
+ force: bool
82
+
83
+
84
+ _FORCE_LOAD: contextvars.ContextVar[bool] = contextvars.ContextVar("_FORCE_LOAD", default=False)
85
+ _ELASTIC_CTX: contextvars.ContextVar[_ElasticLoadContext | None] = contextvars.ContextVar(
86
+ "_ELASTIC_CTX", default=None
87
+ )
88
+
89
+
90
+ @contextlib.contextmanager
91
+ def _force_scope(force: bool) -> Iterator[None]:
92
+ token = _FORCE_LOAD.set(force)
93
+ try:
94
+ yield
95
+ finally:
96
+ _FORCE_LOAD.reset(token)
48
97
 
49
98
 
50
99
  def _deploy_load_step(step: str) -> LoadStep:
@@ -71,27 +120,113 @@ def _reserved(skip: str) -> dict[str, int]:
71
120
  return found
72
121
 
73
122
 
74
- def _room(facts: HostFacts, model: Model, record: Record, freed: dict[str, int]) -> None:
75
- """LOAD_NO_ROOM unless the model fits its pool now, after ``freed`` is given back."""
123
+ def _pressure_name(level: int | None) -> str | None:
124
+ if level is None:
125
+ return None
126
+ if level == metal.PRESSURE_NORMAL:
127
+ return "normal"
128
+ if level == metal.PRESSURE_WARN:
129
+ return "warn"
130
+ return "critical"
131
+
132
+
133
+ def _no_room_error(
134
+ model: Model,
135
+ exc: deploy.AgentMemoryError,
136
+ default_pool: str,
137
+ *,
138
+ failed: bool = False,
139
+ ) -> LibraryError:
140
+ refused_pool = "system" if exc.memory == "system memory" else default_pool
141
+ fields: dict[str, str | int | bool] = {
142
+ "pool": refused_pool,
143
+ "need_bytes": exc.needed_bytes,
144
+ "free_bytes": exc.available_bytes,
145
+ }
146
+ if isinstance(exc, ElasticRoomError):
147
+ refused_pool = exc.pool
148
+ fields["pool"] = refused_pool
149
+ fields["min_need_bytes"] = exc.min_need_bytes
150
+ fields["shortfall_bytes"] = exc.shortfall_bytes
151
+ fields["can_force"] = exc.can_force
152
+ if exc.wired_headroom_bytes is not None:
153
+ fields["wired_headroom_bytes"] = exc.wired_headroom_bytes
154
+ if exc.soft_available_bytes is not None:
155
+ fields["soft_available_bytes"] = exc.soft_available_bytes
156
+ if (label := _pressure_name(exc.pressure_level)) is not None:
157
+ fields["memory_pressure"] = label
158
+ else:
159
+ fields["min_need_bytes"] = exc.needed_bytes
160
+ fields["shortfall_bytes"] = max(0, exc.needed_bytes - exc.available_bytes)
161
+ fields["can_force"] = False
162
+ return LibraryError(
163
+ "LOAD_NO_ROOM",
164
+ f"{model.id} does not fit {refused_pool} now",
165
+ failed=failed,
166
+ **fields,
167
+ )
168
+
169
+
170
+ def _posture_snapshot(spec: library_elastic.PostureSpec) -> PostureSnapshot:
171
+ summary = spec.to_summary()
172
+ snap: PostureSnapshot = {
173
+ "context_tokens": summary["context_tokens"],
174
+ "slots": summary["slots"],
175
+ }
176
+ if "kv_cache_quant" in summary:
177
+ snap["kv_cache_quant"] = summary["kv_cache_quant"]
178
+ return snap
179
+
180
+
181
+ def _load_posture_record(
182
+ elastic: ElasticPlan, *, oom_retries: int = 0, degradation_reason: str | None = None
183
+ ) -> LoadPosture:
184
+ reason = degradation_reason if degradation_reason is not None else elastic.degradation_reason
185
+ degraded = elastic.degraded or oom_retries > 0
186
+ doc: LoadPosture = {
187
+ "requested_posture": _posture_snapshot(elastic.requested_posture),
188
+ "effective_posture": _posture_snapshot(elastic.effective_posture),
189
+ "degraded": degraded,
190
+ }
191
+ if elastic.memory_pressure_warning is not None:
192
+ warn = elastic.memory_pressure_warning
193
+ doc["memory_pressure_warning"] = {
194
+ "level": warn["level"],
195
+ "pool": warn["pool"],
196
+ "free_bytes": warn["free_bytes"],
197
+ "budget_bytes": warn["budget_bytes"],
198
+ }
199
+ if degraded and reason:
200
+ doc["degradation_reason"] = reason
201
+ if oom_retries > 0:
202
+ doc["oom_retries"] = oom_retries
203
+ if elastic.forced:
204
+ doc["forced"] = True
205
+ return doc
206
+
207
+
208
+ def _room(
209
+ facts: HostFacts,
210
+ model: Model,
211
+ record: Record,
212
+ freed: dict[str, int],
213
+ *,
214
+ force: bool = False,
215
+ ) -> ElasticPlan:
216
+ """LOAD_NO_ROOM unless the model fits its pool under dual-tier admission after ``freed``."""
76
217
  now = library_pricing.live(facts, _reserved(model.id), freed)
77
218
  try:
78
- library_pricing.price(
219
+ return library_elastic.price_elastic(
79
220
  now,
80
221
  model,
81
222
  record["pool"],
82
223
  base_of(record),
83
224
  library_pricing.entries(),
84
- require_live=True,
225
+ allow_overcommit=True,
226
+ force=force,
85
227
  )
86
228
  except deploy.AgentMemoryError as exc:
87
- refused_pool = "system" if exc.memory == "system memory" else record["pool"]
88
- raise LibraryError(
89
- "LOAD_NO_ROOM",
90
- f"{model.id} does not fit {refused_pool} now",
91
- pool=refused_pool,
92
- need_bytes=exc.needed_bytes,
93
- free_bytes=exc.available_bytes,
94
- ) from None
229
+ raise _no_room_error(model, exc, record["pool"]) from None
95
230
  except engines.CudaDriverError as exc:
96
231
  raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc)) from None
97
232
  except engines.EngineUnavailableError as exc:
@@ -161,7 +296,7 @@ def stack_member(record: Record) -> str | None:
161
296
 
162
297
  def _fail(record: Record, error: LibraryError) -> LibraryError:
163
298
  record["state"] = "failed"
164
- record["error"] = {"code": error.code, "detail": error.detail}
299
+ record["error"] = problem_from_error(error)
165
300
  library_state.save(record) # a registration it could not take out stays for unload
166
301
  return error
167
302
 
@@ -182,6 +317,7 @@ def stop(record: Record, run: Executor) -> None:
182
317
  "detail": "stopping the model server did not finish; unload or load it again",
183
318
  }
184
319
  library_state.save(record)
320
+ record.pop("load_posture", None)
185
321
  if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
186
322
  _remove_service(record["plan"], run)
187
323
  record["state"] = "idle"
@@ -197,46 +333,52 @@ def _serve(
197
333
  run: Executor,
198
334
  port: int,
199
335
  handle: JobHandle,
336
+ *,
337
+ force: bool = False,
200
338
  ) -> Record:
201
339
  base = base_of(record)
202
340
  now = library_pricing.live(facts, _reserved(model.id))
203
341
  try:
204
- plan = library_pricing.price(
342
+ elastic = library_elastic.price_elastic(
205
343
  now,
206
344
  model,
207
345
  record["pool"],
208
346
  base,
209
347
  library_pricing.entries(),
210
348
  port=port,
211
- require_live=True,
349
+ allow_overcommit=True,
350
+ force=force,
212
351
  )
213
352
  except deploy.AgentMemoryError as exc: # after --unload: no longer a refusal
214
- refused_pool = "system" if exc.memory == "system memory" else record["pool"]
215
- raise LibraryError(
216
- "LOAD_NO_ROOM",
217
- f"{model.id} does not fit {refused_pool} now",
218
- failed=True,
219
- pool=refused_pool,
220
- need_bytes=exc.needed_bytes,
221
- free_bytes=exc.available_bytes,
222
- ) from None
353
+ raise _fail(record, _no_room_error(model, exc, record["pool"], failed=True)) from None
223
354
  except engines.CudaDriverError as exc:
224
355
  raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc), failed=True) from None
225
356
  except engines.EngineUnavailableError as exc:
226
357
  raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc), failed=True) from None
227
358
  except library_pricing.LiveMemoryUnavailable as exc:
228
- raise LibraryError(
229
- "LOAD_NO_ROOM",
230
- str(exc),
231
- failed=True,
232
- pool=record["pool"],
233
- need_bytes=record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"]),
234
- free_bytes=0,
359
+ need = record.get("memory_bytes") or library_pricing.memory_bytes(record["plan"])
360
+ raise _fail(
361
+ record,
362
+ LibraryError(
363
+ "LOAD_NO_ROOM",
364
+ str(exc),
365
+ failed=True,
366
+ pool=record["pool"],
367
+ need_bytes=need,
368
+ free_bytes=0,
369
+ min_need_bytes=need,
370
+ shortfall_bytes=need,
371
+ can_force=False,
372
+ ),
235
373
  ) from None
374
+ plan = elastic.plan
236
375
  if missing := library_jobs.files_missing(plan):
237
376
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing), failed=True)
238
377
  steps = [str(step) for step in LOAD_STEPS]
239
-
378
+ record["load_posture"] = _load_posture_record(elastic)
379
+ ctx_token = _ELASTIC_CTX.set(
380
+ _ElasticLoadContext(elastic=elastic, base=base, pool=record["pool"], port=port, force=force)
381
+ )
240
382
  record["plan"], record["state"] = plan, "starting"
241
383
  record.pop("error", None)
242
384
  library_state.save(record) # the server about to start is recorded before it exists
@@ -249,6 +391,8 @@ def _serve(
249
391
  except BaseException: # interrupted (cancel, Ctrl-C) or crashed once the server may run
250
392
  _abandon(record, run)
251
393
  raise
394
+ finally:
395
+ _ELASTIC_CTX.reset(ctx_token)
252
396
  record["state"] = "loaded"
253
397
  record.pop("error", None)
254
398
  record.pop("note", None)
@@ -256,6 +400,29 @@ def _serve(
256
400
  return record
257
401
 
258
402
 
403
+ def _next_oom_rung(
404
+ model: Model, facts: HostFacts, ctx: _ElasticLoadContext, next_index: int
405
+ ) -> ElasticPlan | None:
406
+ """Build the plan for posture rung ``next_index`` after an OOM failure on rung ``k``."""
407
+ if not ctx.elastic.ladder or next_index >= len(ctx.elastic.ladder):
408
+ return None
409
+ now = library_pricing.live(facts, _reserved(model.id))
410
+ try:
411
+ return library_elastic.price_elastic(
412
+ now,
413
+ model,
414
+ ctx.pool,
415
+ ctx.base,
416
+ library_pricing.entries(),
417
+ port=ctx.port,
418
+ allow_overcommit=True,
419
+ force=ctx.force,
420
+ min_rung_index=next_index,
421
+ )
422
+ except plan_envelope.PlanError:
423
+ return None
424
+
425
+
259
426
  def _start(
260
427
  model: Model,
261
428
  record: Record,
@@ -277,11 +444,32 @@ def _start(
277
444
  except frontend.FrontendError as exc:
278
445
  raise _fail(record, LibraryError("ENGINE_START_FAILED", str(exc))) from None
279
446
 
280
- finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
281
- if not finished["ok"]:
282
- error = LibraryError(_start_code(finished), str(finished.get("error") or "start failed"))
447
+ ctx = _ELASTIC_CTX.get()
448
+ oom_retries = 0
449
+ while True:
450
+ finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
451
+ if finished["ok"]:
452
+ break
453
+ code = _start_code(finished)
454
+ error = LibraryError(code, str(finished.get("error") or "start failed"))
283
455
  with contextlib.suppress(LibraryError): # the record keeps the plan to stop it later
284
456
  _remove_service(plan, run)
457
+ if code == "OUT_OF_MEMORY" and ctx is not None and oom_retries < MAX_OOM_RETRIES:
458
+ next_elastic = _next_oom_rung(model, facts, ctx, ctx.elastic.rung_index + 1)
459
+ if next_elastic is not None:
460
+ oom_retries += 1
461
+ ctx.elastic = next_elastic
462
+ plan = next_elastic.plan
463
+ record["plan"] = plan
464
+ record["load_posture"] = _load_posture_record(
465
+ next_elastic,
466
+ oom_retries=oom_retries,
467
+ degradation_reason="oom_retry",
468
+ )
469
+ library_state.save(record)
470
+ handle.update("load", 0, len(steps), load_step="prepare")
471
+ progress(model.id, "load", 0, len(steps), load_step="prepare")
472
+ continue
285
473
  raise _fail(record, error)
286
474
  handle.update("load", len(steps), len(steps), load_step="load")
287
475
  progress(model.id, "load", len(steps), len(steps), load_step="load")
@@ -345,7 +533,7 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
345
533
  freed["system"] = freed.get("system", 0) + library_pricing.host_ram_bytes(
346
534
  target["plan"], catalog
347
535
  )
348
- _room(facts, model, record, freed)
536
+ _room(facts, model, record, freed, force=_FORCE_LOAD.get())
349
537
 
350
538
 
351
539
  def _row(model: Model, base_dir: str) -> Row:
@@ -354,7 +542,7 @@ def _row(model: Model, base_dir: str) -> Row:
354
542
  return library_status.row(library_status.Library.read(library_jobs.probe(), base_dir), model)
355
543
 
356
544
 
357
- def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
545
+ def load(model_id: str, base_dir: str, unload: list[str], *, force: bool = False) -> Row:
358
546
  from localmodels import library_convert
359
547
 
360
548
  library_convert.convert_once()
@@ -365,7 +553,7 @@ def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
365
553
  dict.fromkeys(library_pricing.find(m, library_pricing.entries()).id for m in unload)
366
554
  )
367
555
  targets: list[Record] = []
368
- with library_state.locked(): # validate, admit and claim as one step
556
+ with library_state.locked(), _force_scope(force): # validate, admit and claim as one step
369
557
  library_state.refuse_busy(model.id, "load")
370
558
  record = library_state.load(model.id)
371
559
  if record is None:
@@ -404,7 +592,15 @@ def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
404
592
  # A stop that fails ends the load: a server that may still run keeps its record
405
593
  # and its memory, and nothing is started beside it.
406
594
  stop(record, executor)
407
- _serve(model, record, library_jobs.probe() if refresh else facts, executor, port, handle)
595
+ _serve(
596
+ model,
597
+ record,
598
+ library_jobs.probe() if refresh else facts,
599
+ executor,
600
+ port,
601
+ handle,
602
+ force=force,
603
+ )
408
604
  return _row(model, base_dir)
409
605
 
410
606
 
@@ -56,6 +56,36 @@ class _RecordRequired(TypedDict):
56
56
  updated_at: str
57
57
 
58
58
 
59
+ class _PostureSnapshotRequired(TypedDict):
60
+ context_tokens: int
61
+ slots: int
62
+
63
+
64
+ class PostureSnapshot(_PostureSnapshotRequired, total=False):
65
+ kv_cache_quant: str
66
+ kv_types: list[str]
67
+
68
+
69
+ class PressureWarningSnapshot(TypedDict):
70
+ level: str
71
+ pool: str
72
+ free_bytes: int
73
+ budget_bytes: int
74
+
75
+
76
+ class _LoadPostureRequired(TypedDict):
77
+ requested_posture: PostureSnapshot
78
+ effective_posture: PostureSnapshot
79
+ degraded: bool
80
+
81
+
82
+ class LoadPosture(_LoadPostureRequired, total=False):
83
+ degradation_reason: str
84
+ memory_pressure_warning: PressureWarningSnapshot
85
+ oom_retries: int
86
+ forced: bool
87
+
88
+
59
89
  class Record(_RecordRequired, total=False):
60
90
  base_dir: str # where it was downloaded: its weights, engine and deployments live there
61
91
  memory_bytes: int # the footprint priced at download (on the pool's whole capacity)
@@ -67,6 +97,7 @@ class Record(_RecordRequired, total=False):
67
97
  converted: bool # adopted from a Quick Install stack
68
98
  stack_provider: str # converted: its own stack provider, the main or the fastest LLM
69
99
  pi_model: str # what pi offers once it is loaded; fixed when the record is made
100
+ load_posture: LoadPosture # elastic posture & warning metadata recorded on load
70
101
 
71
102
 
72
103
  class _JobSince20261113(TypedDict, total=False):
@@ -13,8 +13,10 @@ from typing import cast
13
13
 
14
14
  from localmodels import (
15
15
  __version__,
16
+ budget,
16
17
  debug_mode,
17
18
  hosts,
19
+ library_elastic,
18
20
  library_floor,
19
21
  library_gateway,
20
22
  library_order,
@@ -29,23 +31,30 @@ from localmodels import (
29
31
  from localmodels import catalog as cat
30
32
  from localmodels.library_model import (
31
33
  DOWNLOAD_SOURCES,
34
+ KV_CACHE_QUANTS,
32
35
  LOAD_STEPS_PUBLIC,
33
36
  STATUS_SCHEMA,
34
37
  Availability,
35
38
  DebugInfo,
39
+ DegradationReason,
36
40
  Download,
37
41
  DownloadSource,
38
42
  Engine,
39
43
  Holder,
40
44
  Host,
45
+ KvCacheQuant,
41
46
  LibraryError,
42
47
  Load,
43
48
  LoadStep,
44
49
  MemoryPressure,
50
+ MemoryPressureWarning,
51
+ MemoryPressureWarningLevel,
45
52
  Pool,
53
+ PostureSummary,
46
54
  Problem,
47
55
  Row,
48
56
  Status,
57
+ sanitize_problem,
49
58
  )
50
59
  from localmodels.library_pricing import Model, Priced
51
60
  from localmodels.library_state import Job, Record
@@ -155,7 +164,7 @@ def _state(lib: Library, model: str, record: Record | None) -> tuple[str, Proble
155
164
  return ("downloading" if job["kind"] == "download" else "loading"), None
156
165
  if job is not None: # its process ended without clearing it, or it failed and kept its partials
157
166
  if isinstance(err := job.get("error"), dict) and isinstance(err.get("code"), str):
158
- return "failed", {"code": err["code"], "detail": str(err.get("detail") or "")}
167
+ return "failed", sanitize_problem(err)
159
168
  code = "DOWNLOAD_FAILED" if job["kind"] == "download" else "ENGINE_START_FAILED"
160
169
  return "failed", {"code": code, "detail": f"the {job['kind']} process ended early"}
161
170
  if record is None:
@@ -324,6 +333,53 @@ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None
324
333
  found["host_ram_bytes"] = host_ram
325
334
 
326
335
 
336
+ def _posture_summary(raw: Mapping[str, object]) -> PostureSummary:
337
+ summary: PostureSummary = {
338
+ "context_tokens": int(str(raw["context_tokens"])),
339
+ "slots": int(str(raw["slots"])),
340
+ }
341
+ quant = raw.get("kv_cache_quant")
342
+ if isinstance(quant, str) and quant in KV_CACHE_QUANTS:
343
+ summary["kv_cache_quant"] = cast(KvCacheQuant, quant)
344
+ else:
345
+ kv_types = raw.get("kv_types")
346
+ if (
347
+ isinstance(kv_types, list | tuple)
348
+ and len(kv_types) == 2
349
+ and kv_types[0] == kv_types[1]
350
+ and kv_types[0] in KV_CACHE_QUANTS
351
+ ):
352
+ summary["kv_cache_quant"] = cast(KvCacheQuant, kv_types[0])
353
+ return summary
354
+
355
+
356
+ def _pressure_warning(raw: object) -> MemoryPressureWarning | None:
357
+ if not isinstance(raw, Mapping):
358
+ return None
359
+ level = raw.get("level")
360
+ pool = raw.get("pool")
361
+ free_b = raw.get("free_bytes")
362
+ budget_b = raw.get("budget_bytes")
363
+ if (
364
+ level not in ("soft", "high")
365
+ or not isinstance(pool, str)
366
+ or not pool
367
+ or not isinstance(free_b, int)
368
+ or isinstance(free_b, bool)
369
+ or free_b < 0
370
+ or not isinstance(budget_b, int)
371
+ or isinstance(budget_b, bool)
372
+ or budget_b < 0
373
+ ):
374
+ return None
375
+ return {
376
+ "level": cast(MemoryPressureWarningLevel, level),
377
+ "pool": pool,
378
+ "free_bytes": free_b,
379
+ "budget_bytes": budget_b,
380
+ }
381
+
382
+
327
383
  def _apply_record_meta(
328
384
  found: Row,
329
385
  model: Model,
@@ -344,10 +400,28 @@ def _apply_record_meta(
344
400
  found["tokens_per_second"] = round(speed, 1)
345
401
  if (prefill := record.get("prompt_tokens_per_second")) is not None:
346
402
  found["prompt_tokens_per_second"] = round(prefill, 1)
403
+ if state == "loaded" and (lp := record.get("load_posture")) is not None:
404
+ found["degraded"] = bool(lp["degraded"])
405
+ found["requested_posture"] = _posture_summary(lp["requested_posture"])
406
+ found["effective_posture"] = _posture_summary(lp["effective_posture"])
407
+ if (warn := _pressure_warning(lp.get("memory_pressure_warning"))) is not None:
408
+ found["memory_pressure_warning"] = warn
409
+ if (reason := lp.get("degradation_reason")) in (
410
+ "reduced_slots",
411
+ "reduced_context",
412
+ "above_soft_budget",
413
+ "oom_retry",
414
+ "forced_overcommit",
415
+ ):
416
+ found["degradation_reason"] = cast(DegradationReason, reason)
417
+ if (retries := lp.get("oom_retries")) is not None and retries > 0:
418
+ found["oom_retries"] = int(retries)
419
+ if lp.get("forced"):
420
+ found["forced"] = True
347
421
  if state == "idle" and (note := record.get("note")):
348
422
  found["note"] = note
349
423
  if state == "failed" and problem is not None:
350
- found["error"] = problem
424
+ found["error"] = sanitize_problem(problem)
351
425
 
352
426
 
353
427
  def row(lib: Library, model: Model) -> Row:
@@ -400,6 +474,10 @@ def row(lib: Library, model: Model) -> Row:
400
474
  "state": state, # type: ignore[typeddict-item]
401
475
  }
402
476
  _apply_live_fit(lib, found, model, priced, record, state, memory)
477
+ if found["pool"]:
478
+ min_mem = library_elastic.minimum_memory_bytes(lib.facts, model, found["pool"])
479
+ if min_mem is not None and min_mem > 0:
480
+ found["minimum_memory_bytes"] = min(min_mem, memory) if memory > 0 else min_mem
403
481
  job, alive = lib.jobs.get(model.id, (None, False))
404
482
  if state == "downloading" and job is not None and alive:
405
483
  found["download"] = _downloading(job)
@@ -467,6 +545,13 @@ def pools(lib: Library, rows: list[Row]) -> list[Pool]:
467
545
  "holders": held,
468
546
  "reserve_bytes": library_pricing.pool_reserve(now, pool),
469
547
  }
548
+ if pool == "unified" and metal.supported(now):
549
+ adm = budget.admission_budget(now, "unified")
550
+ if adm is not None:
551
+ entry["soft_budget_bytes"] = adm.soft_budget_bytes
552
+ entry["hard_ceiling_bytes"] = adm.hard_ceiling_bytes
553
+ if adm.wired_headroom_bytes is not None:
554
+ entry["wired_headroom_bytes"] = adm.wired_headroom_bytes
470
555
  if ext := library_vram.pool_external_holders(lib.facts, pool, gpu_pool_count):
471
556
  entry["external_holders"] = ext
472
557
  found.append(entry)
@@ -556,6 +641,14 @@ def host(lib: Library) -> Host:
556
641
  }
557
642
  if (ws := metal.read_working_set(facts)) is not None and ws > 0:
558
643
  found["metal_working_set_bytes"] = ws
644
+ if metal.supported(facts):
645
+ if (ws := metal.read_working_set(facts)) is not None and ws > 0:
646
+ found["wired_limit_bytes"] = metal.wired_ceiling_bytes(facts)
647
+ found["wired_headroom_bytes"] = metal.wired_headroom_bytes(facts)
648
+ if (gpu_use := metal.gpu_in_use_reading(facts)) is not None:
649
+ found["gpu_in_use_bytes"] = gpu_use
650
+ if (inactive_anon := metal.inactive_anon_bytes(facts)) > 0:
651
+ found["inactive_anon_bytes"] = inactive_anon
559
652
  if (pressure := _pressure_label(facts["ram"].get("pressure_level"))) is not None:
560
653
  found["memory_pressure"] = pressure
561
654
  return found
@@ -16,6 +16,7 @@ from dataclasses import dataclass
16
16
  from localmodels import engines, metal, vision
17
17
  from localmodels.budget import HARNESS_RAM, RAM_FLOOR, host_ram
18
18
  from localmodels.catalog import (
19
+ USABLE_FLOOR_TOK_S,
19
20
  CatalogEntry,
20
21
  DecisionRecipe,
21
22
  QuantVariant,
@@ -346,14 +347,18 @@ def choose(
346
347
  ladder: MacLadder | None = None,
347
348
  *,
348
349
  fallback_ids: Iterable[str] = (),
350
+ slow_ids: Iterable[str] = (),
349
351
  ) -> tuple[str, int]:
350
352
  """(entry id, card index) out of ``(rank_key, id, card)`` triples for one scenario: fastest
351
353
  takes the highest decode speed whatever the score (the score breaks ties); smartest and
352
354
  concurrent take the best score (speed breaks ties); fast takes the fastest whose score is
353
- within FAST_QUALITY_BAND of the best. Scoped ``fallback_ids`` are considered only when no
354
- primary fits on any eligible card. On a Mac ``ladder`` rungs never rank by score: smartest
355
- takes the first fitting rung while keeps_default holds for the other fits, and fastest races
356
- the first fitting rung of ``ladder.fastest`` against the other fits."""
355
+ within FAST_QUALITY_BAND of the best. Candidates in ``slow_ids`` (below USABLE_FLOOR_TOK_S)
356
+ are demoted whenever any usable candidate fits; scoped ``fallback_ids`` are considered only
357
+ when no usable primary fits on any eligible card. On a Mac ``ladder`` rungs never rank by
358
+ score: smartest takes the first fitting rung while keeps_default holds for the other fits,
359
+ and fastest races the first fitting rung of ``ladder.fastest`` against the other fits."""
360
+ slow = set(slow_ids)
361
+ ranked = [row for row in ranked if row[1] not in slow] or ranked
357
362
  fallback = set(fallback_ids)
358
363
  ranked = [row for row in ranked if row[1] not in fallback] or ranked
359
364
  if ladder is not None:
@@ -361,7 +366,7 @@ def choose(
361
366
  primary = [row for row in ranked if row[1] not in rungs]
362
367
  if prefer == "fastest":
363
368
  rung = next((rungs[i] for i in ladder.fastest if i in rungs), None)
364
- pool = primary + ([rung] if rung is not None else [])
369
+ pool = primary + ([rung] if rung is not None else []) or ranked
365
370
  _, entry_id, index = max(pool, key=lambda t: (t[0][1], t[0][0]))
366
371
  return entry_id, index
367
372
  if rungs and keeps_default(key[0] for key, _, _ in primary):
@@ -400,6 +405,12 @@ def recommended_entry(
400
405
  return None
401
406
 
402
407
  resident = [(e, c) for e, c in fitting if c.zero_spill and agent_ready(e, c.variant, budget)]
408
+ usable = [
409
+ (e, c)
410
+ for e, c in resident
411
+ if predicted_decode_tok_s(e, c.variant, budget, backend=backend) >= USABLE_FLOOR_TOK_S
412
+ ]
413
+ resident = usable or resident
403
414
  rungs = {e.id: e for e, _ in resident if e.id in ladder}
404
415
  resident = [(e, c) for e, c in resident if e.id not in rungs]
405
416
  if rungs and keeps_default(e.quality for e, _ in resident):