@simplexai/localmodels-darwin-x64 0.1.0-dev.57 → 0.1.0-dev.59

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 (68) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +66 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +1 -1
  5. package/modules/localmodels/bifrost_admin.py +53 -8
  6. package/modules/localmodels/bifrost_config.py +103 -4
  7. package/modules/localmodels/bifrost_log.py +166 -0
  8. package/modules/localmodels/budget.py +161 -1
  9. package/modules/localmodels/catalog.json +55 -32
  10. package/modules/localmodels/catalog.py +5 -2
  11. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
  12. package/modules/localmodels/frontend.py +26 -21
  13. package/modules/localmodels/gateway_bifrost.py +30 -6
  14. package/modules/localmodels/gpu_specs.py +38 -13
  15. package/modules/localmodels/hosts.py +99 -12
  16. package/modules/localmodels/library_cli.py +8 -1
  17. package/modules/localmodels/library_convert.py +34 -0
  18. package/modules/localmodels/library_elastic.py +747 -0
  19. package/modules/localmodels/library_gateway.py +101 -10
  20. package/modules/localmodels/library_jobs.py +16 -7
  21. package/modules/localmodels/library_model.py +101 -4
  22. package/modules/localmodels/library_pricing.py +41 -39
  23. package/modules/localmodels/library_serve.py +322 -58
  24. package/modules/localmodels/library_state.py +35 -1
  25. package/modules/localmodels/library_status.py +113 -6
  26. package/modules/localmodels/llm_rank.py +16 -5
  27. package/modules/localmodels/metal.py +141 -0
  28. package/modules/localmodels/metal_probe.py +167 -0
  29. package/modules/localmodels/plan_envelope.py +4 -1
  30. package/modules/localmodels/probe.py +2 -2
  31. package/modules/localmodels/process_identity_linux.py +39 -0
  32. package/modules/localmodels/recommend.py +6 -1
  33. package/modules/localmodels/remote_ops.py +4 -3
  34. package/modules/localmodels/remote_ops_download.py +37 -24
  35. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  36. package/modules/localmodels/remote_ops_service.py +93 -36
  37. package/modules/localmodels/runtime_auth.py +4 -1
  38. package/modules/localmodels/service_wiring.py +238 -12
  39. package/modules/localmodels/setup_inspection.py +47 -70
  40. package/modules/localmodels/setup_inspection_harness.py +159 -15
  41. package/modules/localmodels/setup_text.py +14 -0
  42. package/modules/localmodels/setup_upgrade.py +1 -1
  43. package/modules/localmodels/source_byok.py +6 -2
  44. package/modules/localmodels/source_byok_probe.py +6 -1
  45. package/modules/localmodels/stack.py +9 -1
  46. package/modules/localmodels/stack_binding.py +3 -35
  47. package/modules/localmodels/stack_cleanup.py +4 -0
  48. package/modules/localmodels/stack_compose.py +24 -3
  49. package/modules/localmodels/stack_hardware.py +3 -1
  50. package/modules/localmodels/stack_lifecycle.py +24 -1
  51. package/modules/localmodels/stack_picks.py +16 -2
  52. package/modules/localmodels/stack_plan.py +6 -2
  53. package/modules/localmodels/stack_ports.py +2 -0
  54. package/modules/localmodels/stack_remove.py +10 -1
  55. package/modules/localmodels/stack_up.py +33 -7
  56. package/modules/localmodels/stack_update.py +3 -1
  57. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
  58. package/modules/localmodels/suite.py +43 -27
  59. package/modules/localmodels/transport.py +13 -2
  60. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
  61. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +63 -61
  62. package/package.json +1 -1
  63. package/tool.json +1 -1
  64. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  65. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
  68. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -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:
