@simplexai/localmodels-win32-x64 0.1.0-dev.59 → 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 (87) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +79 -73
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +104 -43
  5. package/modules/localmodels/apple_sensors.py +431 -0
  6. package/modules/localmodels/bifrost_admin.py +30 -0
  7. package/modules/localmodels/bifrost_checks.py +2 -2
  8. package/modules/localmodels/bifrost_config.py +132 -9
  9. package/modules/localmodels/bifrost_models.py +1 -1
  10. package/modules/localmodels/catalog.json +146 -54
  11. package/modules/localmodels/catalog.py +20 -3
  12. package/modules/localmodels/catalog_add.py +42 -11
  13. package/modules/localmodels/custom_hub.py +983 -0
  14. package/modules/localmodels/custom_hub_http.py +579 -0
  15. package/modules/localmodels/custom_probe.py +451 -0
  16. package/modules/localmodels/deploy.py +27 -5
  17. package/modules/localmodels/deploy_steps.py +5 -0
  18. package/modules/localmodels/download-mirrors.json +8 -0
  19. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  20. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  21. package/modules/localmodels/engines.py +38 -8
  22. package/modules/localmodels/estimator.py +60 -7
  23. package/modules/localmodels/gateway.py +48 -3
  24. package/modules/localmodels/gateway_app_bifrost.py +4 -4
  25. package/modules/localmodels/gateway_bifrost.py +98 -15
  26. package/modules/localmodels/gguf.py +6 -0
  27. package/modules/localmodels/host_sensors.py +704 -0
  28. package/modules/localmodels/library_cli.py +181 -3
  29. package/modules/localmodels/library_custom.py +831 -0
  30. package/modules/localmodels/library_elastic.py +35 -7
  31. package/modules/localmodels/library_gateway.py +94 -32
  32. package/modules/localmodels/library_jobs.py +76 -11
  33. package/modules/localmodels/library_kept.py +50 -6
  34. package/modules/localmodels/library_model.py +254 -2
  35. package/modules/localmodels/library_pricing.py +83 -4
  36. package/modules/localmodels/library_serve.py +112 -50
  37. package/modules/localmodels/library_smoke.py +315 -0
  38. package/modules/localmodels/library_state.py +77 -1
  39. package/modules/localmodels/library_status.py +126 -4
  40. package/modules/localmodels/nvml_ctypes.py +431 -0
  41. package/modules/localmodels/plan_envelope.py +14 -6
  42. package/modules/localmodels/records.py +1 -0
  43. package/modules/localmodels/remote_ops.py +53 -5
  44. package/modules/localmodels/remote_ops_download.py +168 -29
  45. package/modules/localmodels/remote_ops_ranges.py +2 -5
  46. package/modules/localmodels/remote_ops_service.py +2 -1
  47. package/modules/localmodels/remote_ops_verify.py +22 -5
  48. package/modules/localmodels/runtime-lock.json +19 -19
  49. package/modules/localmodels/service_control.py +32 -1
  50. package/modules/localmodels/service_wiring.py +2 -3
  51. package/modules/localmodels/service_worker.py +6 -2
  52. package/modules/localmodels/services_cli.py +35 -27
  53. package/modules/localmodels/source_byok.py +3 -5
  54. package/modules/localmodels/stack_lifecycle.py +2 -2
  55. package/modules/localmodels/stack_memory.py +1 -0
  56. package/modules/localmodels/stack_view.py +77 -53
  57. package/modules/localmodels/stack_view_demo.py +36 -5
  58. package/modules/localmodels/stack_view_events.py +147 -12
  59. package/modules/localmodels/stack_view_gpu.py +97 -17
  60. package/modules/localmodels/stack_view_llm.py +15 -0
  61. package/modules/localmodels/stack_view_measure.py +4 -1
  62. package/modules/localmodels/stack_view_schema.py +54 -8
  63. package/modules/localmodels/stack_view_serve.py +40 -3
  64. package/modules/localmodels/stack_view_slots.py +89 -10
  65. package/modules/localmodels/stack_view_telemetry.py +163 -0
  66. package/modules/localmodels/stack_view_text.py +5 -2
  67. package/modules/localmodels/stack_view_tick.py +658 -0
  68. package/modules/localmodels/stack_view_words.py +4 -0
  69. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  70. package/modules/localmodels/suite.py +3 -1
  71. package/modules/localmodels/telemetry_math.py +538 -0
  72. package/modules/localmodels/web/view/view.js +1 -1
  73. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
  74. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +76 -70
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. package/modules/localmodels/bifrost_datasheet.py +0 -53
  78. package/modules/localmodels/bifrost_provider.py +0 -88
  79. package/modules/localmodels/bifrost_unit.py +0 -99
  80. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
  81. package/modules/localmodels/gateway_switch.py +0 -51
  82. package/modules/localmodels/library_floor.py +0 -78
  83. package/modules/localmodels/service_stop.py +0 -52
  84. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
  87. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -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
  )
