@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.38

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 (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +132 -110
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_checks.py +9 -6
  7. package/modules/localmodels/bifrost_config.py +203 -0
  8. package/modules/localmodels/bifrost_datasheet.py +12 -2
  9. package/modules/localmodels/budget.py +13 -2
  10. package/modules/localmodels/catalog.json +137 -2
  11. package/modules/localmodels/catalog.py +70 -321
  12. package/modules/localmodels/catalog_add.py +2 -8
  13. package/modules/localmodels/catalog_recipes.py +352 -0
  14. package/modules/localmodels/cli_parser.py +4 -1
  15. package/modules/localmodels/console.py +5 -4
  16. package/modules/localmodels/contracts.py +13 -3
  17. package/modules/localmodels/debug_cli.py +158 -0
  18. package/modules/localmodels/debug_mode.py +727 -0
  19. package/modules/localmodels/debug_stub_server.py +192 -0
  20. package/modules/localmodels/decode_calibration.json +1 -1
  21. package/modules/localmodels/decode_calibration.py +34 -17
  22. package/modules/localmodels/gateway.py +21 -155
  23. package/modules/localmodels/gateway_accept.py +201 -0
  24. package/modules/localmodels/gateway_bifrost.py +30 -193
  25. package/modules/localmodels/gateway_cli.py +15 -6
  26. package/modules/localmodels/gateway_foundations.py +2 -4
  27. package/modules/localmodels/gateway_probe.py +0 -1
  28. package/modules/localmodels/gateway_server.py +2 -3
  29. package/modules/localmodels/gpu_specs.py +12 -0
  30. package/modules/localmodels/guard.py +2 -7
  31. package/modules/localmodels/harness.py +16 -129
  32. package/modules/localmodels/harness_cleanup.py +135 -0
  33. package/modules/localmodels/harness_gateway.py +16 -14
  34. package/modules/localmodels/harness_probe.py +12 -4
  35. package/modules/localmodels/hosts.py +25 -2
  36. package/modules/localmodels/http_local.py +59 -0
  37. package/modules/localmodels/install.py +23 -8
  38. package/modules/localmodels/library_gateway.py +20 -9
  39. package/modules/localmodels/library_jobs.py +125 -28
  40. package/modules/localmodels/library_model.py +10 -0
  41. package/modules/localmodels/library_pricing.py +29 -22
  42. package/modules/localmodels/library_serve.py +17 -1
  43. package/modules/localmodels/library_state.py +15 -2
  44. package/modules/localmodels/library_status.py +30 -0
  45. package/modules/localmodels/llm_rank.py +185 -39
  46. package/modules/localmodels/probe.py +108 -174
  47. package/modules/localmodels/process_identity.py +120 -154
  48. package/modules/localmodels/process_windows.py +86 -0
  49. package/modules/localmodels/recommend.py +6 -3
  50. package/modules/localmodels/recommend_cli.py +14 -6
  51. package/modules/localmodels/remote_ops.py +65 -0
  52. package/modules/localmodels/remote_ops_service.py +14 -2
  53. package/modules/localmodels/runtime_args.py +10 -3
  54. package/modules/localmodels/runtime_auth.py +5 -9
  55. package/modules/localmodels/runtime_cli.py +128 -129
  56. package/modules/localmodels/runtime_discovery.py +84 -0
  57. package/modules/localmodels/runtime_install.py +101 -0
  58. package/modules/localmodels/runtime_releases.py +302 -0
  59. package/modules/localmodels/search_server.py +5 -1
  60. package/modules/localmodels/service_stop.py +8 -108
  61. package/modules/localmodels/service_upgrade.py +394 -63
  62. package/modules/localmodels/services_cli.py +24 -14
  63. package/modules/localmodels/setup_inspection.py +97 -9
  64. package/modules/localmodels/setup_text.py +7 -0
  65. package/modules/localmodels/sizecalc.py +0 -1
  66. package/modules/localmodels/stack.py +45 -235
  67. package/modules/localmodels/stack_arena.py +732 -0
  68. package/modules/localmodels/stack_args.py +21 -12
  69. package/modules/localmodels/stack_auto.py +384 -3
  70. package/modules/localmodels/stack_aux_gpu.py +4 -3
  71. package/modules/localmodels/stack_capacity.py +138 -0
  72. package/modules/localmodels/stack_cleanup.py +9 -4
  73. package/modules/localmodels/stack_cli.py +288 -0
  74. package/modules/localmodels/stack_compose.py +63 -30
  75. package/modules/localmodels/stack_console.py +9 -6
  76. package/modules/localmodels/stack_hardware.py +95 -265
  77. package/modules/localmodels/stack_hardware_text.py +263 -0
  78. package/modules/localmodels/stack_journal.py +3 -9
  79. package/modules/localmodels/stack_ledger.py +48 -18
  80. package/modules/localmodels/stack_lifecycle.py +33 -312
  81. package/modules/localmodels/stack_llm_ram.py +16 -6
  82. package/modules/localmodels/stack_mcp.py +729 -0
  83. package/modules/localmodels/stack_memory.py +0 -2
  84. package/modules/localmodels/stack_picks.py +62 -15
  85. package/modules/localmodels/stack_plan.py +19 -1
  86. package/modules/localmodels/stack_preflight.py +11 -19
  87. package/modules/localmodels/stack_progress.py +9 -1
  88. package/modules/localmodels/stack_remove.py +373 -0
  89. package/modules/localmodels/stack_route.py +101 -17
  90. package/modules/localmodels/stack_run.py +29 -0
  91. package/modules/localmodels/stack_suite.py +21 -10
  92. package/modules/localmodels/stack_summary.py +14 -0
  93. package/modules/localmodels/stack_try.py +238 -24
  94. package/modules/localmodels/stack_try_client.py +53 -15
  95. package/modules/localmodels/stack_try_docs.py +2 -2
  96. package/modules/localmodels/stack_view.py +24 -171
  97. package/modules/localmodels/stack_view_access.py +114 -1
  98. package/modules/localmodels/stack_view_agent.py +3 -13
  99. package/modules/localmodels/stack_view_hub.py +9 -10
  100. package/modules/localmodels/stack_view_llm.py +1 -1
  101. package/modules/localmodels/stack_view_sandbox.py +2 -2
  102. package/modules/localmodels/stack_view_schema.py +183 -0
  103. package/modules/localmodels/stack_view_serve.py +7 -1
  104. package/modules/localmodels/stack_view_service.py +1 -2
  105. package/modules/localmodels/stack_view_text.py +13 -9
  106. package/modules/localmodels/stack_warm.py +48 -4
  107. package/modules/localmodels/stack_warm_store.py +517 -0
  108. package/modules/localmodels/tools.json +32 -18
  109. package/modules/localmodels/transport.py +38 -13
  110. package/modules/localmodels/tui.py +28 -4
  111. package/modules/localmodels/tui_dialogs.py +136 -0
  112. package/modules/localmodels/tui_modals.py +279 -0
  113. package/modules/localmodels/tui_screen.py +113 -154
  114. package/modules/localmodels/tui_views.py +134 -203
  115. package/modules/localmodels/web/index.html +510 -101
  116. package/modules/localmodels/web/sizecalc/app.js +363 -10
  117. package/modules/localmodels/web/sizecalc/page.html +27 -3
  118. package/modules/localmodels/web/view/fleet.html +11 -2
  119. package/modules/localmodels/web/view/fleet.js +191 -17
  120. package/modules/localmodels/web/view/i18n.js +3 -2
  121. package/modules/localmodels/web/view/index.html +1 -1
  122. package/modules/localmodels/web/view/nav.js +22 -3
  123. package/modules/localmodels/web/view/view.css +63 -18
  124. package/modules/localmodels/web/view/view.js +169 -32
  125. package/modules/localmodels/windows_job.py +69 -0
  126. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
  127. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
  128. package/package.json +1 -1
  129. package/tool.json +1 -1
  130. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  131. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
  132. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,263 @@
1
+ """Human-readable hardware, card fit, plan header and reboot summaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from localmodels import catalog as cat
6
+ from localmodels import catalog_recipes, console, gpu_specs, metal, stack_capacity
7
+ from localmodels.budget import gib
8
+ from localmodels.estimator import (
9
+ AGENT_DISPLAY_RESERVE_BYTES,
10
+ AGENT_VRAM_SAFETY_BYTES,
11
+ HardwareBudget,
12
+ )
13
+ from localmodels.probe import HostFacts
14
+ from localmodels.records import Plan
15
+ from localmodels.stack_picks import label as fit_label
16
+ from localmodels.stack_picks import lines as pick_lines
17
+ from localmodels.stack_plan import Card, Hardware, platform_error
18
+
19
+ _MAC = "--unified-memory SIZE prices it as a smaller Mac" # the next step's option hint
20
+ _CARDS = "with several cards, --gpu N picks the card for the LLM and the decision model"
21
+
22
+
23
+ def on_metal(part: Plan | None) -> bool:
24
+ """The part runs on a Mac's Metal GPU."""
25
+ return part is not None and metal.on_device(part["placement"])
26
+
27
+
28
+ def plan_card(part: Plan | None, facts: HostFacts) -> int | None:
29
+ """Resolve the running service's CUDA UUID to its current host index (0 on a Mac)."""
30
+ if part is None:
31
+ return None
32
+ if on_metal(part):
33
+ return 0
34
+ devices = part["service"].get("env", {}).get("CUDA_VISIBLE_DEVICES")
35
+ if not isinstance(devices, str) or not devices or "," in devices:
36
+ return None
37
+ return next((g["index"] for g in facts.get("gpus") or [] if g["uuid"] == devices), None)
38
+
39
+
40
+ def card_head(c: Card) -> str:
41
+ arch = c["architecture"] or ""
42
+ if c["compute_capability"]:
43
+ arch = f"{arch} (compute capability {c['compute_capability']})".lstrip()
44
+ traits = [
45
+ t
46
+ for t in (
47
+ arch,
48
+ f"PCIe {c['pcie']}" if c["pcie"] else "",
49
+ {True: "display attached", False: "no display", None: ""}[c["display_active"]],
50
+ "MIG on" if c["mig"] else "",
51
+ )
52
+ if t
53
+ ]
54
+ return f"GPU {c['index']} {c['name']}" + "".join(f" · {t}" for t in traits)
55
+
56
+
57
+ def lines(hw: Hardware, command: str) -> list[str]:
58
+ """What ``stack hardware`` prints."""
59
+ out = [
60
+ f"Hardware of {hw['hostname']} (collected {console.local_time(hw['collected_at'])} local time; "
61
+ f"{hw['system'] or 'system unknown'})"
62
+ ]
63
+ if not hw["cards"]:
64
+ out.append(
65
+ " GPU Apple Silicon Metal working set unknown"
66
+ if hw.get("platform") == "darwin" and hw.get("arch") == "arm64"
67
+ else " GPU no NVIDIA GPU found"
68
+ )
69
+ strata_ids = {
70
+ r["id"] for r in catalog_recipes.components() if r["runtime"] in ("strata", "strata-poly")
71
+ }
72
+ for c in hw["cards"]:
73
+ reserved = f", driver reserved {gib(c['reserved_bytes'])}" if c["reserved_bytes"] else ""
74
+ on_mac = c.get("uuid") == metal.METAL_UUID
75
+ out += [
76
+ f" {card_head(c)}",
77
+ f" Metal working-set limit {gib(c['total_bytes'])}; the memory available "
78
+ f"now can give the GPU {gib(c['free_bytes'])}"
79
+ if on_mac
80
+ else f" VRAM {gib(c['total_bytes'])}: used {gib(c['used_bytes'])}, "
81
+ f"free {gib(c['free_bytes'])}{reserved}",
82
+ ]
83
+ if c["mig"]:
84
+ out.append(
85
+ " in MIG mode CUDA sees only the instances; this tool places nothing "
86
+ "on this card"
87
+ )
88
+ continue
89
+ out.append(
90
+ f" LLM may use {gib(c['llm_bytes'])} (free less a "
91
+ f"{AGENT_VRAM_SAFETY_BYTES >> 20} MiB safety margin and a "
92
+ f"{AGENT_DISPLAY_RESERVE_BYTES >> 20} MiB display reserve"
93
+ + (", kept even with no display attached" if c["display_active"] is False else "")
94
+ + (
95
+ f", less the smallest decision reserve {gib(c['decision_reserve_bytes'])}"
96
+ if c["decision_reserve_bytes"]
97
+ else ""
98
+ )
99
+ + ")"
100
+ )
101
+ out.append(
102
+ f" spec memory bandwidth {c['bandwidth_gb_s']:g} GB/s "
103
+ "(vendor spec, not measured)"
104
+ if c["bandwidth_gb_s"]
105
+ else " memory bandwidth: speed is estimated from "
106
+ f"{cat.DECODE_BASES['uma-class']} (not measured)"
107
+ if on_mac
108
+ else " memory bandwidth: the model is not in the spec table; speed is "
109
+ f"estimated from {cat.DECODE_BASES['discrete-class']}"
110
+ )
111
+ if c["display_active"]:
112
+ out.append(
113
+ " a display is attached: the desktop takes VRAM that changes at any "
114
+ "time; the plan prices what is free now"
115
+ )
116
+ if c["held_by"]:
117
+ out.append(" held by: " + "; ".join(c["held_by"]))
118
+ fits = [fit_label(f) for f in c["llm"][:3]]
119
+ shown = f"top 3 of {len(c['llm'])}" if len(c["llm"]) > 3 else f"{len(fits)} in all"
120
+ family = (
121
+ ""
122
+ if any(f["decode_tok_s"] is None or f["id"] in strata_ids for f in c["llm"])
123
+ else "llama.cpp "
124
+ )
125
+ out.append(
126
+ f" {family}LLMs that fit (agent posture, automatic eligibility, {shown}): "
127
+ + ", ".join(fits)
128
+ if fits
129
+ else " LLMs that fit: no validated LLM fits this card in the agent posture"
130
+ )
131
+ if fits and not c["auto"]:
132
+ out.append(
133
+ " another inference service runs on the Metal GPU; once sharing with "
134
+ "it is confirmed, add --share-gpu to stack plan"
135
+ if on_mac
136
+ else " other programs use this card, so --llm auto skips "
137
+ f"it; when sharing is confirmed, use --gpu {c['index']} --share-gpu"
138
+ )
139
+ slow = [
140
+ f
141
+ for f in c["llm"][:1]
142
+ if f["decode_tok_s"] is not None and f["decode_tok_s"] < cat.PLEASANT_FLOOR_TOK_S
143
+ ]
144
+ if slow:
145
+ out.append(
146
+ " note: the first choice's estimated decode is below the "
147
+ f"pleasant floor of {cat.PLEASANT_FLOOR_TOK_S:g} tok/s"
148
+ )
149
+ out += stack_capacity.lines(hw, command)
150
+ out.append(
151
+ f" RAM {gib(hw['ram_total_bytes'])}, available {gib(hw['ram_available_bytes'])}"
152
+ )
153
+ free = hw["disk_free_bytes"]
154
+ out.append(
155
+ f" disk {hw['disk_path']}: {gib(free) if free is not None else 'unknown'} free"
156
+ )
157
+ out.append(f" tier {hw['tier']}")
158
+ refused = platform_error(hw.get("platform", "linux"), arch=hw.get("arch"))
159
+ out += pick_lines(hw.get("picks") or [], None if refused else command)
160
+ out += [f" note {n}" for n in hw["notes"]]
161
+ mac = any(c.get("uuid") == metal.METAL_UUID for c in hw["cards"])
162
+ out.append(
163
+ "Planning is not possible now: fix the probe or resource problem first, then check the "
164
+ "hardware again."
165
+ if hw.get("planning_problem")
166
+ else "This platform can check its hardware; run the full suite on a supported Linux host "
167
+ "or an Apple Silicon Mac."
168
+ if platform_error(hw.get("platform", "linux"), arch=hw.get("arch"))
169
+ else f"Next: {command} install (plan, confirm once, install and verify), or {command} "
170
+ f"stack plan to only see and save the plan ({_MAC if mac else _CARDS})"
171
+ )
172
+ return out
173
+
174
+
175
+ def plan_lines(hw: Hardware, llm: Plan, *, decision: bool = True) -> list[str]:
176
+ """The hardware lines a stack plan summary opens with; the LLM's card is marked, and named
177
+ as the decision model's too when the plan has one (it only ever shares the LLM's card)."""
178
+ devices = llm["service"].get("env", {}).get("CUDA_VISIBLE_DEVICES")
179
+ llm_uuid = devices if isinstance(devices, str) and devices and "," not in devices else None
180
+ if on_metal(llm):
181
+ llm_uuid = metal.METAL_UUID
182
+ out = []
183
+ for c in hw["cards"]:
184
+ bandwidth = f", spec bandwidth {c['bandwidth_gb_s']:g} GB/s" if c["bandwidth_gb_s"] else ""
185
+ here = llm_uuid is not None and c.get("uuid") == llm_uuid
186
+ mark = (" (LLM and decision)" if decision else " (LLM)") if here else ""
187
+ if c.get("uuid") == metal.METAL_UUID:
188
+ out.append(
189
+ f" hardware GPU 0 {c['name']}{mark}: Metal working-set limit "
190
+ f"{gib(c['total_bytes'])}, {gib(c['free_bytes'])} for the GPU when planned "
191
+ "(unified memory)"
192
+ )
193
+ continue
194
+ out.append(
195
+ f" hardware GPU {c['index']} {c['name']}{mark}: VRAM {gib(c['total_bytes'])}, "
196
+ f"free when planned {gib(c['free_bytes'])}{bandwidth}"
197
+ )
198
+ out.append(
199
+ f" hardware RAM {gib(hw['ram_total_bytes'])}, available when planned "
200
+ f"{gib(hw['ram_available_bytes'])}; {hw['tier']}"
201
+ )
202
+ return out
203
+
204
+
205
+ def reboot_line(hw: Hardware | None, llm: Plan, command: str) -> str:
206
+ """What a reboot does to the planned services, and the one command that changes it."""
207
+ kind = llm["service"]["kind"]
208
+ if kind == "systemd-user":
209
+ manager = hw.get("service_manager") if hw else None
210
+ if manager and manager["linger"]:
211
+ return (
212
+ " reboot the services start at boot (systemd --user, linger on); nothing to "
213
+ f"run; {command} stack up checks them and starts any that are missing"
214
+ )
215
+ return " reboot the services start when you log in (systemd --user)" + (
216
+ "; linger is off, so they do not start at boot until someone logs in. To start "
217
+ "them at boot, run once: loginctl enable-linger"
218
+ if manager
219
+ else ""
220
+ )
221
+ if kind == "launchd-user":
222
+ return (
223
+ " reboot the launchd jobs belong to the current login session; after a reboot "
224
+ f"run {command} stack up to start them"
225
+ )
226
+ return (
227
+ " reboot the services run under nohup and do not come back after a reboot; run "
228
+ f"{command} stack up to start them, without reinstalling"
229
+ )
230
+
231
+
232
+ def slow_warning(facts: HostFacts, llm: Plan) -> list[str]:
233
+ """A note when the stack's LLM, priced at its card's spec bandwidth, decodes below the
234
+ pleasant floor; silent where the card model has no published figure."""
235
+ model, index = llm["model"], plan_card(llm, facts)
236
+ gpu = next((g for g in facts.get("gpus") or [] if g["index"] == index), None)
237
+ mid = model.get("id")
238
+ entry = cat.find_entry(mid) if isinstance(mid, str) else None
239
+ variant = (
240
+ next((v for v in entry.variants if v.quant == model.get("quant")), None) if entry else None
241
+ )
242
+ bandwidth = gpu_specs.bandwidth_gb_s(gpu["name"]) if gpu else None
243
+ if entry is None or variant is None or gpu is None or bandwidth is None:
244
+ return []
245
+ budget = HardwareBudget(0, 0, 0, gpu_bandwidth_gb_s=bandwidth)
246
+ tok_s = cat.decode_estimate(entry, variant, budget).tok_s
247
+ if tok_s >= cat.PLEASANT_FLOOR_TOK_S:
248
+ return []
249
+ return [
250
+ f"LLM: at the {gpu['name']} spec memory bandwidth of {bandwidth:g} GB/s, single-stream "
251
+ f"decode is about {tok_s:.0f} tok/s (estimate), below the pleasant floor of "
252
+ f"{cat.PLEASANT_FLOOR_TOK_S:g} tok/s; --llm can pick a smaller model"
253
+ ]
254
+
255
+
256
+ def agent_label(llm: Plan) -> str:
257
+ """The concurrency and KV types an agent-posture LLM launches with; empty otherwise."""
258
+ launch = llm["launch"]
259
+ if launch.get("posture") != "agent":
260
+ return ""
261
+ kv = launch.get("kv_types")
262
+ pair = [str(t) for t in kv] if isinstance(kv, list) else ["q8_0", "q8_0"]
263
+ return f"{launch.get('slots')} parallel sessions sharing the KV ({'/'.join(pair)}), "
@@ -24,7 +24,7 @@ from collections.abc import Callable
24
24
  from pathlib import Path
25
25
  from typing import TypedDict
26
26
 
27
- from localmodels import hosts
27
+ from localmodels import hosts, process_identity
28
28
  from localmodels.plan_envelope import utc_now
29
29
  from localmodels.stack_events import ProgressEvent, validate_progress
30
30
 
@@ -154,15 +154,9 @@ class Journal:
154
154
 
155
155
 
156
156
  def _alive(pid: object) -> bool:
157
- if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
157
+ if not isinstance(pid, int) or isinstance(pid, bool):
158
158
  return False
159
- try:
160
- os.kill(pid, 0)
161
- except ProcessLookupError:
162
- return False
163
- except PermissionError: # someone else's process: not our apply
164
- return False
165
- return True
159
+ return process_identity.alive(pid, foreign=False) # someone else's process: not our apply
166
160
 
167
161
 
168
162
  def _counters(raw: object) -> dict[str, Counter]:
@@ -17,9 +17,16 @@ from collections.abc import Callable, Sequence
17
17
  from dataclasses import dataclass
18
18
  from datetime import datetime, timezone
19
19
  from itertools import pairwise
20
- from typing import Any, Literal, TypedDict
21
-
22
- from localmodels import cli_help, stack_lifecycle, stack_up, stack_verify, stack_view_gpu
20
+ from typing import Literal, TypedDict
21
+
22
+ from localmodels import (
23
+ cli_help,
24
+ http_local,
25
+ stack_lifecycle,
26
+ stack_up,
27
+ stack_verify,
28
+ stack_view_gpu,
29
+ )
23
30
  from localmodels.records import Plan
24
31
  from localmodels.remote_ops_service import listener_problem
25
32
  from localmodels.stack_plan import StackError, StackPlan
@@ -144,13 +151,6 @@ def parse_metrics(text: str) -> Tokens | None:
144
151
  return {"prompt": found[TOKEN_METRICS[0]], "generated": found[TOKEN_METRICS[1]]}
145
152
 
146
153
 
147
- class _NoRedirect(urllib.request.HTTPRedirectHandler):
148
- def redirect_request(
149
- self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str
150
- ) -> None:
151
- return None
152
-
153
-
154
154
  def read_metrics(part: Plan) -> Tokens | None:
155
155
  """Ask only the owned local listener, without proxies, redirects, inference or raw errors."""
156
156
  port = part["service"]["port"]
@@ -163,7 +163,7 @@ def read_metrics(part: Plan) -> Tokens | None:
163
163
  request = urllib.request.Request(
164
164
  f"http://127.0.0.1:{port}/metrics", headers={"Authorization": f"Bearer {secret}"}
165
165
  )
166
- opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
166
+ opener = http_local.no_proxy_opener(allow_redirects=False)
167
167
  try:
168
168
  with opener.open(request, timeout=2) as response:
169
169
  body = response.read(METRICS_BYTES + 1)
@@ -190,7 +190,19 @@ def power(indices: list[int], readings: Sequence[stack_view_gpu.GpuLoad]) -> flo
190
190
  return sum(v for v in values if v is not None)
191
191
 
192
192
 
193
- def estimate(plan_id: str, indices: list[int], samples: Sequence[Sample]) -> Report:
193
+ def _counter_reset(counters: Sequence[Tokens]) -> bool:
194
+ return any(
195
+ b["prompt"] < a["prompt"] or b["generated"] < a["generated"] for a, b in pairwise(counters)
196
+ )
197
+
198
+
199
+ def estimate(
200
+ plan_id: str,
201
+ indices: list[int],
202
+ samples: Sequence[Sample],
203
+ *,
204
+ streams: Sequence[Sequence[Tokens | None]] = (),
205
+ ) -> Report:
194
206
  """Same-window energy/token ratio, then an explicitly labelled historical extrapolation."""
195
207
  elapsed = samples[-1].seconds - samples[0].seconds if len(samples) > 1 else 0.0
196
208
  report: Report = {
@@ -233,9 +245,8 @@ def estimate(plan_id: str, indices: list[int], samples: Sequence[Sample]) -> Rep
233
245
  report["unavailable"] = "LLM cumulative token counters unavailable"
234
246
  return report
235
247
  counters = [s.tokens for s in samples if s.tokens is not None]
236
- if any(
237
- b["prompt"] < a["prompt"] or b["generated"] < a["generated"] for a, b in pairwise(counters)
238
- ):
248
+ checked = [counters, *([t for t in stream if t is not None] for stream in streams)]
249
+ if any(_counter_reset(stream) for stream in checked):
239
250
  report["unavailable"] = "LLM counters reset during the sampling window"
240
251
  return report
241
252
  delta: Tokens = {
@@ -253,6 +264,21 @@ def estimate(plan_id: str, indices: list[int], samples: Sequence[Sample]) -> Rep
253
264
  return report
254
265
 
255
266
 
267
+ def _read_tick(
268
+ primary: Plan, fast: Plan | None, metrics: Callable[[Plan], Tokens | None]
269
+ ) -> tuple[Tokens | None, tuple[Tokens | None, ...]]:
270
+ t1 = metrics(primary)
271
+ if fast is None:
272
+ return t1, (t1,)
273
+ t2 = metrics(fast)
274
+ if t1 is None or t2 is None:
275
+ return None, (t1, t2)
276
+ return (
277
+ Tokens(prompt=t1["prompt"] + t2["prompt"], generated=t1["generated"] + t2["generated"]),
278
+ (t1, t2),
279
+ )
280
+
281
+
256
282
  def sample(
257
283
  plan: StackPlan,
258
284
  seconds: float = 5,
@@ -263,11 +289,15 @@ def sample(
263
289
  clock: Callable[[], float] = time.monotonic,
264
290
  wait: Callable[[float], None] = time.sleep,
265
291
  ) -> Report:
266
- indices = gpu_indices(plan["llm"])
292
+ fast = plan.get("llm_fast")
293
+ indices = sorted({*gpu_indices(plan["llm"]), *(gpu_indices(fast) if fast is not None else ())})
267
294
  samples: list[Sample] = []
295
+ per_llm: list[list[Tokens | None]] = [[], []] if fast is not None else [[]]
268
296
  started = clock()
269
297
  while True:
270
- tokens = metrics(plan["llm"])
298
+ tokens, parts = _read_tick(plan["llm"], fast, metrics)
299
+ for stream, item in zip(per_llm, parts, strict=True):
300
+ stream.append(item)
271
301
  watts = power(indices, gpu()) if indices else None
272
302
  now = clock()
273
303
  samples.append(Sample(now, watts, tokens))
@@ -275,7 +305,7 @@ def sample(
275
305
  if remaining <= 0 or not indices or watts is None:
276
306
  break
277
307
  wait(min(interval, remaining))
278
- return estimate(plan["plan_id"], indices, samples)
308
+ return estimate(plan["plan_id"], indices, samples, streams=per_llm)
279
309
 
280
310
 
281
311
  def add_money(report: Report, price_kwh: float) -> None: