@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.35

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 (140) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +138 -97
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +5 -1
  11. package/modules/localmodels/catalog.json +51 -10
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines.json +57 -1
  22. package/modules/localmodels/engines.py +6 -2
  23. package/modules/localmodels/estimator.py +21 -7
  24. package/modules/localmodels/frontend.py +4 -4
  25. package/modules/localmodels/gateway.py +14 -4
  26. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  27. package/modules/localmodels/gateway_bifrost.py +70 -57
  28. package/modules/localmodels/gateway_probe.py +3 -4
  29. package/modules/localmodels/gguf.py +7 -0
  30. package/modules/localmodels/harness.py +24 -25
  31. package/modules/localmodels/harness_gateway.py +19 -10
  32. package/modules/localmodels/harness_probe.py +33 -6
  33. package/modules/localmodels/hosts.py +73 -9
  34. package/modules/localmodels/install.py +36 -6
  35. package/modules/localmodels/library_cli.py +179 -0
  36. package/modules/localmodels/library_convert.py +132 -0
  37. package/modules/localmodels/library_gateway.py +471 -0
  38. package/modules/localmodels/library_jobs.py +314 -0
  39. package/modules/localmodels/library_model.py +246 -0
  40. package/modules/localmodels/library_pricing.py +347 -0
  41. package/modules/localmodels/library_serve.py +348 -0
  42. package/modules/localmodels/library_state.py +373 -0
  43. package/modules/localmodels/library_status.py +349 -0
  44. package/modules/localmodels/llm_rank.py +16 -2
  45. package/modules/localmodels/memcalc.py +7 -30
  46. package/modules/localmodels/metal.py +26 -0
  47. package/modules/localmodels/plan_envelope.py +4 -1
  48. package/modules/localmodels/preparation.py +49 -0
  49. package/modules/localmodels/probe.py +8 -8
  50. package/modules/localmodels/process_identity.py +536 -9
  51. package/modules/localmodels/quant_formats.py +123 -0
  52. package/modules/localmodels/recommend_cli.py +8 -4
  53. package/modules/localmodels/records.py +1 -0
  54. package/modules/localmodels/remote_ops.py +104 -6
  55. package/modules/localmodels/remote_ops_download.py +17 -2
  56. package/modules/localmodels/remote_ops_prepare.py +406 -0
  57. package/modules/localmodels/remote_ops_remove.py +40 -7
  58. package/modules/localmodels/remote_ops_service.py +110 -8
  59. package/modules/localmodels/remote_ops_verify.py +15 -2
  60. package/modules/localmodels/runtime_auth.py +31 -1
  61. package/modules/localmodels/runtime_cli.py +3 -4
  62. package/modules/localmodels/runtime_io.py +50 -6
  63. package/modules/localmodels/service_autostart.py +45 -1
  64. package/modules/localmodels/service_control.py +13 -0
  65. package/modules/localmodels/service_deployment.py +12 -3
  66. package/modules/localmodels/service_jobs.py +33 -4
  67. package/modules/localmodels/service_probe.py +67 -13
  68. package/modules/localmodels/service_stop.py +152 -0
  69. package/modules/localmodels/service_worker.py +9 -1
  70. package/modules/localmodels/services_cli.py +50 -6
  71. package/modules/localmodels/setup_inspection.py +34 -25
  72. package/modules/localmodels/setup_text.py +118 -0
  73. package/modules/localmodels/sizecalc.py +625 -0
  74. package/modules/localmodels/sizecalc_cli.py +249 -0
  75. package/modules/localmodels/stack.py +69 -17
  76. package/modules/localmodels/stack_args.py +91 -19
  77. package/modules/localmodels/stack_auto.py +78 -0
  78. package/modules/localmodels/stack_binding.py +23 -35
  79. package/modules/localmodels/stack_card.py +195 -0
  80. package/modules/localmodels/stack_cleanup.py +379 -0
  81. package/modules/localmodels/stack_clients.py +4 -1
  82. package/modules/localmodels/stack_compose.py +150 -194
  83. package/modules/localmodels/stack_console.py +2 -0
  84. package/modules/localmodels/stack_decision.py +3 -2
  85. package/modules/localmodels/stack_down.py +189 -0
  86. package/modules/localmodels/stack_events.py +54 -0
  87. package/modules/localmodels/stack_hardware.py +22 -23
  88. package/modules/localmodels/stack_journal.py +29 -8
  89. package/modules/localmodels/stack_ledger.py +411 -0
  90. package/modules/localmodels/stack_lifecycle.py +162 -167
  91. package/modules/localmodels/stack_llm_ram.py +57 -5
  92. package/modules/localmodels/stack_memory.py +721 -0
  93. package/modules/localmodels/stack_picks.py +139 -0
  94. package/modules/localmodels/stack_plan.py +140 -22
  95. package/modules/localmodels/stack_ports.py +22 -0
  96. package/modules/localmodels/stack_preflight.py +699 -0
  97. package/modules/localmodels/stack_review.py +123 -5
  98. package/modules/localmodels/stack_rollback.py +2 -0
  99. package/modules/localmodels/stack_route.py +256 -0
  100. package/modules/localmodels/stack_run.py +11 -0
  101. package/modules/localmodels/stack_suite.py +102 -17
  102. package/modules/localmodels/stack_summary.py +65 -4
  103. package/modules/localmodels/stack_try.py +354 -0
  104. package/modules/localmodels/stack_try_client.py +194 -0
  105. package/modules/localmodels/stack_try_docs.py +139 -0
  106. package/modules/localmodels/stack_up.py +8 -1
  107. package/modules/localmodels/stack_update.py +29 -4
  108. package/modules/localmodels/stack_verify.py +3 -1
  109. package/modules/localmodels/stack_view.py +10 -11
  110. package/modules/localmodels/stack_view_apply.py +4 -2
  111. package/modules/localmodels/stack_view_events.py +2 -1
  112. package/modules/localmodels/stack_view_serve.py +3 -0
  113. package/modules/localmodels/stack_view_text.py +1 -1
  114. package/modules/localmodels/stack_view_words.py +4 -1
  115. package/modules/localmodels/stack_warm.py +574 -0
  116. package/modules/localmodels/stack_whatif.py +558 -0
  117. package/modules/localmodels/suite.py +48 -39
  118. package/modules/localmodels/tool_archive.py +40 -0
  119. package/modules/localmodels/tools.json +8 -0
  120. package/modules/localmodels/transport.py +1 -0
  121. package/modules/localmodels/vision.py +8 -1
  122. package/modules/localmodels/web/sizecalc/app.js +431 -0
  123. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  124. package/modules/localmodels/web/sizecalc/page.html +362 -0
  125. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  126. package/modules/localmodels/web/view/i18n.js +1 -1
  127. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  128. package/modules/localmodels/web/view/logo-codex.png +0 -0
  129. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  130. package/modules/localmodels/web/view/view.css +4 -0
  131. package/modules/localmodels/web/view/view.js +15 -6
  132. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/METADATA +1 -1
  133. package/modules/simplex_localmodels-0.1.0.dev35.dist-info/RECORD +241 -0
  134. package/package.json +1 -1
  135. package/tool.json +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  137. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/WHEEL +0 -0
  138. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/entry_points.txt +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/NOTICE +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,411 @@