@@ -27,6 +27,7 @@ from typing import Any, TypedDict
27
27
  from localmodels import bifrost_checks, gateway, harness, hosts
28
28
  from localmodels.gateway_bifrost import FAST_PROVIDER, owned_listener
29
29
  from localmodels.stack_view_words import say
30
+ from localmodels.telemetry_math import WATERFALL_LIMIT, WaterfallEntry
30
31
 
31
32
  LIMIT = 40 # the last calls a page needs to animate and to average
32
33
  KINDS = {
@@ -188,18 +189,8 @@ def read(doc: hosts.Owned, magpie_addr: str | None = None, limit: int = LIMIT) -
188
189
  """The last ``limit`` calls of this tool's gateway, newest-ended first: its Bifrost's log
189
190
  (which picks the last ``limit`` by start time), else, for a stack wired into Magpie
190
191
  (``magpie_addr``), Magpie's usage log; empty when neither."""
191
- bifrost = doc["gateway"].get("bifrost")
192
- if bifrost:
193
- try:
194
- if not owned_listener(bifrost):
195
- return []
196
- rows = bifrost_checks.logs(bifrost["addr"], limit=str(limit))
197
- except (OSError, ValueError, KeyError):
198
- return []
199
- return newest_first([event(row) for row in rows if isinstance(row, dict)])
200
- if magpie_addr and doc["gateway"]["providers"]:
201
- return read_magpie(doc, magpie_addr, limit)
202
- return []
192
+ events, _ = read_with_waterfall(doc, magpie_addr, limit)
193
+ return events
203
194
 
204
195
 
205
196
  # What the board says about the calls above: per-component figures and the alerts.
@@ -258,3 +249,147 @@ def alerts(comps: list[Any]) -> list[str]:
258
249
  )
259
250
  )
260
251
  return found
