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

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 (113) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +105 -98
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +104 -43
  5. package/modules/localmodels/app.py +1 -1
  6. package/modules/localmodels/apple_sensors.py +431 -0
  7. package/modules/localmodels/bifrost_admin.py +83 -8
  8. package/modules/localmodels/bifrost_checks.py +2 -2
  9. package/modules/localmodels/bifrost_config.py +235 -13
  10. package/modules/localmodels/bifrost_log.py +166 -0
  11. package/modules/localmodels/bifrost_models.py +1 -1
  12. package/modules/localmodels/budget.py +1 -1
  13. package/modules/localmodels/catalog.json +192 -77
  14. package/modules/localmodels/catalog.py +20 -3
  15. package/modules/localmodels/catalog_add.py +42 -11
  16. package/modules/localmodels/custom_hub.py +983 -0
  17. package/modules/localmodels/custom_hub_http.py +579 -0
  18. package/modules/localmodels/custom_probe.py +451 -0
  19. package/modules/localmodels/deploy.py +27 -5
  20. package/modules/localmodels/deploy_steps.py +5 -0
  21. package/modules/localmodels/download-mirrors.json +8 -0
  22. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  23. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  24. package/modules/localmodels/engines.py +38 -8
  25. package/modules/localmodels/estimator.py +60 -7
  26. package/modules/localmodels/frontend.py +26 -21
  27. package/modules/localmodels/gateway.py +48 -3
  28. package/modules/localmodels/gateway_app_bifrost.py +4 -4
  29. package/modules/localmodels/gateway_bifrost.py +128 -21
  30. package/modules/localmodels/gguf.py +6 -0
  31. package/modules/localmodels/host_sensors.py +704 -0
  32. package/modules/localmodels/hosts.py +99 -12
  33. package/modules/localmodels/library_cli.py +181 -3
  34. package/modules/localmodels/library_convert.py +34 -0
  35. package/modules/localmodels/library_custom.py +831 -0
  36. package/modules/localmodels/library_elastic.py +182 -127
  37. package/modules/localmodels/library_gateway.py +193 -40
  38. package/modules/localmodels/library_jobs.py +92 -18
  39. package/modules/localmodels/library_kept.py +50 -6
  40. package/modules/localmodels/library_model.py +254 -2
  41. package/modules/localmodels/library_pricing.py +97 -8
  42. package/modules/localmodels/library_serve.py +196 -66
  43. package/modules/localmodels/library_smoke.py +315 -0
  44. package/modules/localmodels/library_state.py +81 -2
  45. package/modules/localmodels/library_status.py +144 -8
  46. package/modules/localmodels/metal.py +1 -1
  47. package/modules/localmodels/metal_probe.py +4 -4
  48. package/modules/localmodels/nvml_ctypes.py +431 -0
  49. package/modules/localmodels/plan_envelope.py +18 -7
  50. package/modules/localmodels/process_identity_linux.py +39 -0
  51. package/modules/localmodels/records.py +1 -0
  52. package/modules/localmodels/remote_ops.py +57 -8
  53. package/modules/localmodels/remote_ops_download.py +205 -53
  54. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  55. package/modules/localmodels/remote_ops_ranges.py +2 -5
  56. package/modules/localmodels/remote_ops_service.py +95 -37
  57. package/modules/localmodels/remote_ops_verify.py +22 -5
  58. package/modules/localmodels/runtime-lock.json +19 -19
  59. package/modules/localmodels/runtime_auth.py +4 -1
  60. package/modules/localmodels/service_control.py +32 -1
  61. package/modules/localmodels/service_wiring.py +237 -12
  62. package/modules/localmodels/service_worker.py +6 -2
  63. package/modules/localmodels/services_cli.py +35 -27
  64. package/modules/localmodels/setup_inspection.py +47 -70
  65. package/modules/localmodels/setup_inspection_harness.py +159 -15
  66. package/modules/localmodels/setup_text.py +14 -0
  67. package/modules/localmodels/setup_upgrade.py +1 -1
  68. package/modules/localmodels/source_byok.py +9 -7
  69. package/modules/localmodels/source_byok_probe.py +6 -1
  70. package/modules/localmodels/stack.py +9 -1
  71. package/modules/localmodels/stack_binding.py +3 -35
  72. package/modules/localmodels/stack_cleanup.py +4 -0
  73. package/modules/localmodels/stack_compose.py +18 -2
  74. package/modules/localmodels/stack_lifecycle.py +26 -3
  75. package/modules/localmodels/stack_memory.py +1 -0
  76. package/modules/localmodels/stack_plan.py +6 -2
  77. package/modules/localmodels/stack_ports.py +2 -0
  78. package/modules/localmodels/stack_remove.py +10 -1
  79. package/modules/localmodels/stack_up.py +33 -7
  80. package/modules/localmodels/stack_update.py +3 -1
  81. package/modules/localmodels/stack_view.py +77 -53
  82. package/modules/localmodels/stack_view_demo.py +36 -5
  83. package/modules/localmodels/stack_view_events.py +147 -12
  84. package/modules/localmodels/stack_view_gpu.py +97 -17
  85. package/modules/localmodels/stack_view_llm.py +15 -0
  86. package/modules/localmodels/stack_view_measure.py +4 -1
  87. package/modules/localmodels/stack_view_schema.py +54 -8
  88. package/modules/localmodels/stack_view_serve.py +40 -3
  89. package/modules/localmodels/stack_view_slots.py +89 -10
  90. package/modules/localmodels/stack_view_telemetry.py +163 -0
  91. package/modules/localmodels/stack_view_text.py +5 -2
  92. package/modules/localmodels/stack_view_tick.py +658 -0
  93. package/modules/localmodels/stack_view_words.py +4 -0
  94. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  95. package/modules/localmodels/suite.py +45 -27
  96. package/modules/localmodels/telemetry_math.py +538 -0
  97. package/modules/localmodels/transport.py +13 -2
  98. package/modules/localmodels/web/view/view.js +1 -1
  99. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
  100. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +102 -95
  101. package/package.json +1 -1
  102. package/tool.json +1 -1
  103. package/modules/localmodels/bifrost_datasheet.py +0 -53
  104. package/modules/localmodels/bifrost_provider.py +0 -88
  105. package/modules/localmodels/bifrost_unit.py +0 -99
  106. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  107. package/modules/localmodels/gateway_switch.py +0 -51
  108. package/modules/localmodels/library_floor.py +0 -78
  109. package/modules/localmodels/service_stop.py +0 -52
  110. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
  111. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
  112. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
  113. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -13,10 +13,10 @@ from typing import TypedDict
