@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
@@ -0,0 +1,538 @@
1
+ """Pure telemetry arithmetic: effective decode bandwidth, deterministic bottleneck classification,
2
+ PCIe bandwidth lookup, and bounded request waterfall / p50 TTFT / prefix hit calculations."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import datetime as dt
7
+ import json
8
+ import math
9
+ import re
10
+ import statistics
11
+ import threading
12
+ from collections import deque
13
+ from collections.abc import Mapping, Sequence
14
+ from typing import Any, TypedDict, cast
15
+
16
+ from localmodels import gpu_specs
17
+
18
+ WATERFALL_LIMIT = 20
19
+ DEFAULT_TTFT_WINDOW_S = 60.0
20
+ IO_BOUND_DISK_MB_S = 500.0
21
+ MEM_BW_BOUND_PCT = 74.0
22
+ MEM_CTRL_BOUND_PCT = 75.0
23
+ COMPUTE_BOUND_GPU_PCT = 82.0
24
+ IDLE_GPU_PCT = 10.0
25
+
26
+ # Unidirectional per-lane theoretical bandwidth (GB/s) for PCIe Gen 1..6.
27
+ _PCIE_GEN_PER_LANE_GB_S = {
28
+ 1: 0.25,
29
+ 2: 0.5,
30
+ 3: 0.985,
31
+ 4: 1.969,
32
+ 5: 3.938,
33
+ 6: 7.563,
34
+ }
35
+ _PCIE_RE = re.compile(r"pcie\s*(?:gen\s*)?(\d+)(?:\.\d+)?\s*x(\d+)", re.IGNORECASE)
36
+
37
+ # Exact llama.cpp KV dtype ratios relative to f16 (2.0 B/elem): q8_0 = 34/32, q4_0 = 18/32.
38
+ KV_DTYPE_FACTORS: dict[str, float] = {
39
+ "f16": 1.0,
40
+ "q8_0": round((34 / 32) / 2.0, 5),
41
+ "q4_0": round((18 / 32) / 2.0, 5),
42
+ }
43
+
44
+
45
+ class TelemetryFigure(TypedDict):
46
+ value: float | None
47
+ basis: str # live | measured | estimate | demo | none
48
+ note: str
49
+
50
+
51
+ class WaterfallEntry(TypedDict):
52
+ request_id: str
53
+ at: str
54
+ client_id: str
55
+ model_id: str
56
+ status: str # streaming | completed | deferred | failed
57
+ gateway_ms: float | None
58
+ ttft_ms: float | None
59
+ decode_ms: float | None
60
+ prompt_tokens: int | None
61
+ completion_tokens: int | None
62
+ cached_prefix_pct: float | None
63
+ decode_tok_s: float | None
64
+ basis: str # live | measured | estimate | demo | none
65
+
66
+
67
+ def client_lanes(waterfall: Sequence[WaterfallEntry], in_flight: int) -> dict[str, int]:
68
+ """Count active requests per client without fabricating an identity when unobserved."""
69
+ lanes: dict[str, int] = {}
70
+ for entry in waterfall:
71
+ if entry["status"] == "streaming":
72
+ cid = entry["client_id"] or "unknown"
73
+ lanes[cid] = lanes.get(cid, 0) + 1
74
+ if not lanes and in_flight > 0:
75
+ lanes["unknown"] = in_flight
76
+ return lanes
77
+
78
+
79
+ def figure(value: float | None, basis: str, note: str, *, digits: int = 1) -> TelemetryFigure:
80
+ if value is None or not math.isfinite(value) or value < 0:
81
+ return {"value": None, "basis": "none", "note": note}
82
+ return {"value": round(value, digits), "basis": basis, "note": note}
83
+
84
+
85
+ def effective_decode_bw_gb_s(
86
+ decode_tok_s: Mapping[str, Any] | None, active_weight_bytes: int | None
87
+ ) -> TelemetryFigure:
88
+ """``decode_tok_s * active_weight_bytes / 1e9`` with honest provenance."""
89
+ raw = decode_tok_s.get("value") if isinstance(decode_tok_s, Mapping) else None
90
+ src_basis = (
91
+ str(decode_tok_s.get("basis") or "none") if isinstance(decode_tok_s, Mapping) else "none"
92
+ )
93
+ if (
94
+ not isinstance(raw, int | float)
95
+ or isinstance(raw, bool)
96
+ or not math.isfinite(raw)
97
+ or raw <= 0
98
+ or active_weight_bytes is None
99
+ or active_weight_bytes <= 0
100
+ ):
101
+ return {
102
+ "value": None,
103
+ "basis": "none",
104
+ "note": "Effective decode bandwidth requires live decode speed and active weight bytes",
105
+ }
106
+ gb_s = float(raw) * active_weight_bytes / 1e9
107
+ if src_basis == "demo":
108
+ basis = "demo"
109
+ note = "Demo data, not a measurement"
110
+ elif src_basis in ("live", "measured"):
111
+ basis = "measured"
112
+ note = "decode_tok_s × active_weight_bytes ÷ 1e9"
113
+ else:
114
+ basis = "estimate"
115
+ note = "Estimated decode speed × active_weight_bytes ÷ 1e9"
116
+ return {"value": round(gb_s, 2), "basis": basis, "note": note}
117
+
118
+
119
+ def memory_bw_ceiling_gb_s(
120
+ card: Mapping[str, Any] | None,
121
+ *,
122
+ host_measured_gbps: float | None = None,
123
+ source: str = "live",
124
+ ) -> TelemetryFigure:
125
+ """Theoretical or host-measured memory bandwidth ceiling in GB/s."""
126
+ if card is not None:
127
+ raw_bw = card.get("bandwidth_gb_s")
128
+ if isinstance(raw_bw, int | float) and not isinstance(raw_bw, bool) and raw_bw > 0:
129
+ basis = "demo" if source == "demo" else "estimate"
130
+ return {
131
+ "value": round(float(raw_bw), 1),
132
+ "basis": basis,
133
+ "note": "Vendor published memory bandwidth ceiling",
134
+ }
135
+ name = str(card.get("name") or "")
136
+ total = card.get("total_bytes")
137
+ spec = gpu_specs.bandwidth_gb_s(
138
+ name, total_bytes=int(total) if isinstance(total, int) else None
139
+ )
140
+ if spec is not None and spec > 0:
141
+ basis = "demo" if source == "demo" else "estimate"
142
+ return {
143
+ "value": round(spec, 1),
144
+ "basis": basis,
145
+ "note": "Vendor published memory bandwidth ceiling",
146
+ }
147
+ if host_measured_gbps is not None and host_measured_gbps > 0:
148
+ basis = "demo" if source == "demo" else "measured"
149
+ return {
150
+ "value": round(host_measured_gbps, 1),
151
+ "basis": basis,
152
+ "note": "Host memory copy bandwidth benchmark",
153
+ }
154
+ return {
155
+ "value": None,
156
+ "basis": "none",
157
+ "note": "No published or measured memory bandwidth ceiling for this device",
158
+ }
159
+
160
+
161
+ def pcie_bandwidth_gb_s(pcie_label: str | None) -> float | None:
162
+ """Estimate unidirectional PCIe bandwidth in GB/s from a label like ``PCIe 4.0 x16``."""
163
+ if not pcie_label:
164
+ return None
165
+ match = _PCIE_RE.search(pcie_label)
166
+ if not match:
167
+ return None
168
+ gen, width = int(match.group(1)), int(match.group(2))
169
+ per_lane = _PCIE_GEN_PER_LANE_GB_S.get(gen)
170
+ if per_lane is None or width <= 0:
171
+ return None
172
+ return round(per_lane * width, 2)
173
+
174
+
175
+ def classify_bottleneck(
176
+ *,
177
+ in_flight: int,
178
+ decode_tok_s: float | None = None,
179
+ effective_bw_gb_s: float | None,
180
+ bw_ceiling_gb_s: float | None,
181
+ gpu_util_pct: float | None,
182
+ mem_ctrl_util_pct: float | None = None,
183
+ disk_read_mb_s: float | None = None,
184
+ active_tick_delta: bool = False,
185
+ ) -> str:
186
+ """Deterministic bottleneck enum: memory_bw_bound | compute_bound | io_bound | balanced | idle.
187
+
188
+ Cumulative lifetime or saved warm-store ``decode_tok_s`` values are intentionally not treated as
189
+ proof of current activity: an idle GPU with ``in_flight == 0``, no active tick delta, and
190
+ ``gpu_util_pct < IDLE_GPU_PCT`` must report ``"idle"``.
191
+ """
192
+ _ = decode_tok_s
193
+ bw_util_pct: float | None = None
194
+ if (
195
+ effective_bw_gb_s is not None
196
+ and bw_ceiling_gb_s is not None
197
+ and bw_ceiling_gb_s > 0
198
+ and effective_bw_gb_s >= 0
199
+ ):
200
+ bw_util_pct = (effective_bw_gb_s / bw_ceiling_gb_s) * 100.0
201
+
202
+ active = (
203
+ in_flight > 0
204
+ or active_tick_delta
205
+ or (gpu_util_pct is not None and gpu_util_pct >= IDLE_GPU_PCT)
206
+ )
207
+ if (
208
+ disk_read_mb_s is not None
209
+ and disk_read_mb_s >= IO_BOUND_DISK_MB_S
210
+ and (not active or bw_util_pct is None or bw_util_pct < 50.0)
211
+ ):
212
+ return "io_bound"
213
+
214
+ if not active:
215
+ return "idle"
216
+
217
+ if (
218
+ bw_util_pct is not None
219
+ and bw_util_pct >= MEM_BW_BOUND_PCT
220
+ and (gpu_util_pct is None or bw_util_pct >= gpu_util_pct - 10.0)
221
+ ):
222
+ return "memory_bw_bound"
223
+ if (
224
+ mem_ctrl_util_pct is not None
225
+ and mem_ctrl_util_pct >= MEM_CTRL_BOUND_PCT
226
+ and (gpu_util_pct is None or mem_ctrl_util_pct >= gpu_util_pct - 10.0)
227
+ ):
228
+ return "memory_bw_bound"
229
+
230
+ if gpu_util_pct is not None and gpu_util_pct >= COMPUTE_BOUND_GPU_PCT:
231
+ return "compute_bound"
232
+
233
+ return "balanced"
234
+
235
+
236
+ def _parse_iso(at: str) -> dt.datetime | None:
237
+ if not at:
238
+ return None
239
+ try:
240
+ parsed = dt.datetime.fromisoformat(at.replace("Z", "+00:00"))
241
+ except ValueError:
242
+ return None
243
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.timezone.utc)
244
+
245
+
246
+ def p50_ttft_ms(
247
+ waterfall: Sequence[WaterfallEntry],
248
+ *,
249
+ now: str | dt.datetime | None = None,
250
+ window_s: float = DEFAULT_TTFT_WINDOW_S,
251
+ source: str = "live",
252
+ ) -> TelemetryFigure:
253
+ """Sliding-window (60s) median TTFT across waterfall entries with valid ``ttft_ms``."""
254
+ clock = (
255
+ now
256
+ if isinstance(now, dt.datetime)
257
+ else _parse_iso(now)
258
+ if isinstance(now, str)
259
+ else dt.datetime.now(dt.timezone.utc)
260
+ )
261
+ if clock is None:
262
+ clock = dt.datetime.now(dt.timezone.utc)
263
+ cutoff = clock - dt.timedelta(seconds=window_s)
264
+ samples: list[float] = []
265
+ for entry in waterfall:
266
+ ttft = entry.get("ttft_ms")
267
+ if ttft is None or not math.isfinite(ttft) or ttft <= 0:
268
+ continue
269
+ stamp = _parse_iso(entry.get("at", ""))
270
+ if stamp is None or stamp >= cutoff:
271
+ samples.append(float(ttft))
272
+ if not samples:
273
+ return {
274
+ "value": None,
275
+ "basis": "none",
276
+ "note": f"No TTFT measurements in the last {int(window_s)} s",
277
+ }
278
+ basis = "demo" if source == "demo" else "live"
279
+ note = (
280
+ "Demo data, not a measurement"
281
+ if source == "demo"
282
+ else f"Median TTFT across {len(samples)} request(s) in the last {int(window_s)} s"
283
+ )
284
+ return {"value": round(statistics.median(samples), 1), "basis": basis, "note": note}
285
+
286
+
287
+ def prefix_hit_pct(
288
+ waterfall: Sequence[WaterfallEntry],
289
+ slots: Sequence[Mapping[str, Any]] | None = None,
290
+ *,
291
+ source: str = "live",
292
+ ) -> TelemetryFigure:
293
+ """Prefix cache hit % from recent waterfall requests or live engine ``/slots`` counters."""
294
+ wf_hits: list[float] = []
295
+ for entry in waterfall:
296
+ raw_hit = entry.get("cached_prefix_pct")
297
+ if raw_hit is not None and math.isfinite(raw_hit):
298
+ wf_hits.append(float(raw_hit))
299
+ if wf_hits:
300
+ basis = "demo" if source == "demo" else "live"
301
+ return {
302
+ "value": round(sum(wf_hits) / len(wf_hits), 1),
303
+ "basis": basis,
304
+ "note": "Demo data, not a measurement"
305
+ if source == "demo"
306
+ else "Mean cached prefix share across recent requests",
307
+ }
308
+ prompt_total = 0
309
+ cached_total = 0
310
+ for slot in slots or ():
311
+ p = slot.get("prompt_tokens")
312
+ c = slot.get("cached")
313
+ if isinstance(p, int) and isinstance(c, int) and p > 0 and c >= 0:
314
+ prompt_total += p
315
+ cached_total += min(c, p)
316
+ if prompt_total > 0:
317
+ basis = "demo" if source == "demo" else "live"
318
+ return {
319
+ "value": round((cached_total / prompt_total) * 100.0, 1),
320
+ "basis": basis,
321
+ "note": "Demo data, not a measurement"
322
+ if source == "demo"
323
+ else "Cached prompt token ratio from live /slots",
324
+ }
325
+ return {
326
+ "value": None,
327
+ "basis": "none",
328
+ "note": "No prefix cache counters observed yet",
329
+ }
330
+
331
+
332
+ class RequestWaterfallBuffer:
333
+ """Thread-safe bounded ring buffer tracking in-flight & recent gateway requests (last 20)."""
334
+
335
+ def __init__(self, maxlen: int = WATERFALL_LIMIT) -> None:
336
+ self._lock = threading.Lock()
337
+ self._maxlen = max(1, maxlen)
338
+ self._in_flight: dict[str, tuple[float, WaterfallEntry]] = {}
339
+ self._completed: deque[WaterfallEntry] = deque(maxlen=self._maxlen)
340
+
341
+ def record_dispatch(
342
+ self,
343
+ request_id: str,
344
+ client_id: str,
345
+ model_id: str,
346
+ *,
347
+ dispatched_at: float,
348
+ at_iso: str = "",
349
+ gateway_ms: float | None = None,
350
+ prompt_tokens: int | None = None,
351
+ cached_prefix_pct: float | None = None,
352
+ basis: str = "live",
353
+ ) -> None:
354
+ entry: WaterfallEntry = {
355
+ "request_id": request_id,
356
+ "at": at_iso or dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
357
+ "client_id": client_id,
358
+ "model_id": model_id,
359
+ "status": "streaming",
360
+ "gateway_ms": round(gateway_ms, 1) if gateway_ms is not None else None,
361
+ "ttft_ms": None,
362
+ "decode_ms": None,
363
+ "prompt_tokens": prompt_tokens,
364
+ "completion_tokens": 0,
365
+ "cached_prefix_pct": round(cached_prefix_pct, 1)
366
+ if cached_prefix_pct is not None
367
+ else None,
368
+ "decode_tok_s": None,
369
+ "basis": basis,
370
+ }
371
+ with self._lock:
372
+ self._in_flight[request_id] = (dispatched_at, entry)
373
+
374
+ def record_first_token(self, request_id: str, *, arrived_at: float) -> float | None:
375
+ with self._lock:
376
+ item = self._in_flight.get(request_id)
377
+ if item is None:
378
+ return None
379
+ dispatched_at, entry = item
380
+ ttft = max(0.0, (arrived_at - dispatched_at) * 1000.0)
381
+ entry["ttft_ms"] = round(ttft, 1)
382
+ return entry["ttft_ms"]
383
+
384
+ def record_complete(
385
+ self,
386
+ request_id: str,
387
+ *,
388
+ completed_at: float,
389
+ gateway_ms: float | None = None,
390
+ prompt_tokens: int | None = None,
391
+ completion_tokens: int | None = None,
392
+ cached_prefix_tokens: int | None = None,
393
+ status: str = "completed",
394
+ ) -> WaterfallEntry | None:
395
+ with self._lock:
396
+ item = self._in_flight.pop(request_id, None)
397
+ if item is None:
398
+ return None
399
+ dispatched_at, entry = item
400
+ total_ms = max(0.0, (completed_at - dispatched_at) * 1000.0)
401
+ ttft = entry["ttft_ms"]
402
+ decode_ms = max(0.0, total_ms - ttft) if ttft is not None else total_ms
403
+ entry["status"] = (
404
+ status
405
+ if status in ("streaming", "completed", "deferred", "failed")
406
+ else "completed"
407
+ )
408
+ if gateway_ms is not None:
409
+ entry["gateway_ms"] = round(gateway_ms, 1)
410
+ entry["decode_ms"] = round(decode_ms, 1)
411
+ if prompt_tokens is not None:
412
+ entry["prompt_tokens"] = prompt_tokens
413
+ if completion_tokens is not None:
414
+ entry["completion_tokens"] = completion_tokens
415
+ if (
416
+ cached_prefix_tokens is not None
417
+ and entry["prompt_tokens"] is not None
418
+ and entry["prompt_tokens"] > 0
419
+ ):
420
+ pct = min(100.0, max(0.0, (cached_prefix_tokens / entry["prompt_tokens"]) * 100.0))
421
+ entry["cached_prefix_pct"] = round(pct, 1)
422
+ if entry["completion_tokens"] and decode_ms > 0:
423
+ entry["decode_tok_s"] = round(entry["completion_tokens"] / (decode_ms / 1000.0), 1)
424
+ self._completed.appendleft(entry)
425
+ return dict(entry) # type: ignore[return-value]
426
+
427
+ def in_flight_count(self) -> int:
428
+ with self._lock:
429
+ return len(self._in_flight)
430
+
431
+ def client_lane_counts(self) -> dict[str, int]:
432
+ with self._lock:
433
+ counts: dict[str, int] = {}
434
+ for _, entry in self._in_flight.values():
435
+ cid = entry["client_id"]
436
+ counts[cid] = counts.get(cid, 0) + 1
437
+ return counts
438
+
439
+ def entries(self) -> list[WaterfallEntry]:
440
+ with self._lock:
441
+ live = [cast(WaterfallEntry, dict(entry)) for _, entry in self._in_flight.values()]
442
+ done = [cast(WaterfallEntry, dict(entry)) for entry in self._completed]
443
+ return [*live, *done][: self._maxlen]
444
+
445
+ def p50_ttft(
446
+ self, *, now: str | dt.datetime | None = None, window_s: float = DEFAULT_TTFT_WINDOW_S
447
+ ) -> TelemetryFigure:
448
+ return p50_ttft_ms(self.entries(), now=now, window_s=window_s)
449
+
450
+
451
+ def _parse_polystrata_json_metrics(text: str) -> dict[str, Any] | None:
452
+ """Parse PolyStrata JSON ``/metrics`` when it carries live numeric engine counters."""
453
+ try:
454
+ raw = json.loads(text)
455
+ except ValueError:
456
+ return None
457
+ if not isinstance(raw, dict):
458
+ return None
459
+ src = raw.get("metrics") if isinstance(raw.get("metrics"), dict) else raw
460
+ if not isinstance(src, dict):
461
+ return None
462
+
463
+ def num(*keys: str) -> float | None:
464
+ for key in keys:
465
+ val = src.get(key)
466
+ if isinstance(val, int | float) and not isinstance(val, bool) and math.isfinite(val):
467
+ return float(val)
468
+ return None
469
+
470
+ prompt_tok = num("prompt_tokens_total", "prompt_tokens")
471
+ prompt_sec = num("prompt_seconds_total", "prompt_seconds")
472
+ pred_tok = num("tokens_predicted_total", "predicted_tokens", "decode_tokens_total")
473
+ pred_sec = num("tokens_predicted_seconds_total", "predicted_seconds", "decode_seconds_total")
474
+ processing = num("requests_processing", "in_flight", "active_requests")
475
+ deferred = num("requests_deferred", "queued_requests")
476
+ kv_ratio = num("kv_cache_usage_ratio", "kv_usage_ratio")
477
+ prompt_rate = num("prompt_tokens_seconds", "prefill_tok_s")
478
+ pred_rate = num("predicted_tokens_seconds", "decode_tok_s")
479
+ if all(
480
+ v is None
481
+ for v in (prompt_tok, pred_tok, processing, deferred, kv_ratio, prompt_rate, pred_rate)
482
+ ):
483
+ return None
484
+ return {
485
+ "prompt_tokens": prompt_tok or 0.0,
486
+ "prompt_seconds": prompt_sec or 0.0,
487
+ "predicted_tokens": pred_tok or 0.0,
488
+ "predicted_seconds": pred_sec or 0.0,
489
+ "processing": processing or 0.0,
490
+ "requests_deferred": deferred,
491
+ "kv_cache_usage_ratio": kv_ratio,
492
+ "prompt_tokens_seconds": prompt_rate,
493
+ "predicted_tokens_seconds": pred_rate,
494
+ }
495
+
496
+
497
+ def parse_engine_metrics(text: str) -> dict[str, Any] | None:
498
+ """Parse llama-server Prometheus or PolyStrata ``/metrics`` into structured counters."""
499
+ stripped = text.lstrip()
500
+ if stripped.startswith("{"):
501
+ return _parse_polystrata_json_metrics(stripped)
502
+ totals: dict[str, float] = {}
503
+ for line in text.splitlines():
504
+ if line.startswith("#") or not line.strip():
505
+ continue
506
+ prefix = (
507
+ "llamacpp:"
508
+ if line.startswith("llamacpp:")
509
+ else "polystrata:"
510
+ if line.startswith("polystrata:")
511
+ else "strata:"
512
+ if line.startswith("strata:")
513
+ else ""
514
+ )
515
+ if not prefix:
516
+ continue
517
+ name, _, rest = line.partition(" ")
518
+ try:
519
+ value = float(rest.split()[0])
520
+ except (IndexError, ValueError):
521
+ continue
522
+ if not math.isfinite(value):
523
+ continue
524
+ key = name.partition("{")[0].removeprefix(prefix)
525
+ totals[key] = totals.get(key, 0.0) + value
526
+ if not totals:
527
+ return None
528
+ return {
529
+ "prompt_tokens": totals.get("prompt_tokens_total", 0.0),
530
+ "prompt_seconds": totals.get("prompt_seconds_total", 0.0),
531
+ "predicted_tokens": totals.get("tokens_predicted_total", 0.0),
532
+ "predicted_seconds": totals.get("tokens_predicted_seconds_total", 0.0),
533
+ "processing": totals.get("requests_processing", 0.0),
534
+ "requests_deferred": totals.get("requests_deferred"),
535
+ "kv_cache_usage_ratio": totals.get("kv_cache_usage_ratio"),
536
+ "prompt_tokens_seconds": totals.get("prompt_tokens_seconds"),
537
+ "predicted_tokens_seconds": totals.get("predicted_tokens_seconds"),
538
+ }
@@ -1112,7 +1112,7 @@ function renderLoad(v) {
1112
1112
  if (!line) continue;
1113
1113
  let span = line.querySelector(".load");
1114
1114
  if (!span) line.append((span = h("span", { class: "load" })));
1115
- const label = `${text} · ${t("basis." + l.basis)}`;
1115
+ const label = text ? `${text} · ${t("basis." + l.basis)}` : t("basis." + l.basis);
1116
1116
  if (span.textContent !== label) span.textContent = label;
1117
1117
  span.style.setProperty("--load", util.toFixed(2));
1118
1118
  if (!host.classList.contains("gpu")) continue;
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simplex-localmodels
3
- Version: 0.1.0.dev59
3
+ Version: 0.1.0.dev60
4
4
  Summary: Detect hardware, recommend and install a verified local model stack
5
5
  License-Expression: LicenseRef-Proprietary
6
6
  License-File: NOTICE