252
+
253
+
254
+ _CLIENT_TAGS = ("pi", "claude", "codex", "linger", "local")
255
+
256
+
257
+ def _client_id(row: dict[str, Any], default: str = "unknown") -> str:
258
+ """Safe, allowlisted client attribution from gateway metadata (never copies arbitrary headers)."""
259
+ for key in ("client_id", "client", "source_client", "user_agent", "routing_rule_id"):
260
+ raw = row.get(key)
261
+ if not isinstance(raw, str):
262
+ continue
263
+ lower = raw.lower()
264
+ for tag in _CLIENT_TAGS:
265
+ if tag in lower:
266
+ return tag
267
+ return default
268
+
269
+
270
+ def _waterfall_status(raw_status: object) -> str:
271
+ text = str(raw_status or "").strip().lower()
272
+ if text in ("streaming", "in_progress", "processing", "running"):
273
+ return "streaming"
274
+ if text in ("deferred", "queued", "pending", "rate_limited"):
275
+ return "deferred"
276
+ if text in ("failed", "error", "errored", "timeout", "cancelled", "canceled") or (
277
+ text.isdigit() and int(text) >= 400
278
+ ):
279
+ return "failed"
280
+ return "completed"
281
+
282
+
283
+ def waterfall_from_bifrost_row(row: dict[str, Any], *, basis: str = "live") -> WaterfallEntry:
284
+ """Convert one Bifrost log row into a sanitized ``WaterfallEntry`` (no prompt/answer text)."""
285
+ usage = row.get("token_usage")
286
+ prompt_tokens = _count(usage, "prompt_tokens")
287
+ completion_tokens = _count(usage, "completion_tokens")
288
+ cached_tokens = _count(usage, "cached_tokens")
289
+ if cached_tokens is None and isinstance(usage, dict):
290
+ details = usage.get("prompt_tokens_details")
291
+ if isinstance(details, dict):
292
+ cached_tokens = _count(details, "cached_tokens")
293
+ cached_pct: float | None = None
294
+ if cached_tokens is not None and prompt_tokens is not None and prompt_tokens > 0:
295
+ cached_pct = round(min(100.0, max(0.0, (cached_tokens / prompt_tokens) * 100.0)), 1)
296
+ latency_ms = _number(row.get("latency"))
297
+ gateway_ms = _number(row.get("overhead_latency"))
298
+ ttft_ms = _number(row.get("ttft_ms"))
299
+ if ttft_ms is None:
300
+ ttft_ms = _number(row.get("time_to_first_token_ms"))
301
+ decode_ms: float | None = None
302
+ if latency_ms is not None:
303
+ head = (ttft_ms or 0.0) + (gateway_ms or 0.0 if ttft_ms is None else 0.0)
304
+ decode_ms = round(max(0.0, latency_ms - head), 1)
305
+ decode_tok_s: float | None = None
306
+ if completion_tokens and decode_ms and decode_ms > 0:
307
+ decode_tok_s = round(completion_tokens / (decode_ms / 1000.0), 1)
308
+ model_raw = str(row.get("model") or row.get("provider") or "local-llm")[:128]
309
+ return {
310
+ "request_id": str(row.get("id") or ""),
311
+ "at": str(row.get("timestamp") or ""),
312
+ "client_id": _client_id(row),
313
+ "model_id": model_raw,
314
+ "status": _waterfall_status(row.get("status")),
315
+ "gateway_ms": round(gateway_ms, 1) if gateway_ms is not None else None,
316
+ "ttft_ms": round(ttft_ms, 1) if ttft_ms is not None else None,
317
+ "decode_ms": decode_ms,
318
+ "prompt_tokens": prompt_tokens,
319
+ "completion_tokens": completion_tokens,
320
+ "cached_prefix_pct": cached_pct,
321
+ "decode_tok_s": decode_tok_s,
322
+ "basis": basis,
323
+ }
324
+
325
+
326
+ def waterfall_from_events(
327
+ events: list[Event],
328
+ *,
329
+ default_client: str = "unknown",
330
+ model_by_component: dict[str, str] | None = None,
331
+ basis: str = "live",
332
+ limit: int = WATERFALL_LIMIT,
333
+ ) -> list[WaterfallEntry]:
334
+ """Project sanitized ``Event`` rows into bounded rolling ``WaterfallEntry`` items."""
335
+ models = model_by_component or {}
336
+ found: list[WaterfallEntry] = []
337
+ for ev in newest_first(events)[:limit]:
338
+ latency = ev["latency_ms"]
339
+ gw = ev["gateway_ms"]
340
+ ttft = ev["ttft_ms"]
341
+ decode_ms: float | None = None
342
+ if latency is not None:
343
+ head = ttft if ttft is not None else (gw or 0.0)
344
+ decode_ms = round(max(0.0, latency - head), 1)
345
+ out_tok = ev["tokens_out"]
346
+ tok_s = (
347
+ round(out_tok / (decode_ms / 1000.0), 1)
348
+ if out_tok and decode_ms and decode_ms > 0
349
+ else None
350
+ )
351
+ comp = ev["component"] or ev["kind"]
352
+ found.append(
353
+ {
354
+ "request_id": ev["id"],
355
+ "at": ev["at"],
356
+ "client_id": default_client,
357
+ "model_id": models.get(comp, comp),
358
+ "status": "completed" if ev["ok"] else "failed",
359
+ "gateway_ms": round(gw, 1) if gw is not None else None,
360
+ "ttft_ms": round(ttft, 1) if ttft is not None else None,
361
+ "decode_ms": decode_ms,
362
+ "prompt_tokens": ev["tokens_in"],
363
+ "completion_tokens": out_tok,
364
+ "cached_prefix_pct": None,
365
+ "decode_tok_s": tok_s,
366
+ "basis": basis,
367
+ }
368
+ )
369
+ return found
370
+
371
+
372
+ def read_with_waterfall(
373
+ doc: hosts.Owned, magpie_addr: str | None = None, limit: int = LIMIT
374
+ ) -> tuple[list[Event], list[WaterfallEntry]]:
375
+ """Read gateway events and bounded rolling waterfall entries in a single gateway call."""
376
+ bifrost = doc["gateway"].get("bifrost")
377
+ if bifrost:
378
+ try:
379
+ if not owned_listener(bifrost):
380
+ return [], []
381
+ rows = bifrost_checks.logs(bifrost["addr"], limit=str(limit))
382
+ except (OSError, ValueError, KeyError):
383
+ return [], []
384
+ dict_rows = [row for row in rows if isinstance(row, dict)]
385
+ paired = [(event(row), row) for row in dict_rows]
386
+ paired.sort(key=lambda item: ended(item[0]), reverse=True)
387
+ ev = [item[0] for item in paired]
388
+ wf = [
389
+ waterfall_from_bifrost_row(item[1], basis="live") for item in paired[:WATERFALL_LIMIT]
390
+ ]
391
+ return ev, wf
392
+ if magpie_addr and doc["gateway"]["providers"]:
393
+ ev = read_magpie(doc, magpie_addr, limit)
394
+ return ev, waterfall_from_events(ev, basis="live")
395
+ return [], []