13
13
 
14
14
  from localmodels import (
15
15
  bifrost_checks,
16
- bifrost_unit,
17
16
  console,
18
17
  deploy,
19
18
  gateway,
19
+ gateway_bifrost,
20
20
  gateway_probe,
21
21
  gateway_speed,
22
22
  harness,
@@ -69,6 +69,25 @@ def _run(argv: list[str]) -> str:
69
69
  return out.stdout.strip() if out.returncode == 0 else ""
70
70
 
71
71
 
72
+ def _systemd_unit_elsewhere(plan: Plan) -> bool:
73
+ """True when the systemd unit for ``plan`` runs another deployment's script or loads from
74
+ another unit file, so status/doctor/deployment_pids never impersonate another install."""
75
+ svc = plan["service"]
76
+ unit = f"{svc['name']}.service"
77
+ unit_path = Path(os.path.expanduser(f"~/.config/systemd/user/{unit}"))
78
+ script = str(Path(os.path.expanduser(svc["deploy_dir"])) / "run.sh")
79
+ if unit_path.is_symlink():
80
+ return True
81
+ try:
82
+ text = unit_path.read_text(encoding="utf-8")
83
+ except OSError:
84
+ text = None
85
+ if text is not None and f"\nExecStart={script}\n" not in text:
86
+ return True
87
+ fragment = _run(["systemctl", "--user", "show", "-p", "FragmentPath", "--value", unit])
88
+ return bool(fragment and Path(fragment).resolve() != unit_path.resolve())
89
+
90
+
72
91
  def _service(plan: Plan) -> tuple[str, int | None]:
73
92
  if not sys.platform.startswith("linux") and sys.platform not in ("darwin", "win32"):
74
93
  return "unknown", None
@@ -76,6 +95,8 @@ def _service(plan: Plan) -> tuple[str, int | None]:
76
95
  if svc["kind"] == "launchd-user":
77
96
  return remote_ops_launchd.status(svc["deploy_dir"])
78
97
  if svc["kind"] == "systemd-user":
98
+ if _systemd_unit_elsewhere(plan):
99
+ return "inactive", None
79
100
  unit = f"{svc['name']}.service"
80
101
  state = harness.run_tool(["systemctl", "--user", "is-active", unit], timeout=10)
81
102
  pid = _run(["systemctl", "--user", "show", "-p", "MainPID", "--value", unit])
@@ -269,7 +290,7 @@ def _owned_lines(doc: hosts.Owned) -> list[str]:
269
290
  if gw["started"]:
270
291
  lines.append(f"gateway started by this tool ({gw['started']})")
271
292
  if bifrost := gw.get("bifrost"):
272
- unit = bifrost_unit.unit(bifrost)
293
+ unit = gateway_bifrost.unit(bifrost)
273
294
  how = f"systemd --user {unit}" if bifrost["how"] == "unit" else "background"
274
295
  lines.append(
275
296
  f"Bifrost gateway {bifrost['addr']} ({how}), config and logs in {bifrost['app_dir']}"
@@ -374,7 +395,9 @@ def service_remove(
374
395
  params["purge"] = [path for path, _, _ in found]
375
396
  result = _act(executor, params)
376
397
  if result.get("event") == "result":
377
- hosts.delete_record(dev_id, name, purged=purge)
398
+ hosts.delete_record(
399
+ dev_id, name, purged=purge, deploy_dir=record["plan"]["service"]["deploy_dir"]
400
+ )
378
401
  return result
379
402
 
380
403
 
@@ -242,6 +242,7 @@ def price(subject: Subject, posture: Posture, context: int, *, metal_host: bool)
242
242
  kv_types=posture.kv_types,
243
243
  ubatch=posture.ubatch,
244
244
  mtp=posture.mtp,
245
+ unified=posture.shared,
245
246
  )
246
247
  )
247
248
  mode = posture.vision
@@ -544,8 +544,12 @@ def own_name(model_id: str, port: int, base_dir: str) -> str:
544
544
 
545
545
 
546
546
  def is_redeploy(plan: Plan) -> bool:
547
- """A deployment directory with this plan's name is a previous run of the same component."""
548
- return Path(os.path.expanduser(plan["service"]["deploy_dir"]), "deployment.json").is_file()
547
+ """A deployment directory with this plan's name is a previous run of the same component,
548
+ provided another live controller deployment does not already own its port."""
549
+ svc = plan["service"]
550
+ if hosts.port_owned_elsewhere(svc["port"], svc["deploy_dir"]):
551
+ return False
552
+ return Path(os.path.expanduser(svc["deploy_dir"]), "deployment.json").is_file()
549
553
 
550
554
 
551
555
  def reuse_copies(
@@ -103,6 +103,8 @@ def failed_own_port(model_ids: Sequence[str], base_dir: str) -> int | None:
103
103
  continue
104
104
  if record["ok"] or not (directory / "deployment.json").is_file():
105
105
  return None
106
+ if hosts.port_owned_elsewhere(int(service["port"]), service["deploy_dir"]):
107
+ return None
106
108
  return int(service["port"])
107
109
  return None
108
110
 
@@ -187,7 +187,9 @@ def remove_services(
187
187
  {"check": name, "ok": ok, "detail": done if ok else str(result.get("message"))}
188
188
  )
189
189
  if ok:
190
- hosts.delete_record(hosts.LOCAL_ID, name, purged=not kept)
190
+ hosts.delete_record(
191
+ hosts.LOCAL_ID, name, purged=not kept, deploy_dir=entry["deploy_dir"]
192
+ )
191
193
  return checks
192
194
 
193
195
 
@@ -332,6 +334,13 @@ def run_remove(
332
334
  serve_log = str(hosts.owned_path().parent / "magpie-serve.log")
333
335
  keep = in_use(hosts.records(hosts.LOCAL_ID), selected)
334
336
  keep |= {f for n, d in doc["deployments"].items() if n not in selected for f in d["files"]}
337
+ keep |= {
338
+ f
339
+ for n, d in hosts.load_owned()["deployments"].items()
340
+ if not d["removed"]
341
+ and (n not in entries or not hosts._same_place(d["deploy_dir"], entries[n]["deploy_dir"]))
342
+ for f in d["files"]
343
+ }
335
344
  found = list_files(executor, entries, plans, keep, purge, act=act)
336
345
  found += stack_cleanup.local_listing(
337
346
  [*doc["archives"], serve_log, *([str(profile)] if profile else [])]
@@ -83,12 +83,26 @@ def _accepted(plan_id: str | None = None) -> StackPlan | None:
83
83
  return None
84
84
 
85
85
 
86
- def drift(plan: StackPlan) -> list[str]:
87
- """Why the deployments on this computer are no longer ``plan``'s; empty: they are."""
86
+ def library_parts(plan: StackPlan) -> set[str]:
87
+ """The deployment names of ``plan``'s LLMs the model library adopted (the rule setup binding
88
+ uses, library_convert.adopted_components): the library loads, unloads and removes them, so
89
+ ``library unload`` (Linger runs it on quit and before a kit update) deletes their records. They are the library's to start, not ``stack
90
+ up``'s, and their records missing is not drift."""
91
+ from localmodels import library_convert, stack_verify
92
+
93
+ adopted = library_convert.adopted_components(plan)
94
+ return {part["name"] for component, part in stack_verify.parts(plan) if component in adopted}
95
+
96
+
97
+ def drift(plan: StackPlan, library: set[str] | frozenset[str] = frozenset()) -> list[str]:
98
+ """Why the deployments on this computer are no longer ``plan``'s; empty: they are. Parts in
99
+ ``library`` (library_parts) are not checked."""
88
100
  records = {r["plan"]["name"]: r for r in hosts.records(hosts.LOCAL_ID)}
89
101
  owned = hosts.load_owned(plan["harness"]["tools_dir"])["deployments"]
90
102
  found = []
91
103
  for part in deployments(plan):
104
+ if part["name"] in library:
105
+ continue
92
106
  record, entry = records.get(part["name"]), owned.get(part["name"])
93
107
  if record is None or (entry is not None and entry["removed"]):
94
108
  found.append(f"{part['name']} was removed")
@@ -211,7 +225,8 @@ def up(
211
225
  ) -> UpReport:
212
226
  if sys.platform != "darwin" and (error := platform_error(sys.platform)):
213
227
  raise StackError(error)
214
- if moved := drift(plan):
228
+ library = library_parts(plan)
229
+ if moved := drift(plan, library):
215
230
  raise StackError(
216
231
  "the deployments on this computer no longer match this plan ("
217
232
  + ", ".join(moved)
@@ -219,7 +234,7 @@ def up(
219
234
  )
220
235
  try:
221
236
  with hosts.stack_apply_lock():
222
- report = _up(plan, share_gpu, timeout, out)
237
+ report = _up(plan, share_gpu, timeout, out, library)
223
238
  except hosts.LockedError as exc:
224
239
  raise StackError("another stack apply is running") from exc
225
240
  if report["ok"]:
@@ -227,9 +242,20 @@ def up(
227
242
  return report
228
243
 
229
244
 
230
- def _up(plan: StackPlan, share_gpu: bool, timeout: float, out: Out) -> UpReport:
231
- parts = deployments(plan) # the LLM first: Strata sizes its expert cache on an empty card
232
- notes: list[str] = []
245
+ def _up(
246
+ plan: StackPlan,
247
+ share_gpu: bool,
248
+ timeout: float,
249
+ out: Out,
250
+ library: set[str] | frozenset[str] = frozenset(),
251
+ ) -> UpReport:
252
+ # The LLM first: Strata sizes its expert cache on an empty card.
253
+ parts = [p for p in deployments(plan) if p["name"] not in library]
254
+ notes: list[str] = [
255
+ f"{name} belongs to the model library, which loads it (library load or source apply); "
256
+ "stack up does not start it"
257
+ for name in sorted(library)
258
+ ]
233
259
  if outside := plan["decision_existing"]:
234
260
  notes.append(
235
261
  f"the decision model uses the external service {outside['url']}, "
@@ -432,7 +432,9 @@ def retire(names: list[str]) -> list[str]:
432
432
  hosts.own_deployment(record["plan"]) # a record from before the manifest
433
433
  result = remove(lifecycle.plan_params(record["plan"]))
434
434
  if result.get("event") == "result":
435
- hosts.delete_record(hosts.LOCAL_ID, name)
435
+ hosts.delete_record(
436
+ hosts.LOCAL_ID, name, deploy_dir=record["plan"]["service"]["deploy_dir"]
437
+ )
436
438
  done.append(f"retired {name} (model and logs kept)")
437
439
  else:
438
440
  failed.append(f"{name}: {str(result.get('message') or 'remove failed')[:200]}")
@@ -3,11 +3,11 @@ memory goes, which component serves what, how fast the LLM reads a prompt (prefi
3
3
  (decode), and how a request travels from a client through the gateway to the models.
4
4
 
5
5
  The terminal, the web page and the app window all draw the same ``localmodels.stack-view/v1``
6
- document; none of them plans, approves or changes anything. Every figure names what it rests
7
- on (``basis``): ``live`` is the service's own ``/metrics`` or the gateway's request log,
8
- ``measured`` a reading here or a retained measurement made elsewhere, ``estimate`` the planner's
9
- arithmetic, ``demo`` the synthetic picture ``--demo`` draws. An estimate never stands in for a
10
- measurement.
6
+ document (additively extended to v1.1 telemetry); none of them plans, approves or changes anything.
7
+ Every figure names what it rests on (``basis``): ``live`` is the service's own ``/metrics`` or the
8
+ gateway's request log, ``measured`` a reading here or a retained measurement made elsewhere,
9
+ ``estimate`` the planner's arithmetic, ``demo`` the synthetic picture ``--demo`` draws. An estimate
10
+ never stands in for a measurement.
11
11
 
12
12
  ``read_live`` gathers a ``Reading`` from this computer (the hardware probe, the latest applied
13
13
  stack plan, each owned service's state and metrics, the gateway's recent calls); ``render``
@@ -23,6 +23,7 @@ from typing import Any, cast
23
23
 
24
24
  from localmodels import (
25
25
  app,
26
+ host_sensors,
26
27
  hosts,
27
28
  metal,
28
29
  stack_lifecycle,
@@ -30,17 +31,21 @@ from localmodels import (
30
31
  stack_view_events,
31
32
  stack_view_gpu,
32
33
  stack_view_slots,
34
+ stack_view_telemetry,
35
+ telemetry_math,
33
36
  )
34
37
  from localmodels import catalog as cat
35
38
  from localmodels import stack_hardware as hardware
36
39
  from localmodels import stack_journal as journal
37
40
  from localmodels import stack_view_apply as running
38
41
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES, HardwareBudget
42
+ from localmodels.host_sensors import HostSensors
39
43
  from localmodels.records import Plan
40
44
  from localmodels.stack_compose import agent_posture
41
45
  from localmodels.stack_plan import Hardware, StackPlan, default_options
42
46
  from localmodels.stack_view_events import Event
43
47
  from localmodels.stack_view_gpu import GpuLoad
48
+ from localmodels.stack_view_llm import active_weight_bytes as active_weight_bytes
44
49
  from localmodels.stack_view_llm import catalog_entry as catalog_entry
45
50
  from localmodels.stack_view_llm import llm_parts as llm_parts
46
51
  from localmodels.stack_view_measure import Measured, measure, measured_rows
@@ -48,6 +53,7 @@ from localmodels.stack_view_measure import MeasuredRow as MeasuredRow
48
53
  from localmodels.stack_view_schema import GIB as GIB
49
54
  from localmodels.stack_view_schema import METRICS_BYTES as METRICS_BYTES
50
55
  from localmodels.stack_view_schema import SCHEMA as SCHEMA
56
+ from localmodels.stack_view_schema import SCHEMA_VERSION as SCHEMA_VERSION
51
57
  from localmodels.stack_view_schema import TASKS as TASKS
52
58
  from localmodels.stack_view_schema import Client as Client
53
59
  from localmodels.stack_view_schema import Component as Component
@@ -67,6 +73,7 @@ from localmodels.stack_view_schema import WhatIf as WhatIf
67
73
  from localmodels.stack_view_schema import next_steps as next_steps
68
74
  from localmodels.stack_view_slots import Slot, owned_get
69
75
  from localmodels.stack_view_words import say
76
+ from localmodels.telemetry_math import WaterfallEntry
70
77
 
71
78
 
72
79
  def now() -> str:
@@ -77,35 +84,19 @@ def _int(value: object) -> int:
77
84
  return int(value) if isinstance(value, int | float) and not isinstance(value, bool) else 0
78
85
 
79
86
 
80
- def _figure(value: float | None, basis: str, note: str) -> Figure:
81
- if value is None or not math.isfinite(value) or value <= 0:
87
+ def _figure(value: float | None, basis: str, note: str, *, allow_zero: bool = False) -> Figure:
88
+ if value is None or not math.isfinite(value) or (value < 0 if allow_zero else value <= 0):
82
89
  return {"value": None, "basis": "none", "note": note}
83
90
  return {"value": round(value, 1), "basis": basis, "note": note}
84
91
 
85
92
 
86
93
  def parse_metrics(text: str) -> Counters | None:
87
- """llama-server's Prometheus page: each counter summed over its labels. None when the page
88
- is not llama.cpp's (Strata answers JSON, whisper-server has none)."""
89
- totals: dict[str, float] = {}
90
- for line in text.splitlines():
91
- if not line.startswith("llamacpp:"):
92
- continue
93
- name, _, rest = line.partition(" ")
94
- try:
95
- value = float(rest.split()[0])
96
- except (IndexError, ValueError):
97
- continue
98
- key = name.partition("{")[0].removeprefix("llamacpp:")
99
- totals[key] = totals.get(key, 0.0) + value
100
- if not totals:
101
- return None
102
- return {
103
- "prompt_tokens": totals.get("prompt_tokens_total", 0.0),
104
- "prompt_seconds": totals.get("prompt_seconds_total", 0.0),
105
- "predicted_tokens": totals.get("tokens_predicted_total", 0.0),
106
- "predicted_seconds": totals.get("tokens_predicted_seconds_total", 0.0),
107
- "processing": totals.get("requests_processing", 0.0),
108
- }
94
+ """llama-server or PolyStrata ``/metrics`` page: each counter summed over its labels.
95
+
96
+ Returns None when the page carries no recognized engine telemetry counters.
97
+ """
98
+ parsed = telemetry_math.parse_engine_metrics(text)
99
+ return cast(Counters, parsed) if parsed is not None else None
109
100
 
110
101
 
111
102
  def _rate(tokens: float, seconds: float) -> float | None:
@@ -177,16 +168,14 @@ def _perf(
177
168
  "counters": counters,
178
169
  }
179
170
  if counters is not None:
180
- perf["prefill_tok_s"] = _figure(
181
- _rate(counters["prompt_tokens"], counters["prompt_seconds"]),
182
- "live",
183
- say("fig.prefill.live"),
184
- )
185
- perf["decode_tok_s"] = _figure(
186
- _rate(counters["predicted_tokens"], counters["predicted_seconds"]),
187
- "live",
188
- say("fig.decode.live"),
189
- )
171
+ pre_rate = _rate(counters["prompt_tokens"], counters["prompt_seconds"])
172
+ if pre_rate is None and counters.get("prompt_tokens_seconds"):
173
+ pre_rate = counters.get("prompt_tokens_seconds")
174
+ dec_rate = _rate(counters["predicted_tokens"], counters["predicted_seconds"])
175
+ if dec_rate is None and counters.get("predicted_tokens_seconds"):
176
+ dec_rate = counters.get("predicted_tokens_seconds")
177
+ perf["prefill_tok_s"] = _figure(pre_rate, "live", say("fig.prefill.live"))
178
+ perf["decode_tok_s"] = _figure(dec_rate, "live", say("fig.decode.live"))
190
179
  if task in ("llm", "llm_fast"):
191
180
  perf["decode_bound"] = _decode_estimate(hw, part)
192
181
  if perf["decode_tok_s"]["value"] is None:
@@ -234,8 +223,6 @@ def _component(task: str, part: Plan, reading: Reading, ram: int) -> Component:
234
223
  state, health = _state(reading["liveness"].get(part["name"]))
235
224
  kv = launch.get("kv_types")
236
225
  plan = reading["plan"]
237
- # a decision model is named "alias (decision, GPU 0)"; plans saved before the English-only
238
- # CLI wrote the same suffix in fullwidth parentheses
239
226
  title = str(part["model"].get("display_name") or part["model"]["id"]).split("\uff08")[0]
240
227
  return {
241
228
  "id": task,
@@ -291,8 +278,6 @@ def _segment(
291
278
 
292
279
 
293
280
  def _shares(comp: Component, plan: StackPlan | None) -> list[Segment]:
294
- """A component's memory as segments: the LLM split into its parts when the catalog prices
295
- it, everything else one share."""
296
281
  if comp["id"] == "llm" and plan is not None and (parts := llm_parts(plan["llm"])):
297
282
  return [
298
283
  _segment(k, say(f"part.{k}"), v, "estimate", "llm", say(f"note.{k}"))
@@ -306,9 +291,6 @@ def _shares(comp: Component, plan: StackPlan | None) -> list[Segment]:
306
291
  def _rest(
307
292
  total: int, used: int, ours: int, running: int, reserve: int, basis: str
308
293
  ) -> list[Segment]:
309
- """Other programs (what is in use beyond this stack's running share), the reserve and what
310
- stays free once the planned components are in: an estimate when the stack plans or reserves
311
- anything here, else as measured as the use it is the rest of."""
312
294
  foreign = max(0, used - running)
313
295
  free = total - foreign - ours - reserve
314
296
  free_basis = "estimate" if ours or reserve else basis
@@ -374,7 +356,7 @@ def _ram_view(hw: Hardware, comps: list[Component], plan: StackPlan | None, basi
374
356
  serving = {c["id"] for c in comps if c["state"] == "serving"}
375
357
  order = [*TASKS, "harness"]
376
358
  segments: list[Segment] = []
377
- for comp in comps: # an LLM off the GPU: its parts, in place of the plan's host share
359
+ for comp in comps:
378
360
  if comp["id"] == "llm" and comp["gpu"] is None and comp["ram_bytes"]:
379
361
  segments += _shares(comp, plan)
380
362
  parts.pop("llm", None)
@@ -397,9 +379,8 @@ def _ram_view(hw: Hardware, comps: list[Component], plan: StackPlan | None, basi
397
379
  _RAM_KEYS = {f"ram.{key}" for key in (*TASKS, "harness")}
398
380
 
399
381
 
400
- def _what_if(plan: StackPlan, gpus: list[Gpu]) -> WhatIf | None:
401
- """The LLM's footprint as a line through the planned window and twice it, both priced by the
402
- estimator, so the slider moves along the planner's own numbers."""
382
+ def _what_if(plan: StackPlan, gpus: list[Gpu], hw: Hardware) -> WhatIf | None:
383
+ """The LLM's footprint + roofline coefficients so UI What-If forecasts need zero round-trips."""
403
384
  llm = plan["llm"]
404
385
  index, window = _gpu_of(llm), _int(llm["launch"].get("window"))
405
386
  here, there = llm_parts(llm), llm_parts(llm, 2 * window) if window else {}
@@ -413,6 +394,19 @@ def _what_if(plan: StackPlan, gpus: list[Gpu]) -> WhatIf | None:
413
394
  for s in card["segments"]
414
395
  if s["component"] not in (None, "llm") or s["kind"] in ("foreign", "reserve")
415
396
  )
397
+ hw_card = next((c for c in hw["cards"] if c["index"] == index), None)
398
+ uma = hw_card is not None and hw_card.get("uuid") == metal.METAL_UUID
399
+ active_bytes = active_weight_bytes(llm) or here.get("weights", 0)
400
+ bw_ceiling = telemetry_math.memory_bw_ceiling_gb_s(
401
+ cast(dict[str, Any], hw_card) if hw_card is not None else None
402
+ )["value"]
403
+ pcie_gb_s = (
404
+ None
405
+ if uma
406
+ else telemetry_math.pcie_bandwidth_gb_s(
407
+ str(hw_card.get("pcie") or "") if hw_card is not None else None
408
+ )
409
+ )
416
410
  return {
417
411
  "gpu": index,
418
412
  "window": window,
@@ -421,11 +415,17 @@ def _what_if(plan: StackPlan, gpus: list[Gpu]) -> WhatIf | None:
421
415
  "compute_bytes_per_token": compute,
422
416
  "fixed_bytes": int(sum(here.values()) - (kv + compute) * window),
423
417
  "room_bytes": max(0, card["total_bytes"] - others),
418
+ "active_weight_bytes": active_bytes,
419
+ "weights_bytes": here.get("weights", active_bytes),
420
+ "memory_bw_ceiling_gb_s": bw_ceiling,
421
+ "pcie_bandwidth_gb_s": pcie_gb_s,
422
+ "kv_dtype_factors": dict(telemetry_math.KV_DTYPE_FACTORS),
423
+ "pool_kind": "unified" if uma else "discrete",
424
+ "host_ram_available_bytes": hw["ram_available_bytes"],
424
425
  }
425
426
 
426
427
 
427
428
  def _clients(plan: StackPlan | None, owned: hosts.Owned | None) -> list[Client]:
428
- """The agent clients this tool pointed at the gateway: pi, then each native client."""
429
429
  found: list[Client] = []
430
430
  if owned and owned["pi"]:
431
431
  found.append({"id": "pi", "name": "pi", "model": owned["pi"]["model"]})
@@ -463,6 +463,8 @@ def render(reading: Reading) -> StackView:
463
463
  figure["basis"], figure["note"] = "demo", say("fig.demo")
464
464
  basis = "demo" if source == "demo" else "measured"
465
465
  gpus = [_gpu_view(cast(dict[str, object], c), comps, plan, basis) for c in hw["cards"]]
466
+ sensors = reading.get("sensors") or stack_view_telemetry.default_sensors(source)
467
+ telemetry = stack_view_telemetry.summary(reading, comps, gpus, sensors)
466
468
  gateway: Gateway | None = None
467
469
  if plan is not None:
468
470
  gw = plan["harness"]["gateway"]
@@ -470,6 +472,9 @@ def render(reading: Reading) -> StackView:
470
472
  "kind": str(plan["options"].get("gateway") or "magpie"),
471
473
  "addr": gw["addr"],
472
474
  "route": gw["pi_model"],
475
+ "in_flight": telemetry["in_flight"],
476
+ "client_lanes": telemetry["client_lanes"],
477
+ "p50_ttft_ms": telemetry["p50_ttft_ms"],
473
478
  }
474
479
  notes = [] if plan else [say("notes.empty")]
475
480
  if source == "demo":
@@ -477,6 +482,7 @@ def render(reading: Reading) -> StackView:
477
482
  notes += stack_view_events.alerts(comps)
478
483
  return {
479
484
  "schema": SCHEMA,
485
+ "schema_version": SCHEMA_VERSION,
480
486
  "generated_at": reading["generated_at"],
481
487
  "source": source if plan or source == "demo" else "empty",
482
488
  "lang": "en",
@@ -487,13 +493,24 @@ def render(reading: Reading) -> StackView:
487
493
  "components": comps,
488
494
  "gpus": gpus,
489
495
  "ram": _ram_view(hw, comps, plan, basis),
490
- "what_if": _what_if(plan, gpus) if plan else None,
496
+ "what_if": _what_if(plan, gpus, hw) if plan else None,
491
497
  "events": reading["events"], # every call the figures counted, so the page agrees
492
498
  "measured": measured_rows(comps, reading["measured"]),
493
499
  "notes": notes,
494
500
  "next_steps": [] if plan or source == "demo" else next_steps(),
495
501
  "apply": running.rows(reading["apply"], plan) if plan else None,
496
502
  "gpu_load": reading["gpu_load"],
503
+ "sensors": sensors,
504
+ "effective_decode_bw_gb_s": telemetry["effective_decode_bw_gb_s"],
505
+ "memory_bw_ceiling_gb_s": telemetry["memory_bw_ceiling_gb_s"],
506
+ "bottleneck": telemetry["bottleneck"],
507
+ "waterfall": telemetry["waterfall"],
508
+ "p50_ttft_ms": telemetry["p50_ttft_ms"],
509
+ "prefix_hit_pct": telemetry["prefix_hit_pct"],
510
+ "requests_deferred": telemetry["requests_deferred"],
511
+ "kv_cache_usage_ratio": telemetry["kv_cache_usage_ratio"],
512
+ "in_flight": telemetry["in_flight"],
513
+ "client_lanes": telemetry["client_lanes"],
497
514
  }
498
515
 
499
516
 
@@ -511,6 +528,8 @@ def reading(
511
528
  apply: journal.Live | None = None,
512
529
  gpu_load: list[GpuLoad] | None = None,
513
530
  slots: dict[str, list[Slot]] | None = None,
531
+ sensors: HostSensors | None = None,
532
+ waterfall: list[WaterfallEntry] | None = None,
514
533
  ) -> Reading:
515
534
  return {
516
535
  "hw": hw,
@@ -525,6 +544,8 @@ def reading(
525
544
  "apply": apply,
526
545
  "gpu_load": gpu_load or [],
527
546
  "slots": slots or {},
547
+ "sensors": sensors,
548
+ "waterfall": waterfall or [],
528
549
  }
529
550
 
530
551
 
@@ -571,8 +592,9 @@ def read_live(hw: Hardware | None = None) -> Reading:
571
592
  if plan and plan["options"].get("gateway", "magpie") == "magpie"
572
593
  else None
573
594
  )
574
- events = stack_view_events.read(owned, magpie) if plan else []
595
+ events, wf = stack_view_events.read_with_waterfall(owned, magpie) if plan else ([], [])
575
596
  held = measure(live, any(_gpu_of(p) is not None for p in live.values()))
597
+ sensors, _ = host_sensors.collect(liveness=liveness)
576
598
  return reading(
577
599
  hw,
578
600
  plan,
@@ -584,6 +606,8 @@ def read_live(hw: Hardware | None = None) -> Reading:
584
606
  apply=journal.live(),
585
607
  gpu_load=stack_view_gpu.read() if hw["cards"] else [],
586
608
  slots=slots,
609
+ sensors=sensors,
610
+ waterfall=wf,
587
611
  )
588
612
 
589
613
 
@@ -15,6 +15,7 @@ from localmodels import (
15
15
  component,
16
16
  gateway_bifrost,
17
17
  harness,
18
+ host_sensors,
18
19
  hosts,
19
20
  llm_rank,
20
21
  stack_view,
@@ -29,6 +30,7 @@ from localmodels.stack_plan import Hardware, StackPlan
29
30
  from localmodels.stack_view import Counters, Reading, StackView
30
31
  from localmodels.stack_view_events import Event
31
32
  from localmodels.stack_view_slots import Slot
33
+ from localmodels.telemetry_math import WaterfallEntry
32
34
 
33
35
  PLAN_FILE = Path(__file__).with_name("fixtures") / "stack-research-demo-plan.json"
34
36
  GIB = 1 << 30
@@ -62,7 +64,8 @@ def _fits(plan: StackPlan, budget: HardwareBudget) -> list[dict[str, object]]:
62
64
  return found
63
65
 
64
66
 
65
- DESKTOP_VRAM = 900 << 20 # the desktop session's share of the card
67
+ DESK_VRAM = 900 << 20 # the desktop session's share of the card
68
+ DESKTOP_VRAM = DESK_VRAM
66
69
  OS_RAM = 6 * GIB # the system, the desktop and its apps, the gateway and its clients
67
70
 
68
71
 
@@ -108,7 +111,7 @@ def hardware(plan: StackPlan, serving: set[str] | None = None) -> Hardware:
108
111
  "llm_bytes": usable,
109
112
  "decision_reserve_bytes": reserve,
110
113
  "bandwidth_gb_s": bandwidth,
111
- "pcie": None,
114
+ "pcie": "PCIe 4.0 x16",
112
115
  "display_active": True,
113
116
  "held_by": ["desktop session 0.9 GB"],
114
117
  "llm": fits,
@@ -157,6 +160,10 @@ def counters(task: str, seconds: float) -> Counters | None:
157
160
  "predicted_tokens": (turns + writing) * wrote,
158
161
  "predicted_seconds": (turns + writing) * write_s if wrote else 0.0,
159
162
  "processing": 1.0 if busy else 0.0,
163
+ "requests_deferred": 0.0,
164
+ "kv_cache_usage_ratio": 0.28 if task == "llm" else None,
165
+ "prompt_tokens_seconds": round(read / read_s, 1) if busy and read_s > 0 else 0.0,
166
+ "predicted_tokens_seconds": round(wrote / write_s, 1) if busy and wrote > 0 else 0.0,
160
167
  }
161
168
 
162
169
 
@@ -223,28 +230,48 @@ def slots(seconds: float) -> list[Slot]:
223
230
  cached = int(read * 0.8)
224
231
  done = cached + int((read - cached) * _progress(phase, start, read_s))
225
232
  busy = start <= phase < write_start + write_s
233
+ decoded = int(wrote * _progress(phase, write_start, write_s))
234
+ slot0_phase = "idle" if not busy else ("decoding" if decoded > 0 else "prefill")
226
235
  return [
227
236
  {
228
237
  "id": 0,
229
238
  "n_ctx": 131072,
230
239
  "busy": busy,
240
+ "phase": slot0_phase,
231
241
  "prompt_tokens": int(read),
232
242
  "prompt_done": done if phase >= start else int(read),
233
243
  "cached": cached,
234
- "decoded": int(wrote * _progress(phase, write_start, write_s)),
244
+ "decoded": decoded,
245
+ "n_prompt": int(read),
246
+ "cached_prefix_tokens": cached,
247
+ "n_decoded": decoded,
248
+ "tok_s": 38.0 if slot0_phase == "decoding" else None,
249
+ "ttft_ms": 200.0 if busy else None,
235
250
  },
236
251
  {
237
252
  "id": 1,
238
253
  "n_ctx": 131072,
239
254
  "busy": False,
255
+ "phase": "idle",
240
256
  "prompt_tokens": 31200,
241
257
  "prompt_done": 31200,
242
258
  "cached": 30100,
243
259
  "decoded": 812,
260
+ "n_prompt": 31200,
261
+ "cached_prefix_tokens": 30100,
262
+ "n_decoded": 812,
263
+ "tok_s": None,
264
+ "ttft_ms": None,
244
265
  },
245
266
  ]
246
267
 
247
268
 
269
+ def _waterfall(ev: list[Event], model_id: str) -> list[WaterfallEntry]:
270
+ return stack_view_events.waterfall_from_events(
271
+ ev, default_client="pi", model_by_component={"llm": model_id}, basis="demo"
272
+ )
273
+
274
+
248
275
  def _busy(seconds: float) -> bool:
249
276
  """Whether the made-up turn is on the card ``seconds`` into the demo (Jev, then the LLM)."""
250
277
  phase = seconds % TURN_S
@@ -267,6 +294,8 @@ def reading(seconds: float | None = None) -> Reading:
267
294
  name: {"model": route, "previous": None, "files": {}} for name in ("claude", "codex")
268
295
  }
269
296
  stamp = dt.datetime.now(dt.timezone.utc).replace(microsecond=0)
297
+ ev = events(clock, now=stamp)
298
+ busy = _busy(clock)
270
299
  return stack_view.reading(
271
300
  hardware(stack, {task for task, _ in parts}), # every component serves (liveness)
272
301
  stack,
@@ -277,9 +306,11 @@ def reading(seconds: float | None = None) -> Reading:
277
306
  if (found := counters(task, clock)) is not None
278
307
  },
279
308
  owned=owned,
280
- events=events(clock, now=stamp),
281
- gpu_load=stack_view_gpu.demo(_busy(clock)),
309
+ events=ev,
310
+ gpu_load=stack_view_gpu.demo(busy),
282
311
  slots={stack["llm"]["name"]: slots(clock)},
312
+ sensors=host_sensors.demo(busy),
313
+ waterfall=_waterfall(ev, stack["llm"]["model"]["id"]),
283
314
  source="demo",
284
315
  generated_at=stamp.isoformat(),
285
316
  )