@@ -177,10 +186,24 @@ def _state(lib: Library, model: str, record: Record | None) -> tuple[str, Proble
177
186
  return "idle", None
178
187
 
179
188
 
180
- def _plan_of(lib: Library, model: Model, record: Record | None, priced: Priced) -> Plan | None:
181
- """The plan a row shows: its record's; for a model a live job is downloading, the price on
182
- the pool that job recorded (status never moves a running download to another card)."""
189
+ def _plan_of(
190
+ lib: Library,
191
+ model: Model,
192
+ record: Record | None,
193
+ priced: Priced,
194
+ *,
195
+ state: str | None = None,
196
+ ) -> Plan | None:
197
+ """The plan a row shows: its record's (preferring ``baseline_plan`` whenever not loaded so a
198
+ prior degraded load never pollutes idle/failed specs); for a model a live job is downloading,
199
+ the price on the pool that job recorded (status never moves a running download to another card)."""
183
200
  if record is not None:
201
+ if (
202
+ state is not None
203
+ and state != "loaded"
204
+ and (baseline := record.get("baseline_plan")) is not None
205
+ ):
206
+ return baseline
184
207
  return record["plan"]
185
208
  job, alive = lib.jobs.get(model.id, (None, False))
186
209
  if job is not None and alive and job["pool"] != priced.pool:
@@ -324,6 +347,53 @@ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None
324
347
  found["host_ram_bytes"] = host_ram
325
348
 
326
349
 
350
+ def _posture_summary(raw: Mapping[str, object]) -> PostureSummary:
351
+ summary: PostureSummary = {
352
+ "context_tokens": int(str(raw["context_tokens"])),
353
+ "slots": int(str(raw["slots"])),
354
+ }
355
+ quant = raw.get("kv_cache_quant")
356
+ if isinstance(quant, str) and quant in KV_CACHE_QUANTS:
357
+ summary["kv_cache_quant"] = cast(KvCacheQuant, quant)
358
+ else:
359
+ kv_types = raw.get("kv_types")
360
+ if (
361
+ isinstance(kv_types, list | tuple)
362
+ and len(kv_types) == 2
363
+ and kv_types[0] == kv_types[1]
364
+ and kv_types[0] in KV_CACHE_QUANTS
365
+ ):
366
+ summary["kv_cache_quant"] = cast(KvCacheQuant, kv_types[0])
367
+ return summary
368
+
369
+
370
+ def _pressure_warning(raw: object) -> MemoryPressureWarning | None:
371
+ if not isinstance(raw, Mapping):
372
+ return None
373
+ level = raw.get("level")
374
+ pool = raw.get("pool")
375
+ free_b = raw.get("free_bytes")
376
+ budget_b = raw.get("budget_bytes")
377
+ if (
378
+ level not in ("soft", "high")
379
+ or not isinstance(pool, str)
380
+ or not pool
381
+ or not isinstance(free_b, int)
382
+ or isinstance(free_b, bool)
383
+ or free_b < 0
384
+ or not isinstance(budget_b, int)
385
+ or isinstance(budget_b, bool)
386
+ or budget_b < 0
387
+ ):
388
+ return None
389
+ return {
390
+ "level": cast(MemoryPressureWarningLevel, level),
391
+ "pool": pool,
392
+ "free_bytes": free_b,
393
+ "budget_bytes": budget_b,
394
+ }
395
+
396
+
327
397
  def _apply_record_meta(
328
398
  found: Row,
329
399
  model: Model,
@@ -344,17 +414,35 @@ def _apply_record_meta(
344
414
  found["tokens_per_second"] = round(speed, 1)
345
415
  if (prefill := record.get("prompt_tokens_per_second")) is not None:
346
416
  found["prompt_tokens_per_second"] = round(prefill, 1)
417
+ if state == "loaded" and (lp := record.get("load_posture")) is not None:
418
+ found["degraded"] = bool(lp["degraded"])
419
+ found["requested_posture"] = _posture_summary(lp["requested_posture"])
420
+ found["effective_posture"] = _posture_summary(lp["effective_posture"])
421
+ if (warn := _pressure_warning(lp.get("memory_pressure_warning"))) is not None:
422
+ found["memory_pressure_warning"] = warn
423
+ if (reason := lp.get("degradation_reason")) in (
424
+ "reduced_slots",
425
+ "reduced_context",
426
+ "above_soft_budget",
427
+ "oom_retry",
428
+ "forced_overcommit",
429
+ ):
430
+ found["degradation_reason"] = cast(DegradationReason, reason)
431
+ if (retries := lp.get("oom_retries")) is not None and retries > 0:
432
+ found["oom_retries"] = int(retries)
433
+ if lp.get("forced"):
434
+ found["forced"] = True
347
435
  if state == "idle" and (note := record.get("note")):
348
436
  found["note"] = note
349
437
  if state == "failed" and problem is not None:
350
- found["error"] = problem
438
+ found["error"] = sanitize_problem(problem)
351
439
 
352
440
 
353
441
  def row(lib: Library, model: Model) -> Row:
354
442
  record = lib.records.get(model.id)
355
443
  priced = lib.judge(model)
356
444
  state, problem = _state(lib, model.id, record)
357
- plan = _plan_of(lib, model, record, priced)
445
+ plan = _plan_of(lib, model, record, priced, state=state)
358
446
  job, alive = lib.jobs.get(model.id, (None, False))
359
447
  fallback_memory, fallback_window, fallback_vision, fallback_download = (
360
448
  library_floor.floor_metadata(
@@ -400,6 +488,10 @@ def row(lib: Library, model: Model) -> Row:
400
488
  "state": state, # type: ignore[typeddict-item]
401
489
  }
402
490
  _apply_live_fit(lib, found, model, priced, record, state, memory)
491
+ if found["pool"]:
492
+ min_mem = library_elastic.minimum_memory_bytes(lib.facts, model, found["pool"])
493
+ if min_mem is not None and min_mem > 0:
494
+ found["minimum_memory_bytes"] = min(min_mem, memory) if memory > 0 else min_mem
403
495
  job, alive = lib.jobs.get(model.id, (None, False))
404
496
  if state == "downloading" and job is not None and alive:
405
497
  found["download"] = _downloading(job)
@@ -467,6 +559,13 @@ def pools(lib: Library, rows: list[Row]) -> list[Pool]:
467
559
  "holders": held,
468
560
  "reserve_bytes": library_pricing.pool_reserve(now, pool),
469
561
  }
562
+ if pool == "unified" and metal.supported(now):
563
+ adm = budget.admission_budget(now, "unified")
564
+ if adm is not None:
565
+ entry["soft_budget_bytes"] = adm.soft_budget_bytes
566
+ entry["hard_ceiling_bytes"] = adm.hard_ceiling_bytes
567
+ if adm.wired_headroom_bytes is not None:
568
+ entry["wired_headroom_bytes"] = adm.wired_headroom_bytes
470
569
  if ext := library_vram.pool_external_holders(lib.facts, pool, gpu_pool_count):
471
570
  entry["external_holders"] = ext
472
571
  found.append(entry)
@@ -556,6 +655,14 @@ def host(lib: Library) -> Host:
556
655
  }
557
656
  if (ws := metal.read_working_set(facts)) is not None and ws > 0:
558
657
  found["metal_working_set_bytes"] = ws
658
+ if metal.supported(facts):
659
+ if (ws := metal.read_working_set(facts)) is not None and ws > 0:
660
+ found["wired_limit_bytes"] = metal.wired_ceiling_bytes(facts)
661
+ found["wired_headroom_bytes"] = metal.wired_headroom_bytes(facts)
662
+ if (gpu_use := metal.gpu_in_use_reading(facts)) is not None:
663
+ found["gpu_in_use_bytes"] = gpu_use
664
+ if (inactive_anon := metal.inactive_anon_bytes(facts)) > 0:
665
+ found["inactive_anon_bytes"] = inactive_anon
559
666
  if (pressure := _pressure_label(facts["ram"].get("pressure_level"))) is not None:
560
667
  found["memory_pressure"] = pressure
561
668
  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):
@@ -62,8 +62,21 @@ RESERVE_MAX_BYTES = 8 * GIB
62
62
  # it kills processes (a 73.4 GB plan against 73.8 GB available was aborted on local-119,
63
63
  # 2026-10-29). A shared Mac can sit at warning for hours with tens of GB free, so warning plans
64
64
  # keep this share of the RAM available back instead of refusing.
65
+ PRESSURE_NORMAL = 1
65
66
  PRESSURE_WARN = 2
67
+ PRESSURE_CRITICAL = 4
66
68
  WARN_KEEP_FRACTION = 0.25
69
+ # Dual-tier admission constants for Apple Silicon unified memory:
70
+ # - Hard ceiling: Metal wired ceiling minus live AGX wired usage, scaled by a safety fraction.
71
+ # - Soft budget: scales host keep down for 16 GiB Macs (1.0 GiB + 0.5 GiB display = 1.5 GiB vs
72
+ # 2.5 GiB on 24 GiB+ Macs) and accounts for compressible inactive anonymous pages when macOS
73
+ # VM memory pressure is Normal or Warn (never when Critical).
74
+ SMALL_HOST_THRESHOLD_BYTES = 16 * GIB
75
+ SMALL_HOST_KEEP_BYTES = 1 * GIB
76
+ HARD_OS_FLOOR_BYTES = 1 * GIB
77
+ WIRED_HEADROOM_SAFETY_FRACTION = 0.92
78
+ INACTIVE_ANON_RECLAIM_NORMAL = 0.50
79
+ INACTIVE_ANON_RECLAIM_WARN = 0.25
67
80
 
68
81
 
69
82
  class Metal(TypedDict, total=False):
@@ -75,6 +88,8 @@ class Metal(TypedDict, total=False):
75
88
  recommended_max_working_set_bytes: int | None
76
89
  unified_memory: bool
77
90
  assumed_total_bytes: int # set by ``assume`` (--unified-memory), never by the probe
91
+ wired_limit_bytes: int | None # sysctl iogpu.wired_limit_mb in bytes when explicitly set (> 0)
92
+ gpu_in_use_bytes: int | None # live AGXAccelerator "In use system memory" in bytes
78
93
 
79
94
 
80
95
  def reading(facts: HostFacts) -> Metal | None:
@@ -135,6 +150,132 @@ def working_set_bytes(facts: HostFacts) -> int:
135
150
  return read_working_set(facts) or default_working_set(facts["ram"]["total_bytes"])
136
151
 
137
152
 
153
+ def wired_ceiling_bytes(facts: HostFacts) -> int:
154
+ """Effective Metal wired ceiling: explicit ``iogpu.wired_limit_mb`` when set, else
155
+ ``recommendedMaxWorkingSetSize``, else Apple's default share of physical RAM."""
156
+ found = reading(facts)
157
+ wired = found.get("wired_limit_bytes") if found else None
158
+ if wired is not None and wired > 0:
159
+ return int(wired)
160
+ return working_set_bytes(facts)
161
+
162
+
163
+ def gpu_in_use_reading(facts: HostFacts) -> int | None:
164
+ """Live AGXAccelerator wired GPU usage reading in bytes when available, else None."""
165
+ found = reading(facts)
166
+ in_use = found.get("gpu_in_use_bytes") if found else None
167
+ if in_use is not None and in_use >= 0:
168
+ return int(in_use)
169
+ return None
170
+
171
+
172
+ def gpu_in_use_bytes(facts: HostFacts) -> int:
173
+ """Live system-wide GPU wired usage in bytes: AGXAccelerator reading when available,
174
+ otherwise the non-cached resident memory of observed Metal inference processes."""
175
+ direct = gpu_in_use_reading(facts)
176
+ if direct is not None:
177
+ return direct
178
+ return sum(
179
+ max(0, int(p.get("used_bytes") or 0) - int(p.get("cached_bytes") or 0))
180
+ for p in _metal_processes(facts)
181
+ )
182
+
183
+
184
+ def is_critical_pressure(facts: HostFacts) -> bool:
185
+ """True when macOS ``kern.memorystatus_vm_pressure_level`` reports Critical (4)."""
186
+ level = facts["ram"].get("pressure_level")
187
+ return level is not None and level not in (PRESSURE_NORMAL, PRESSURE_WARN)
188
+
189
+
190
+ def wired_headroom_bytes(facts: HostFacts) -> int:
191
+ """Hard Metal wired headroom ceiling for new allocations:
192
+ ``min((wired_ceiling - gpu_in_use) * WIRED_HEADROOM_SAFETY_FRACTION, physical_safety_cap)``,
193
+ or 0 off Apple Silicon or under Critical VM memory pressure."""
194
+ if not supported(facts) or is_critical_pressure(facts):
195
+ return 0
196
+ ceiling = wired_ceiling_bytes(facts)
197
+ in_use = gpu_in_use_bytes(facts)
198
+ wired_room = int(max(0, ceiling - in_use) * WIRED_HEADROOM_SAFETY_FRACTION)
199
+ total = int(facts["ram"]["total_bytes"])
200
+ wired_ram = facts["ram"].get("wired_bytes")
201
+ if wired_ram is not None and wired_ram >= 0:
202
+ phys_cap = max(0, total - int(wired_ram) - HARD_OS_FLOOR_BYTES)
203
+ else:
204
+ phys_cap = max(0, total - HOST_KEEP_BYTES)
205
+ return min(wired_room, phys_cap)
206
+
207
+
208
+ def inactive_anon_bytes(facts: HostFacts) -> int:
209
+ """Inactive anonymous memory in bytes from ``facts['ram']`` when present, else 0."""
210
+ ram = facts["ram"]
211
+ direct = ram.get("inactive_anon_bytes")
212
+ if direct is not None and direct >= 0:
213
+ return int(direct)
214
+ req = (
215
+ "active_bytes",
216
+ "inactive_bytes",
217
+ "file_backed_bytes",
218
+ "anonymous_bytes",
219
+ "purgeable_bytes",
220
+ )
221
+ if all(ram.get(k) is not None for k in req):
222
+ active = max(0, int(ram["active_bytes"]))
223
+ inactive = max(0, int(ram["inactive_bytes"]))
224
+ speculative = max(0, int(ram.get("speculative_bytes") or 0))
225
+ file_backed = max(0, int(ram["file_backed_bytes"]))
226
+ anonymous = max(0, int(ram["anonymous_bytes"]))
227
+ purgeable = max(0, int(ram["purgeable_bytes"]))
228
+ non_purgeable_anon = max(0, anonymous - purgeable)
229
+ upper = min(inactive, non_purgeable_anon)
230
+ lower = min(upper, max(0, inactive - max(0, file_backed - speculative) - purgeable))
231
+ if active + inactive > 0:
232
+ est = int(non_purgeable_anon * (inactive / (active + inactive)))
233
+ return max(lower, min(upper, est))
234
+ return upper
235
+ return 0
236
+
237
+
238
+ def reclaimable_inactive_anon_bytes(facts: HostFacts) -> int:
239
+ """Estimated compressible/reclaimable share of inactive anonymous pages on macOS.
240
+ Zero when pressure is Critical or when no inactive anonymous breakdown was probed."""
241
+ if is_critical_pressure(facts):
242
+ return 0
243
+ anon = inactive_anon_bytes(facts)
244
+ if anon <= 0:
245
+ return 0
246
+ level = facts["ram"].get("pressure_level")
247
+ factor = INACTIVE_ANON_RECLAIM_WARN if level == PRESSURE_WARN else INACTIVE_ANON_RECLAIM_NORMAL
248
+ raw = int(anon * factor)
249
+ ram = facts["ram"]
250
+ total = int(ram["total_bytes"])
251
+ avail = int(ram["available_bytes"])
252
+ wired = ram.get("wired_bytes")
253
+ compressed = ram.get("compressed_bytes")
254
+ if wired is not None and wired >= 0:
255
+ hard_used = int(wired) + max(0, int(compressed or 0)) + HARD_OS_FLOOR_BYTES
256
+ max_avail = max(0, total - hard_used)
257
+ else:
258
+ max_avail = max(0, total - HOST_KEEP_BYTES)
259
+ return min(raw, max(0, max_avail - avail))
260
+
261
+
262
+ def soft_host_keep_bytes(facts: HostFacts) -> int:
263
+ """Soft host/gateway RAM reserve for library admission: 1 GiB on <=16 GiB Macs, 2 GiB above."""
264
+ total = int(facts["ram"]["total_bytes"])
265
+ return SMALL_HOST_KEEP_BYTES if 0 < total <= SMALL_HOST_THRESHOLD_BYTES else HOST_KEEP_BYTES
266
+
267
+
268
+ def soft_available_bytes(facts: HostFacts) -> int:
269
+ """Soft available unified memory: ``pressured`` available bytes plus reclaimable inactive
270
+ anonymous headroom (0 under Critical pressure)."""
271
+ if is_critical_pressure(facts):
272
+ return 0
273
+ pressured_facts, _ = pressured(facts)
274
+ base_avail = int(pressured_facts["ram"]["available_bytes"])
275
+ reclaim = reclaimable_inactive_anon_bytes(facts)
276
+ return min(int(facts["ram"]["total_bytes"]), base_avail + reclaim)
277
+
278
+
138
279
  def assumed_total(facts: HostFacts) -> int | None:
139
280
  """The unified memory ``assume`` priced these facts at; None for a reading of this Mac."""
140
281
  found = reading(facts)
@@ -22,6 +22,19 @@ from typing import Any
22
22
 
23
23
  OBJC = "/usr/lib/libobjc.A.dylib"
24
24
  METAL = "/System/Library/Frameworks/Metal.framework/Metal"
25
+ _LAST_VM_DETAILS: dict[str, int] = {}
26
+
27
+
28
+ def last_vm_details() -> dict[str, int]:
29
+ """Return the vm_stat byte breakdown recorded by the latest ``available_memory`` call."""
30
+ return dict(_LAST_VM_DETAILS)
31
+
32
+
33
+ def ram_status() -> dict[str, int]:
34
+ """Pop recorded vm_stat breakdown and merge sysctl pressure/swap status for ``probe.collect``."""
35
+ details = dict(_LAST_VM_DETAILS)
36
+ _LAST_VM_DETAILS.clear()
37
+ return {**details, **memory_status()}
25
38
 
26
39
 
27
40
  def available_memory(total_text: str, vm_stat: str) -> tuple[int, int]:
@@ -49,9 +62,163 @@ def available_memory(total_text: str, vm_stat: str) -> tuple[int, int]:
49
62
  available = sum(n for n in pages if n is not None) * int(page[1])
50
63
  if total <= 0 or int(page[1]) <= 0 or available > total:
51
64
  raise OSError("RAM measurement unavailable")
65
+ _LAST_VM_DETAILS.clear()
66
+ _LAST_VM_DETAILS.update(parse_vm_stat_details(vm_stat))
52
67
  return total, available
53
68
 
54
69
 
70
+ def _vm_stat_counts(vm_stat: str) -> tuple[int, dict[str, int]] | None:
71
+ """Parse page size and integer page counts from macOS ``vm_stat`` output."""
72
+ page = re.search(r"page size of (\d+) bytes\)", vm_stat)
73
+ if not page:
74
+ return None
75
+ page_size = int(page[1])
76
+ if page_size <= 0:
77
+ return None
78
+ counts: dict[str, int] = {}
79
+ for match in re.finditer(
80
+ r"^([A-Za-z][A-Za-z0-9 -]+):[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE
81
+ ):
82
+ counts[match[1]] = int(match[2])
83
+ return page_size, counts
84
+
85
+
86
+ def parse_vm_stat_details(vm_stat: str) -> dict[str, int]:
87
+ """Byte breakdown of macOS ``vm_stat`` counters, including estimated inactive anonymous memory.
88
+
89
+ Returns an empty dict when ``vm_stat`` is unreadable. Inactive anonymous pages are bounded
90
+ between ``min(upper, max(0, inactive - max(0, file_backed - speculative) - purgeable))`` and
91
+ ``upper = min(inactive, max(0, anonymous - purgeable))``, estimated proportionally by the
92
+ inactive share of active+inactive paged memory without double-counting purgeable pages.
93
+ """
94
+ parsed = _vm_stat_counts(vm_stat)
95
+ if parsed is None:
96
+ return {}
97
+ page_size, counts = parsed
98
+ mapping = {
99
+ "Pages free": "free_bytes",
100
+ "Pages active": "active_bytes",
101
+ "Pages inactive": "inactive_bytes",
102
+ "Pages speculative": "speculative_bytes",
103
+ "Pages wired down": "wired_bytes",
104
+ "Pages purgeable": "purgeable_bytes",
105
+ "File-backed pages": "file_backed_bytes",
106
+ "Anonymous pages": "anonymous_bytes",
107
+ "Pages occupied by compressor": "compressed_bytes",
108
+ }
109
+ details = {key: counts[label] * page_size for label, key in mapping.items() if label in counts}
110
+ req = (
111
+ "Pages active",
112
+ "Pages inactive",
113
+ "File-backed pages",
114
+ "Anonymous pages",
115
+ "Pages purgeable",
116
+ )
117
+ if all(label in counts for label in req):
118
+ active = counts["Pages active"]
119
+ inactive = counts["Pages inactive"]
120
+ speculative = counts.get("Pages speculative", 0)
121
+ file_backed = counts["File-backed pages"]
122
+ anonymous = counts["Anonymous pages"]
123
+ purgeable = counts["Pages purgeable"]
124
+ non_purgeable_anon = max(0, anonymous - purgeable)
125
+ upper = min(inactive, non_purgeable_anon)
126
+ lower = min(upper, max(0, inactive - max(0, file_backed - speculative) - purgeable))
127
+ if active + inactive > 0:
128
+ est = int(non_purgeable_anon * (inactive / (active + inactive)))
129
+ inactive_anon = max(lower, min(upper, est))
130
+ else:
131
+ inactive_anon = upper
132
+ details["inactive_anon_bytes"] = inactive_anon * page_size
133
+ return details
134
+
135
+
136
+ def vm_memory_details() -> dict[str, int]:
137
+ """Read macOS ``vm_stat`` breakdown; returns empty dict off macOS or on error."""
138
+ try:
139
+ result = subprocess.run(
140
+ ["/usr/bin/vm_stat"],
141
+ capture_output=True,
142
+ text=True,
143
+ timeout=10,
144
+ check=False,
145
+ )
146
+ if result.returncode:
147
+ return {}
148
+ return parse_vm_stat_details(result.stdout)
149
+ except (OSError, ValueError, subprocess.TimeoutExpired):
150
+ return {}
151
+
152
+
153
+ def parse_wired_limit_mb(text: str) -> int | None:
154
+ """Parse ``sysctl -n iogpu.wired_limit_mb`` into bytes; None when 0, unset, or invalid."""
155
+ try:
156
+ mb = int(text.strip())
157
+ except ValueError:
158
+ return None
159
+ return (mb << 20) if mb > 0 else None
160
+
161
+
162
+ def wired_limit_bytes() -> int | None:
163
+ """Read ``iogpu.wired_limit_mb`` in bytes when set (> 0), else None."""
164
+ try:
165
+ result = subprocess.run(
166
+ ["/usr/sbin/sysctl", "-n", "iogpu.wired_limit_mb"],
167
+ capture_output=True,
168
+ text=True,
169
+ timeout=10,
170
+ check=False,
171
+ )
172
+ if result.returncode:
173
+ return None
174
+ return parse_wired_limit_mb(result.stdout)
175
+ except (OSError, ValueError, subprocess.TimeoutExpired):
176
+ return None
177
+
178
+
179
+ def parse_agx_in_use_bytes(text: str) -> int | None:
180
+ """Parse live AGXAccelerator ``In use system memory`` bytes from ``ioreg`` output."""
181
+ matches = [int(m) for m in re.findall(r'"In use system memory"\s*=\s*(\d+)', text)]
182
+ return max(matches) if matches else None
183
+
184
+
185
+ def agx_in_use_bytes() -> int | None:
186
+ """Read live system-wide Apple GPU wired usage via ``ioreg -r -c AGXAccelerator``."""
187
+ try:
188
+ result = subprocess.run(
189
+ ["/usr/sbin/ioreg", "-r", "-c", "AGXAccelerator"],
190
+ capture_output=True,
191
+ text=True,
192
+ timeout=10,
193
+ check=False,
194
+ )
195
+ if result.returncode:
196
+ return None
197
+ return parse_agx_in_use_bytes(result.stdout)
198
+ except (OSError, ValueError, subprocess.TimeoutExpired):
199
+ return None
200
+
201
+
202
+ def metal_telemetry() -> dict[str, int]:
203
+ """Optional Apple Silicon wired-limit and AGX live-usage telemetry for ``facts['metal']``."""
204
+ found: dict[str, int] = {}
205
+ wired = wired_limit_bytes()
206
+ if wired is not None:
207
+ found["wired_limit_bytes"] = wired
208
+ in_use = agx_in_use_bytes()
209
+ if in_use is not None:
210
+ found["gpu_in_use_bytes"] = in_use
211
+ return found
212
+
213
+
214
+ def metal_device_with_telemetry() -> dict[str, Any] | None:
215
+ """Read ``metal_device()`` and attach available wired-limit/AGX telemetry when present."""
216
+ device = metal_device()
217
+ if device is not None:
218
+ device.update(metal_telemetry())
219
+ return device
220
+
221
+
55
222
  def memory_status() -> dict[str, int]:
56
223
  """Missing sysctl readings stay unknown, not zero pressure or zero swap."""
57
224
  values = {}
@@ -325,7 +325,10 @@ def service_name(base_dir: str, name: str) -> str:
325
325
 
326
326
 
327
327
  def _same_dir(a: str, b: str) -> bool:
328
- return os.path.normpath(os.path.expanduser(a)) == os.path.normpath(os.path.expanduser(b))
328
+ def norm(path: str) -> str:
329
+ return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
330
+
331
+ return norm(a) == norm(b)
329
332
 
330
333
 
331
334
  def resolved_name(model_id: str, port: int, base_dir: str, taken: Mapping[str, str]) -> str:
@@ -712,9 +712,9 @@ def collect(
712
712
  "python": platform.python_version(),
713
713
  "cpu": {"model": _cpu_model(), "logical_cores": os.cpu_count()},
714
714
  "ram": {
715
+ **(metal_probe.ram_status() if sys.platform == "darwin" else {}),
715
716
  "total_bytes": ram_total,
716
717
  "available_bytes": ram_avail,
717
- **(metal_probe.memory_status() if sys.platform == "darwin" else {}),
718
718
  },
719
719
  "gpu_vendor_class": vendor,
720
720
  "nvidia": nvidia,
@@ -730,7 +730,7 @@ def collect(
730
730
  "shared_libraries": shared_libraries() if is_linux else {},
731
731
  }
732
732
  if facts["platform"] == "darwin" and facts["arch"] == "arm64":
733
- facts["metal"] = metal_probe.metal_device()
733
+ facts["metal"] = metal_probe.metal_device_with_telemetry()
734
734
  if facts["platform"] == "win32" and gpus and (gpu_procs := win_probe.gpu_process_memory()):
735
735
  facts["gpu_processes"] = gpu_procs
736
736
  return facts