1
+ """Local GPU energy estimates from a bounded window of power and llama-server counters.
2
+
3
+ Power includes idle draw and other workloads on the selected cards. The window is integrated
4
+ with the trapezoid rule; its energy per processed prompt + generated token is extrapolated to
5
+ the server's current counters, never presented as a measured lifetime energy bill. No inference
6
+ or cloud request is made, no history is stored, and missing readings stay unavailable.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import math
14
+ import time
15
+ import urllib.request
16
+ from collections.abc import Callable, Sequence
17
+ from dataclasses import dataclass
18
+ from datetime import datetime, timezone
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
23
+ from localmodels.records import Plan
24
+ from localmodels.remote_ops_service import listener_problem
25
+ from localmodels.stack_plan import StackError, StackPlan
26
+
27
+ SCHEMA = "localmodels.stack-ledger/v1"
28
+ METRICS_BYTES = 1 << 20
29
+ TOKEN_METRICS = ("llamacpp:prompt_tokens_total", "llamacpp:tokens_predicted_total")
30
+
31
+
32
+ class CloudPrice(TypedDict):
33
+ model: str
34
+ period: Literal["peak", "off-peak"]
35
+ input_usd_per_million: float
36
+ output_usd_per_million: float
37
+ source: str
38
+ checked_on: str
39
+ terms: str
40
+
41
+
42
+ # Official pricing table, cache misses, standard API; read only at development time.
43
+ CLOUD_PRICES: tuple[CloudPrice, ...] = (
44
+ {
45
+ "model": "deepseek-flash",
46
+ "period": "peak",
47
+ "input_usd_per_million": 0.30,
48
+ "output_usd_per_million": 1.20,
49
+ "source": "https://api-docs.deepseek.com/quick_start/pricing",
50
+ "checked_on": "2026-11-12",
51
+ "terms": "Peak hours, cache-miss input, standard API; excludes discounts and taxes.",
52
+ },
53
+ {
54
+ "model": "deepseek-flash",
55
+ "period": "off-peak",
56
+ "input_usd_per_million": 0.15,
57
+ "output_usd_per_million": 0.60,
58
+ "source": "https://api-docs.deepseek.com/quick_start/pricing",
59
+ "checked_on": "2026-11-12",
60
+ "terms": "Off-peak hours, cache-miss input, standard API; excludes discounts and taxes.",
61
+ },
62
+ {
63
+ "model": "deepseek-v4-pro",
64
+ "period": "peak",
65
+ "input_usd_per_million": 1.32,
66
+ "output_usd_per_million": 3.96,
67
+ "source": "https://api-docs.deepseek.com/quick_start/pricing",
68
+ "checked_on": "2026-11-12",
69
+ "terms": "Peak hours, cache-miss input, standard API; excludes discounts and taxes.",
70
+ },
71
+ {
72
+ "model": "deepseek-v4-pro",
73
+ "period": "off-peak",
74
+ "input_usd_per_million": 0.66,
75
+ "output_usd_per_million": 1.98,
76
+ "source": "https://api-docs.deepseek.com/quick_start/pricing",
77
+ "checked_on": "2026-11-12",
78
+ "terms": "Off-peak hours, cache-miss input, standard API; excludes discounts and taxes.",
79
+ },
80
+ )
81
+
82
+
83
+ class Tokens(TypedDict):
84
+ prompt: int
85
+ generated: int
86
+
87
+
88
+ class CloudComparison(CloudPrice):
89
+ estimated_same_token_cost: float
90
+
91
+
92
+ class Money(TypedDict):
93
+ currency: str
94
+ price_per_kwh: float
95
+ estimated_total_electricity: float | None
96
+ estimated_electricity_per_million_tokens: float | None
97
+ cloud_references: list[CloudComparison]
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class Sample:
102
+ seconds: float
103
+ power_w: float | None
104
+ tokens: Tokens | None
105
+
106
+
107
+ class Report(TypedDict):
108
+ schema: str
109
+ plan_id: str
110
+ sampled_at: str
111
+ window_seconds: float
112
+ sample_count: int
113
+ power_sample_count: int
114
+ gpu_indices: list[int]
115
+ average_gpu_w: float | None
116
+ window_kwh: float | None
117
+ tokens: Tokens | None
118
+ window_tokens: Tokens | None
119
+ kwh_per_million_tokens: float | None
120
+ estimated_total_kwh: float | None
121
+ unavailable: str | None
122
+ notes: list[str]
123
+ money: Money | None
124
+
125
+
126
+ def parse_metrics(text: str) -> Tokens | None:
127
+ """Both unlabelled cumulative counters are required; reject nonfinite or repeated values."""
128
+ found: dict[str, int] = {}
129
+ for line in text.splitlines():
130
+ cells = line.split()
131
+ if not cells or cells[0].startswith("#") or cells[0] not in TOKEN_METRICS:
132
+ continue
133
+ if len(cells) not in (2, 3) or cells[0] in found:
134
+ return None
135
+ try:
136
+ value = float(cells[1])
137
+ except ValueError:
138
+ return None
139
+ if not math.isfinite(value) or value < 0 or not value.is_integer():
140
+ return None
141
+ found[cells[0]] = int(value)
142
+ if any(name not in found for name in TOKEN_METRICS):
143
+ return None
144
+ return {"prompt": found[TOKEN_METRICS[0]], "generated": found[TOKEN_METRICS[1]]}
145
+
146
+
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
+ def read_metrics(part: Plan) -> Tokens | None:
155
+ """Ask only the owned local listener, without proxies, redirects, inference or raw errors."""
156
+ port = part["service"]["port"]
157
+ pids = stack_lifecycle.service_pids(part)
158
+ if not pids or listener_problem(port, pids):
159
+ return None
160
+ secret = stack_verify.key(part)
161
+ if secret is None:
162
+ return None
163
+ request = urllib.request.Request(
164
+ f"http://127.0.0.1:{port}/metrics", headers={"Authorization": f"Bearer {secret}"}
165
+ )
166
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
167
+ try:
168
+ with opener.open(request, timeout=2) as response:
169
+ body = response.read(METRICS_BYTES + 1)
170
+ except (OSError, ValueError):
171
+ return None
172
+ return parse_metrics(body.decode("utf-8", "replace")) if len(body) <= METRICS_BYTES else None
173
+
174
+
175
+ def gpu_indices(part: Plan) -> list[int]:
176
+ cards = part["placement"].get("gpus")
177
+ if not isinstance(cards, list):
178
+ return []
179
+ return sorted(
180
+ {int(c["index"]) for c in cards if isinstance(c, dict) and isinstance(c.get("index"), int)}
181
+ )
182
+
183
+
184
+ def power(indices: list[int], readings: Sequence[stack_view_gpu.GpuLoad]) -> float | None:
185
+ """Require a live, finite power reading for every selected card, including zero watts."""
186
+ by_index = {r["index"]: r for r in readings if r["basis"] == "live"}
187
+ values = [by_index[i]["power_w"] if i in by_index else None for i in indices]
188
+ if not values or any(v is None or not math.isfinite(v) or v < 0 for v in values):
189
+ return None
190
+ return sum(v for v in values if v is not None)
191
+
192
+
193
+ def estimate(plan_id: str, indices: list[int], samples: Sequence[Sample]) -> Report:
194
+ """Same-window energy/token ratio, then an explicitly labelled historical extrapolation."""
195
+ elapsed = samples[-1].seconds - samples[0].seconds if len(samples) > 1 else 0.0
196
+ report: Report = {
197
+ "schema": SCHEMA,
198
+ "plan_id": plan_id,
199
+ "sampled_at": datetime.now(timezone.utc).isoformat(),
200
+ "window_seconds": elapsed,
201
+ "sample_count": len(samples),
202
+ "power_sample_count": sum(s.power_w is not None for s in samples),
203
+ "gpu_indices": indices,
204
+ "average_gpu_w": None,
205
+ "window_kwh": None,
206
+ "tokens": samples[-1].tokens if samples else None,
207
+ "window_tokens": None,
208
+ "kwh_per_million_tokens": None,
209
+ "estimated_total_kwh": None,
210
+ "unavailable": None,
211
+ "notes": [
212
+ "GPU-only power on the selected cards; excludes CPU and whole-system power.",
213
+ "Includes idle power and other workloads on those cards; no workload attribution.",
214
+ "Tokens are processed prompt + generated tokens since this server started; "
215
+ "cached prompt tokens may be excluded by llama-server.",
216
+ "Historical energy is extrapolated at this window's energy/token ratio, not "
217
+ "a lifetime power measurement; idle time outside the window is not accounted for.",
218
+ ],
219
+ "money": None,
220
+ }
221
+ if not indices or any(s.power_w is None for s in samples):
222
+ report["unavailable"] = "NVIDIA power readings unavailable for the selected LLM GPUs"
223
+ return report
224
+ if elapsed <= 0 or any(b.seconds <= a.seconds for a, b in pairwise(samples)):
225
+ report["unavailable"] = "a positive sampling window needs at least two readings"
226
+ return report
227
+ joules = sum(
228
+ (float(a.power_w or 0) + float(b.power_w or 0)) / 2 * (b.seconds - a.seconds)
229
+ for a, b in pairwise(samples)
230
+ )
231
+ report["average_gpu_w"], report["window_kwh"] = joules / elapsed, joules / 3_600_000
232
+ if any(s.tokens is None for s in samples):
233
+ report["unavailable"] = "LLM cumulative token counters unavailable"
234
+ return report
235
+ 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
+ ):
239
+ report["unavailable"] = "LLM counters reset during the sampling window"
240
+ return report
241
+ delta: Tokens = {
242
+ "prompt": counters[-1]["prompt"] - counters[0]["prompt"],
243
+ "generated": counters[-1]["generated"] - counters[0]["generated"],
244
+ }
245
+ report["window_tokens"] = delta
246
+ count = delta["prompt"] + delta["generated"]
247
+ if not count:
248
+ report["unavailable"] = "no tokens processed during the sampling window; try during use"
249
+ return report
250
+ per_token = joules / 3_600_000 / count
251
+ report["kwh_per_million_tokens"] = per_token * 1_000_000
252
+ report["estimated_total_kwh"] = per_token * (counters[-1]["prompt"] + counters[-1]["generated"])
253
+ return report
254
+
255
+
256
+ def sample(
257
+ plan: StackPlan,
258
+ seconds: float = 5,
259
+ interval: float = 1,
260
+ *,
261
+ metrics: Callable[[Plan], Tokens | None] = read_metrics,
262
+ gpu: Callable[[], list[stack_view_gpu.GpuLoad]] = stack_view_gpu.read,
263
+ clock: Callable[[], float] = time.monotonic,
264
+ wait: Callable[[float], None] = time.sleep,
265
+ ) -> Report:
266
+ indices = gpu_indices(plan["llm"])
267
+ samples: list[Sample] = []
268
+ started = clock()
269
+ while True:
270
+ tokens = metrics(plan["llm"])
271
+ watts = power(indices, gpu()) if indices else None
272
+ now = clock()
273
+ samples.append(Sample(now, watts, tokens))
274
+ remaining = seconds - (now - started)
275
+ if remaining <= 0 or not indices or watts is None:
276
+ break
277
+ wait(min(interval, remaining))
278
+ return estimate(plan["plan_id"], indices, samples)
279
+
280
+
281
+ def add_money(report: Report, price_kwh: float) -> None:
282
+ """USD only, so electricity and static API references share a currency without FX guesses."""
283
+ totals = report["tokens"]
284
+ kwh, per_million = report["estimated_total_kwh"], report["kwh_per_million_tokens"]
285
+ report["money"] = {
286
+ "currency": "USD",
287
+ "price_per_kwh": price_kwh,
288
+ "estimated_total_electricity": None if kwh is None else kwh * price_kwh,
289
+ "estimated_electricity_per_million_tokens": (
290
+ None if per_million is None else per_million * price_kwh
291
+ ),
292
+ "cloud_references": [
293
+ {
294
+ **price,
295
+ "estimated_same_token_cost": (
296
+ totals["prompt"] * price["input_usd_per_million"]
297
+ + totals["generated"] * price["output_usd_per_million"]
298
+ )
299
+ / 1_000_000,
300
+ }
301
+ for price in CLOUD_PRICES
302
+ if totals is not None
303
+ ],
304
+ }
305
+
306
+
307
+ def lines(report: Report) -> list[str]:
308
+ out = [
309
+ "Energy ledger (estimates)",
310
+ f" Sampling window {report['window_seconds']:.3f} s; "
311
+ f"{report['sample_count']} samples, {report['power_sample_count']} with GPU power.",
312
+ ]
313
+ if tokens := report["tokens"]:
314
+ prompt, generated = tokens["prompt"], tokens["generated"]
315
+ out.append(
316
+ f" Since server start: {prompt:,} prompt tokens, {generated:,} generated tokens "
317
+ f"({prompt + generated:,} total)."
318
+ )
319
+ if report["window_kwh"] is not None:
320
+ out.append(f" Window GPU energy estimate: {report['window_kwh']:.8f} kWh.")
321
+ if report["unavailable"]:
322
+ out.append(
323
+ f" Energy per million tokens / historical total unavailable: {report['unavailable']}."
324
+ )
325
+ else:
326
+ out.extend(
327
+ [
328
+ f" Estimated kWh / million processed tokens: {report['kwh_per_million_tokens']:.6f}.",
329
+ f" Estimated kWh for tokens so far (extrapolated): {report['estimated_total_kwh']:.6f}.",
330
+ ]
331
+ )
332
+ if money := report["money"]:
333
+ total = money["estimated_total_electricity"]
334
+ per_million = money["estimated_electricity_per_million_tokens"]
335
+ total_text = f"{total:.6f}" if total is not None else "unavailable"
336
+ rate_text = f"{per_million:.6f}" if per_million is not None else "unavailable"
337
+ out.append(
338
+ f" Electricity USD / kWh {money['price_per_kwh']}; estimated total USD {total_text}; "
339
+ f"estimated USD / million processed tokens {rate_text}."
340
+ )
341
+ out.append(
342
+ " Cloud references use the same counts, standard cache-miss input; "
343
+ "tokenizers, quality and billing differ. These are not verified savings."
344
+ )
345
+ out.append(
346
+ " Peak hours are 01:00-04:00 and 06:00-10:00 UTC, Monday through Friday, "
347
+ "excluding Chinese public holidays. All other hours are off-peak."
348
+ )
349
+ by_model: dict[str, dict[str, CloudComparison]] = {}
350
+ for price in money["cloud_references"]:
351
+ by_model.setdefault(price["model"], {})[price["period"]] = price
352
+ for periods in by_model.values():
353
+ peak, off_peak = periods["peak"], periods["off-peak"]
354
+ out.append(
355
+ f" {peak['model']}: estimated USD {peak['estimated_same_token_cost']:.6f} (peak) "
356
+ f"to {off_peak['estimated_same_token_cost']:.6f} (off-peak); "
357
+ f"input/output USD per million {peak['input_usd_per_million']:.2f}/"
358
+ f"{peak['output_usd_per_million']:.2f} (peak) to "
359
+ f"{off_peak['input_usd_per_million']:.2f}/"
360
+ f"{off_peak['output_usd_per_million']:.2f} (off-peak); {peak['terms']} "
361
+ f"{off_peak['terms']} Source {peak['source']} (checked {peak['checked_on']})."
362
+ )
363
+ out.extend(f" {note}" for note in report["notes"])
364
+ return out
365
+
366
+
367
+ def _number(text: str) -> float:
368
+ value = float(text)
369
+ if not math.isfinite(value) or value < 0:
370
+ raise argparse.ArgumentTypeError("a finite nonnegative number")
371
+ return value
372
+
373
+
374
+ def add_parser(actions: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
375
+ parser = actions.add_parser(
376
+ "ledger", help="estimate GPU-only energy from local power and tokens"
377
+ )
378
+ parser.add_argument(
379
+ "--seconds", type=_number, default=5.0, help="sampling seconds, 0.1..60 (default 5)"
380
+ )
381
+ parser.add_argument(
382
+ "--interval", type=_number, default=1.0, help="seconds between samples, 0.1..60 (default 1)"
383
+ )
384
+ parser.add_argument(
385
+ "--price-kwh", type=_number, help="your electricity price in USD/kWh; no default"
386
+ )
387
+ parser.add_argument("--json", action="store_true", help=f"the report as {SCHEMA}")
388
+ cli_help.document(
389
+ parser,
390
+ "Read local cumulative LLM counters and NVIDIA power without sending inference. "
391
+ "Energy is estimated over the sampling window and extrapolated to tokens served. "
392
+ "GPU-only, no CPU or whole-system power. No history or telemetry. Money and dated "
393
+ "static cloud references appear only with --price-kwh, in USD.",
394
+ examples=[
395
+ ("%(prog)s --json", "sample for five seconds; unavailable without readings"),
396
+ ("%(prog)s --price-kwh 0.15", "use your own USD/kWh electricity price"),
397
+ ],
398
+ )
399
+
400
+
401
+ def cli(args: argparse.Namespace) -> int:
402
+ if not 0.1 <= args.seconds <= 60 or not 0.1 <= args.interval <= 60:
403
+ raise StackError("--seconds and --interval must be between 0.1 and 60")
404
+ plan = stack_up._accepted()
405
+ if plan is None or stack_up.drift(plan):
406
+ raise StackError("no unchanged accepted local stack; run stack install or stack up")
407
+ report = sample(plan, args.seconds, args.interval)
408
+ if args.price_kwh is not None:
409
+ add_money(report, args.price_kwh)
410
+ print(json.dumps(report, indent=1, allow_nan=False) if args.json else "\n".join(lines(report)))
411
+ return 0