@simplexai/localmodels-linux-arm64 0.1.0-dev.103 → 0.1.0-dev.105

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 (172) hide show
  1. package/LICENSE +201 -0
  2. package/{modules/simplex_localmodels-0.1.0.dev103.dist-info/licenses/NOTICE → NOTICE} +42 -13
  3. package/README.md +10 -0
  4. package/bootstrap.identity +1 -1
  5. package/bootstrap.sha256 +159 -158
  6. package/modules/localmodels/__init__.py +1 -1
  7. package/modules/localmodels/__main__.py +204 -86
  8. package/modules/localmodels/apple_sensors.py +23 -0
  9. package/modules/localmodels/approval.py +25 -2
  10. package/modules/localmodels/catalog.json +584 -158
  11. package/modules/localmodels/catalog.py +18 -3
  12. package/modules/localmodels/catalog_recipes.py +64 -6
  13. package/modules/localmodels/cli_help.py +10 -0
  14. package/modules/localmodels/cli_parser.py +313 -230
  15. package/modules/localmodels/component.py +21 -3
  16. package/modules/localmodels/console.py +1 -1
  17. package/modules/localmodels/context_policy.py +6 -5
  18. package/modules/localmodels/custom_probe.py +4 -2
  19. package/modules/localmodels/debug_cli.py +0 -12
  20. package/modules/localmodels/debug_mode.py +0 -6
  21. package/modules/localmodels/decode_calibration.json +3 -4
  22. package/modules/localmodels/decode_calibration.py +5 -2
  23. package/modules/localmodels/deploy.py +11 -1
  24. package/modules/localmodels/deployment_lifecycle.py +1 -1
  25. package/modules/localmodels/download-mirrors.json +1 -1
  26. package/modules/localmodels/engine_adapters/base.py +11 -1
  27. package/modules/localmodels/engine_adapters/strata_poly.py +65 -3
  28. package/modules/localmodels/engine_adapters/suite_plan.py +61 -24
  29. package/modules/localmodels/engines-b11583.json +6 -26
  30. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +3 -15
  31. package/modules/localmodels/engines-b12757-mix-ef2df21.json +3 -15
  32. package/modules/localmodels/engines-prism-b12178-03ec600.json +3 -15
  33. package/modules/localmodels/engines-speechcpp-v0.11.3.json +4 -20
  34. package/modules/localmodels/engines-strata-0.1.47.json +1 -5
  35. package/modules/localmodels/engines-strata-0.1.49.2.json +1 -5
  36. package/modules/localmodels/engines-strata-0.1.59.1.json +1 -5
  37. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +6 -30
  38. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +129 -0
  39. package/modules/localmodels/engines-whisper-b5454.json +6 -30
  40. package/modules/localmodels/engines.json +13 -61
  41. package/modules/localmodels/estimator.py +10 -5
  42. package/modules/localmodels/gpu_specs.py +1 -1
  43. package/modules/localmodels/host_sensors.py +25 -2
  44. package/modules/localmodels/hosts.py +38 -21
  45. package/modules/localmodels/kokoro-tts-0.6.1.txt +1 -1
  46. package/modules/localmodels/library_cli.py +34 -16
  47. package/modules/localmodels/library_custom.py +9 -1
  48. package/modules/localmodels/library_direct.py +41 -1
  49. package/modules/localmodels/library_elastic.py +135 -6
  50. package/modules/localmodels/library_jobs.py +23 -4
  51. package/modules/localmodels/library_kept.py +9 -1
  52. package/modules/localmodels/library_model.py +174 -2
  53. package/modules/localmodels/library_order.py +175 -69
  54. package/modules/localmodels/library_poly.py +150 -21
  55. package/modules/localmodels/library_presentation.py +485 -0
  56. package/modules/localmodels/library_pricing.py +15 -4
  57. package/modules/localmodels/library_serve.py +342 -70
  58. package/modules/localmodels/library_smoke.py +63 -5
  59. package/modules/localmodels/library_state.py +48 -10
  60. package/modules/localmodels/library_status.py +37 -17
  61. package/modules/localmodels/llm_rank.py +22 -11
  62. package/modules/localmodels/metal.py +1 -2
  63. package/modules/localmodels/plan_envelope.py +40 -13
  64. package/modules/localmodels/planning/budget.py +14 -12
  65. package/modules/localmodels/planning/memory_pools.py +7 -1
  66. package/modules/localmodels/privacy_acceptance.py +6 -5
  67. package/modules/localmodels/probe.py +34 -7
  68. package/modules/localmodels/py.typed +0 -0
  69. package/modules/localmodels/quant_formats.py +10 -3
  70. package/modules/localmodels/recommend_cli.py +1 -1
  71. package/modules/localmodels/records.py +19 -2
  72. package/modules/localmodels/remote_ops_launchd.py +8 -1
  73. package/modules/localmodels/remote_ops_verify.py +91 -24
  74. package/modules/localmodels/runtime_index.py +303 -0
  75. package/modules/localmodels/runtime_process.py +1 -1
  76. package/modules/localmodels/service_deployment.py +2 -4
  77. package/modules/localmodels/service_probe.py +59 -13
  78. package/modules/localmodels/setup_inspection.py +94 -73
  79. package/modules/localmodels/setup_text.py +7 -56
  80. package/modules/localmodels/sidecar_downloads.py +34 -0
  81. package/modules/localmodels/sidecar_http.py +61 -5
  82. package/modules/localmodels/sidecar_state.py +52 -2
  83. package/modules/localmodels/speech_admission.py +20 -4
  84. package/modules/localmodels/speech_catalog.py +23 -0
  85. package/modules/localmodels/speech_cli.py +30 -16
  86. package/modules/localmodels/speech_jobs.py +42 -17
  87. package/modules/localmodels/speech_serve.py +9 -2
  88. package/modules/localmodels/speech_server.py +185 -81
  89. package/modules/localmodels/speech_state.py +4 -1
  90. package/modules/localmodels/speech_workers.py +11 -0
  91. package/modules/localmodels/stack.py +1 -1
  92. package/modules/localmodels/stack_args.py +276 -145
  93. package/modules/localmodels/stack_auto.py +91 -6
  94. package/modules/localmodels/stack_aux_gpu.py +1 -1
  95. package/modules/localmodels/stack_cleanup.py +21 -18
  96. package/modules/localmodels/stack_cli.py +120 -115
  97. package/modules/localmodels/stack_compose.py +16 -5
  98. package/modules/localmodels/stack_debug.py +15 -6
  99. package/modules/localmodels/stack_decision.py +4 -4
  100. package/modules/localmodels/stack_doctor.py +2 -2
  101. package/modules/localmodels/stack_down.py +2 -0
  102. package/modules/localmodels/stack_events.py +1 -1
  103. package/modules/localmodels/stack_gpu_memory.py +1 -1
  104. package/modules/localmodels/stack_hardware.py +17 -15
  105. package/modules/localmodels/stack_mcp.py +1 -2
  106. package/modules/localmodels/stack_mlx.py +8 -1
  107. package/modules/localmodels/stack_picks.py +20 -21
  108. package/modules/localmodels/stack_plan.py +12 -11
  109. package/modules/localmodels/stack_ports.py +31 -4
  110. package/modules/localmodels/stack_review.py +28 -7
  111. package/modules/localmodels/stack_rollback.py +1 -1
  112. package/modules/localmodels/stack_run.py +1 -1
  113. package/modules/localmodels/stack_suite.py +72 -21
  114. package/modules/localmodels/stack_up.py +2 -0
  115. package/modules/localmodels/stack_view.py +180 -35
  116. package/modules/localmodels/stack_view_agent.py +1 -1
  117. package/modules/localmodels/stack_view_demo.py +2 -0
  118. package/modules/localmodels/stack_view_gpu.py +36 -2
  119. package/modules/localmodels/stack_view_schema.py +26 -3
  120. package/modules/localmodels/stack_view_serve.py +0 -2
  121. package/modules/localmodels/stack_view_slots.py +3 -1
  122. package/modules/localmodels/stack_view_telemetry.py +90 -4
  123. package/modules/localmodels/stack_view_tick.py +246 -40
  124. package/modules/localmodels/stack_view_words.py +9 -2
  125. package/modules/localmodels/stack_warm.py +2 -2
  126. package/modules/localmodels/stack_whatif.py +524 -41
  127. package/modules/localmodels/stack_whatif_html.py +900 -0
  128. package/modules/localmodels/startlux-decide-83fe6c7d.txt +2 -2
  129. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.7.txt → strata-poly-serve-0.2.20-poly.9.txt} +1 -1
  130. package/modules/localmodels/strata_poly_server.py +114 -3
  131. package/modules/localmodels/suite.py +265 -6
  132. package/modules/localmodels/telemetry_math.py +458 -18
  133. package/modules/localmodels/transport.py +8 -1
  134. package/modules/localmodels/tts_admission.py +2 -17
  135. package/modules/localmodels/tts_catalog.py +29 -1
  136. package/modules/localmodels/tts_cli.py +45 -22
  137. package/modules/localmodels/tts_http.py +10 -4
  138. package/modules/localmodels/tts_jobs.py +49 -19
  139. package/modules/localmodels/tts_serve.py +9 -2
  140. package/modules/localmodels/tts_server.py +1 -1
  141. package/modules/localmodels/tts_sidecar.py +69 -28
  142. package/modules/localmodels/tts_state.py +7 -2
  143. package/modules/localmodels/vision.py +5 -3
  144. package/modules/localmodels/web/view/ASSET-SOURCES.md +4 -7
  145. package/modules/localmodels/web/view/view.css +0 -1
  146. package/modules/localmodels/web/view/view.js +2 -5
  147. package/modules/localmodels/web/whatif/app.js +730 -0
  148. package/modules/localmodels/web/whatif/page.html +1172 -0
  149. package/modules/localmodels/web/whatif/sim.js +297 -0
  150. package/modules/localmodels/win_probe.py +89 -16
  151. package/modules/localmodels/windows_job.py +179 -11
  152. package/modules/simplex_localmodels-0.1.0.dev105.dist-info/METADATA +14 -0
  153. package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/RECORD +151 -145
  154. package/modules/simplex_localmodels-0.1.0.dev105.dist-info/licenses/LICENSE +201 -0
  155. package/modules/simplex_localmodels-0.1.0.dev105.dist-info/licenses/NOTICE +126 -0
  156. package/package.json +11 -2
  157. package/tool.json +1 -1
  158. package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +0 -94
  159. package/modules/localmodels/fixtures/stack-research-demo-plan.json +0 -1059
  160. package/modules/localmodels/stack_research.py +0 -716
  161. package/modules/localmodels/stack_research_demo.py +0 -125
  162. package/modules/localmodels/stack_research_plan.py +0 -146
  163. package/modules/localmodels/web/index.html +0 -2605
  164. package/modules/localmodels/web/sizecalc/app.js +0 -1306
  165. package/modules/localmodels/web/sizecalc/calc.js +0 -269
  166. package/modules/localmodels/web/sizecalc/page.html +0 -520
  167. package/modules/localmodels/web/view/logo-claude.svg +0 -3
  168. package/modules/localmodels/web/view/logo-codex.png +0 -0
  169. package/modules/simplex_localmodels-0.1.0.dev103.dist-info/METADATA +0 -9
  170. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/WHEEL +0 -0
  171. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/entry_points.txt +0 -0
  172. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,900 @@
1
+ """Self-contained interactive HTML simulator for ``localmodels stack what-if --html``.
2
+
3
+ Every model pick, context window, KV type, memory breakdown, refusal, library pick and
4
+ policy threshold in the generated page is evaluated live from the real planner
5
+ (``stack_whatif.evaluate`` and ``library_pricing.smartest``) inside an isolated temporary
6
+ environment. The browser JavaScript only looks up these pre-evaluated piecewise curves and
7
+ policy constants — zero hardcoded model rules or thresholds live in JS.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import contextlib
14
+ import json
15
+ import math
16
+ import multiprocessing
17
+ import os
18
+ import sys
19
+ import tempfile
20
+ from collections.abc import Callable, Iterator
21
+ from concurrent.futures import ProcessPoolExecutor
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from localmodels import (
26
+ __version__,
27
+ catalog,
28
+ context_policy,
29
+ library_pricing,
30
+ llm_rank,
31
+ metal,
32
+ stack_picks,
33
+ stack_plan,
34
+ stack_whatif,
35
+ suite,
36
+ vision,
37
+ )
38
+ from localmodels.planning import budget
39
+ from localmodels.planning.memcalc import parse_size
40
+ from localmodels.probe import HostFacts
41
+ from localmodels.stack_memory import Machine
42
+ from localmodels.stack_plan import StackError
43
+ from localmodels.stack_whatif import GIB, EvalResult, Simulation
44
+
45
+ SCHEMA = "localmodels.stack-whatif-html/v1"
46
+ PAGE_DIR = Path(__file__).parent / "web" / "whatif"
47
+
48
+ NVIDIA_PLATFORMS = ("win32", "linux")
49
+ VRAM_TIERS_GIB = (8, 12, 16, 24, 32, 48, 96)
50
+ RAM_TIERS_GIB = (16, 24, 32, 64, 128)
51
+ CUDA_VERSIONS = ("13.0", "12.8", "12.4")
52
+ VRAM_USED_GIB = (0, 1, 2, 3, 4)
53
+ SIM_PREFERS = ("smartest", "fastest", "concurrent")
54
+ SIM_DECISIONS = ("none", "auto")
55
+ MAC_TIERS_GIB = (8, 16, 24, 32, 48, 64, 96, 128, 256)
56
+ MAC_DIRECT_TIERS_GIB = (8, 16, 24, 256)
57
+ MAC_SPLICED_TIERS_GIB = (32, 48, 64, 96, 128)
58
+ MAC_SWEEP_PREFERS = ("smartest", "fastest")
59
+ OTHER_UNIFIED_VENDORS = ("amd", "intel", "cuda-uma")
60
+ OTHER_UNIFIED_TIERS_GIB = (16, 24, 32, 64, 128)
61
+ IDLE_NVIDIA_RAM_GIB = {8: 32, 12: 32, 16: 32, 24: 64, 32: 64, 48: 64, 96: 128}
62
+ RAM_STEP_GIB = 0.25
63
+ DECISION_AUTO_STEP_GIB = 2.0
64
+ LIB_STEP_GIB = 0.5
65
+
66
+
67
+ @contextlib.contextmanager
68
+ def _isolated_env() -> Iterator[str]:
69
+ """Run offline evaluations with empty HOME/state and no CUDA_VISIBLE_DEVICES leak."""
70
+ with tempfile.TemporaryDirectory(prefix="whatif-html-") as tmp:
71
+ saved = dict(os.environ)
72
+ os.environ["HOME"] = tmp
73
+ os.environ["USERPROFILE"] = tmp
74
+ os.environ["LOCALMODELS_STATE"] = str(Path(tmp, "state"))
75
+ os.environ.pop("CUDA_VISIBLE_DEVICES", None)
76
+ try:
77
+ yield str(Path(tmp, "base"))
78
+ finally:
79
+ os.environ.clear()
80
+ os.environ.update(saved)
81
+
82
+
83
+ class _ResultPool:
84
+ """Deduplicate identical ``EvalResult`` payloads into an integer-indexed table."""
85
+
86
+ def __init__(self) -> None:
87
+ self._index: dict[str, int] = {}
88
+ self.items: list[dict[str, Any]] = []
89
+
90
+ def add(self, res: EvalResult | dict[str, Any]) -> int:
91
+ payload = dict(res)
92
+ key = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
93
+ existing = self._index.get(key)
94
+ if existing is not None:
95
+ return existing
96
+ idx = len(self.items)
97
+ self._index[key] = idx
98
+ self.items.append(payload)
99
+ return idx
100
+
101
+
102
+ def _refusal_kind(res: EvalResult) -> str:
103
+ if res["ok"]:
104
+ return ""
105
+ msg = res["refusal"] or ""
106
+ if "not enough available RAM" in msg:
107
+ return "ram-budget"
108
+ if "memory pressure is critical" in msg:
109
+ return "pressure-critical"
110
+ if "available RAM" in msg:
111
+ return "ram-auto"
112
+ if "fits" in msg:
113
+ return "no-fit"
114
+ return res["cause_code"] or "other"
115
+
116
+
117
+ def _struct_key(res: EvalResult) -> tuple[object, ...]:
118
+ """Structural equivalence key for piecewise RAM bisection (ignores dynamic numbers in prose)."""
119
+ return (
120
+ res["ok"],
121
+ res["id"],
122
+ res["quant"],
123
+ res["engine"],
124
+ res["window"],
125
+ res["slots"],
126
+ tuple(res["kv_types"]),
127
+ res["vision"],
128
+ res["decision_id"],
129
+ res["cause_code"],
130
+ _refusal_kind(res),
131
+ )
132
+
133
+
134
+ def _bisect_curve(
135
+ upper_steps: int,
136
+ step_gib: float,
137
+ probe: Callable[[int], tuple[object, Any]],
138
+ *,
139
+ lower_steps: int = 0,
140
+ is_refusal: Callable[[Any], bool] | None = None,
141
+ hint_steps: Callable[[Any], tuple[int, ...]] | None = None,
142
+ ) -> list[list[Any]]:
143
+ """Find every transition on ``[lower_steps, upper_steps]`` assuming contiguous monotone regions.
144
+
145
+ Returns ascending ``[[min_gib, payload_at_band_top], ...]``.
146
+ """
147
+ memo: dict[int, tuple[object, Any]] = {}
148
+
149
+ def at(step: int) -> tuple[object, Any]:
150
+ found = memo.get(step)
151
+ if found is None:
152
+ found = probe(step)
153
+ memo[step] = found
154
+ return found
155
+
156
+ bands: list[list[Any]] = []
157
+ high = upper_steps
158
+ while high >= lower_steps:
159
+ hi_key, hi_val = at(high)
160
+ if high == lower_steps or (is_refusal is not None and is_refusal(hi_val)):
161
+ bands.append([round(lower_steps * step_gib, 4), hi_val])
162
+ break
163
+ lo, hi = lower_steps, high
164
+ if hint_steps is not None:
165
+ for hint in hint_steps(hi_val):
166
+ if lo < hint < hi:
167
+ if at(hint)[0] == hi_key:
168
+ hi = hint
169
+ else:
170
+ lo = hint
171
+ if lo == lower_steps and at(lower_steps)[0] == hi_key:
172
+ bands.append([round(lower_steps * step_gib, 4), at(lower_steps)[1]])
173
+ break
174
+ while hi - lo > 1:
175
+ mid = (lo + hi) // 2
176
+ if at(mid)[0] == hi_key:
177
+ hi = mid
178
+ else:
179
+ lo = mid
180
+ bands.append([round(hi * step_gib, 4), at(hi)[1]])
181
+ high = lo
182
+ bands.reverse()
183
+ return bands
184
+
185
+
186
+ def _strata_possible(platform: str, cuda: str, vram_used: int) -> bool:
187
+ """True only when Strata/PolyStrata can enter selection and read ``ram_total`` (under every
188
+ ``--prefer``: concurrent and fastest also weigh full-VRAM-resident PolyStrata recipes)."""
189
+ if cuda != "13.0":
190
+ return False
191
+ if platform == "linux" and vram_used >= 1:
192
+ return False
193
+ if platform == "win32" and vram_used > budget.DESKTOP_VRAM_BASELINE_CAP_BYTES // GIB:
194
+ return False
195
+ return True
196
+
197
+
198
+ def _ram_bucket_map() -> dict[str, dict[str, str]]:
199
+ """Group ``RAM_TIERS_GIB`` per VRAM tier by which validated Strata recipes pass ``min_ram_total_bytes``."""
200
+ validated = [r for r in suite.recipes("llm") if r.get("status") == "validated"]
201
+ mapping: dict[str, dict[str, str]] = {}
202
+ for vram in VRAM_TIERS_GIB:
203
+ by_sig: dict[tuple[str, ...], list[int]] = {}
204
+ for ram in RAM_TIERS_GIB:
205
+ eligible = tuple(
206
+ sorted(
207
+ str(r["id"])
208
+ for r in validated
209
+ if ram * GIB >= int(r.get("min_ram_total_bytes") or 0)
210
+ and vram * GIB >= int(r.get("vram_bytes") or 0)
211
+ )
212
+ )
213
+ by_sig.setdefault(eligible, []).append(ram)
214
+ per_vram: dict[str, str] = {}
215
+ for group in by_sig.values():
216
+ rep = str(max(group))
217
+ for ram in group:
218
+ per_vram[str(ram)] = rep
219
+ mapping[str(vram)] = per_vram
220
+ return mapping
221
+
222
+
223
+ def _nvidia_facts(
224
+ platform: str, vram: int, ram_total: int, ram_avail: float, cuda: str, vram_used: int
225
+ ) -> HostFacts:
226
+ return stack_whatif.simulate_facts(
227
+ Machine(vram=vram * GIB, ram=ram_total * GIB),
228
+ Simulation(
229
+ platform=platform,
230
+ cuda=cuda,
231
+ vram_used=vram_used * GIB,
232
+ ram_available=int(round(ram_avail * GIB)),
233
+ ),
234
+ )
235
+
236
+
237
+ def _eval_refused(val: dict[str, Any]) -> bool:
238
+ return not val["ok"]
239
+
240
+
241
+ def _eval_hints(step_gib: float) -> Callable[[dict[str, Any]], tuple[int, ...]]:
242
+ def hints(val: dict[str, Any]) -> tuple[int, ...]:
243
+ needed = val.get("ram_needed_bytes") or 0
244
+ if needed <= 0:
245
+ return ()
246
+ needed_gib = needed / GIB
247
+ hi = max(1, int(needed_gib / step_gib) - 1)
248
+ lo = max(1, int(max(0.0, needed_gib - 7.0) / step_gib))
249
+ return (hi, lo) if lo != hi else (hi,)
250
+
251
+ return hints
252
+
253
+
254
+ def _nvidia_curve_raw(
255
+ base_dir: str,
256
+ plat: str,
257
+ vram: int,
258
+ ram_total: int,
259
+ cuda: str,
260
+ vram_used: int,
261
+ prefer: str,
262
+ decision: str,
263
+ ) -> list[list[Any]]:
264
+ step_gib = DECISION_AUTO_STEP_GIB if decision == "auto" else RAM_STEP_GIB
265
+ upper = int(round(ram_total / step_gib))
266
+
267
+ def probe(step: int) -> tuple[object, dict[str, Any]]:
268
+ facts = _nvidia_facts(plat, vram, ram_total, step * step_gib, cuda, vram_used)
269
+ res = stack_whatif.evaluate(facts, prefer=prefer, decision=decision, base_dir=base_dir)
270
+ return _struct_key(res), dict(res)
271
+
272
+ return _bisect_curve(
273
+ upper, step_gib, probe, is_refusal=_eval_refused, hint_steps=_eval_hints(step_gib)
274
+ )
275
+
276
+
277
+ def _vram_used_groups(plat: str, vram: int, cuda: str) -> list[tuple[bool, list[int]]]:
278
+ """Partition ``VRAM_USED_GIB`` by ``_strata_possible`` so cards can share identical curves."""
279
+ valid = [vu for vu in VRAM_USED_GIB if vu < vram]
280
+ if vram < 24:
281
+ return [(_strata_possible(plat, cuda, vu), [vu]) for vu in valid]
282
+ by_strata: dict[bool, list[int]] = {}
283
+ for vu in valid:
284
+ by_strata.setdefault(_strata_possible(plat, cuda, vu), []).append(vu)
285
+ return list(by_strata.items())
286
+
287
+
288
+ def _group_by_top_eval(
289
+ base_dir: str,
290
+ plat: str,
291
+ vram: int,
292
+ ram_total: int,
293
+ cuda: str,
294
+ group: list[int],
295
+ prefer: str,
296
+ decision: str,
297
+ ) -> list[list[int]]:
298
+ """Split ``group`` into equivalence classes sharing the same top-of-RAM structural result."""
299
+ if len(group) <= 1:
300
+ return [group]
301
+ by_key: dict[tuple[object, ...], list[int]] = {}
302
+ for vu in group:
303
+ res = stack_whatif.evaluate(
304
+ _nvidia_facts(plat, vram, ram_total, ram_total, cuda, vu),
305
+ prefer=prefer,
306
+ decision=decision,
307
+ base_dir=base_dir,
308
+ )
309
+ by_key.setdefault(_struct_key(res), []).append(vu)
310
+ return list(by_key.values())
311
+
312
+
313
+ def _sweep_nvidia_eval_slice(
314
+ base_dir: str, plat: str, vram: int, cuda: str, ram_reps: list[int], decision: str
315
+ ) -> dict[str, list[list[Any]]]:
316
+ curves: dict[str, list[list[Any]]] = {}
317
+ for prefer in SIM_PREFERS:
318
+ best_res = stack_whatif.evaluate(
319
+ _nvidia_facts(plat, vram, RAM_TIERS_GIB[-1], RAM_TIERS_GIB[-1], cuda, 0),
320
+ prefer=prefer,
321
+ decision=decision,
322
+ base_dir=base_dir,
323
+ )
324
+ all_refused = not best_res["ok"]
325
+ refused_curve: list[list[Any]] = [[0.0, dict(best_res)]]
326
+ for strata, group in _vram_used_groups(plat, vram, cuda):
327
+ if not strata and cuda == "13.0":
328
+ continue
329
+ ram_list: list[int | None] = list(ram_reps) if strata else [None]
330
+ for ram_total in ram_list:
331
+ actual_ram = RAM_TIERS_GIB[-1] if ram_total is None else ram_total
332
+ ram_key = "*" if ram_total is None else str(ram_total)
333
+ if all_refused:
334
+ for out_vu in group:
335
+ curves[f"{plat}|{vram}|{ram_key}|{cuda}|{out_vu}|{prefer}|{decision}"] = (
336
+ refused_curve
337
+ )
338
+ continue
339
+ subgroups = _group_by_top_eval(
340
+ base_dir, plat, vram, actual_ram, cuda, group, prefer, decision
341
+ )
342
+ for sub in subgroups:
343
+ curve = _nvidia_curve_raw(
344
+ base_dir, plat, vram, actual_ram, cuda, sub[-1], prefer, decision
345
+ )
346
+ for out_vu in sub:
347
+ key = f"{plat}|{vram}|{ram_key}|{cuda}|{out_vu}|{prefer}|{decision}"
348
+ curves[key] = curve
349
+ return curves
350
+
351
+
352
+ def _sweep_nvidia_lib_slice(
353
+ base_dir: str, plat: str, vram: int, cuda: str, ram_reps: list[int]
354
+ ) -> dict[str, list[list[Any]]]:
355
+ lib_curves: dict[str, list[list[Any]]] = {}
356
+ lib_hint = (int(round(16.0 / LIB_STEP_GIB)), int(round(8.0 / LIB_STEP_GIB)))
357
+
358
+ def lib_hints(_val: Any) -> tuple[int, ...]:
359
+ return lib_hint
360
+
361
+ for strata, group in _vram_used_groups(plat, vram, cuda):
362
+ if not strata and cuda == "13.0":
363
+ continue
364
+ lib_rams: list[int | None] = list(ram_reps) if strata else [None]
365
+ for ram_total in lib_rams:
366
+ actual_ram = RAM_TIERS_GIB[-1] if ram_total is None else ram_total
367
+ ram_key = "*" if ram_total is None else str(ram_total)
368
+ upper = int(round(actual_ram / LIB_STEP_GIB))
369
+ by_top: dict[tuple[str, str] | None, list[int]] = {}
370
+ for vu in group:
371
+ top_pick = library_pricing.smartest(
372
+ _nvidia_facts(plat, vram, actual_ram, actual_ram, cuda, vu),
373
+ base_dir=base_dir,
374
+ )
375
+ by_top.setdefault(top_pick, []).append(vu)
376
+ for sub in by_top.values():
377
+ rep_vu = sub[-1]
378
+
379
+ def probe_lib(
380
+ step: int, _r: int = actual_ram, _u: int = rep_vu
381
+ ) -> tuple[object, list[str] | None]:
382
+ facts = _nvidia_facts(plat, vram, _r, step * LIB_STEP_GIB, cuda, _u)
383
+ pick = library_pricing.smartest(facts, base_dir=base_dir)
384
+ return pick, list(pick) if pick is not None else None
385
+
386
+ curve = _bisect_curve(
387
+ upper,
388
+ LIB_STEP_GIB,
389
+ probe_lib,
390
+ is_refusal=lambda pick: pick is None,
391
+ hint_steps=lib_hints,
392
+ )
393
+ for out_vu in sub:
394
+ lib_curves[f"{plat}|{vram}|{ram_key}|{cuda}|{out_vu}"] = curve
395
+ return lib_curves
396
+
397
+
398
+ def _worker_nvidia_slice(
399
+ task: tuple[str, int, str, list[int], str],
400
+ ) -> tuple[dict[str, list[list[Any]]], dict[str, list[list[Any]]]]:
401
+ """Worker: compute NVIDIA planner (and library for decision=none) curves for one slice."""
402
+ plat, vram, cuda, ram_reps, decision = task
403
+ with _isolated_env() as base_dir:
404
+ curves = _sweep_nvidia_eval_slice(base_dir, plat, vram, cuda, ram_reps, decision)
405
+ lib = (
406
+ _sweep_nvidia_lib_slice(base_dir, plat, vram, cuda, ram_reps)
407
+ if decision == "none"
408
+ else {}
409
+ )
410
+ return curves, lib
411
+
412
+
413
+ def _mac_tier_info(total: int) -> dict[str, float]:
414
+ ws = metal.default_working_set(total * GIB) / GIB
415
+ reserve = metal.in_use(total * GIB) / GIB
416
+ return {
417
+ "working_set_gib": round(ws, 2),
418
+ "reserve_gib": round(reserve, 2),
419
+ "ceiling_gib": round(total - reserve, 2),
420
+ }
421
+
422
+
423
+ def _scan_curve(
424
+ points_gib: list[float],
425
+ probe: Callable[[float], tuple[object, Any]],
426
+ ) -> list[list[Any]]:
427
+ """Evaluate every point in ascending ``points_gib`` and merge consecutive equal keys.
428
+
429
+ Used for Mac ``decision="auto"`` where higher unified memory can let the LLM step up in
430
+ KV precision or context and temporarily leave too little headroom for a decision model
431
+ (non-monotonic in available memory).
432
+ """
433
+ bands: list[list[Any]] = []
434
+ last_key: object = object()
435
+ for gib_val in points_gib:
436
+ key, val = probe(gib_val)
437
+ if bands and key == last_key:
438
+ continue
439
+ bands.append([round(gib_val, 4), val])
440
+ last_key = key
441
+ return bands
442
+
443
+
444
+ def _mac_auto_points(low_gib: float, high_gib: float) -> list[float]:
445
+ """Grid points for Mac ``decision="auto"``: 0.5 GiB up to 32 GiB, 1.0 GiB to 64, 2.0 above."""
446
+ pts: list[float] = []
447
+ cur = low_gib
448
+ while cur < high_gib - 1e-6:
449
+ pts.append(round(cur, 4))
450
+ step = 0.5 if cur < 32.0 else (1.0 if cur < 64.0 else 2.0)
451
+ cur += step
452
+ pts.append(round(high_gib, 4))
453
+ return pts
454
+
455
+
456
+ def _worker_mac_direct(
457
+ total: int,
458
+ ) -> tuple[int, dict[str, list[list[Any]]], list[list[Any]]]:
459
+ """Worker: compute full planner + library curves for a direct Mac tier (8, 16, 24, 256)."""
460
+ curves: dict[str, list[list[Any]]] = {}
461
+ with _isolated_env() as base_dir:
462
+ for prefer in MAC_SWEEP_PREFERS:
463
+ for decision in SIM_DECISIONS:
464
+ if decision == "auto":
465
+
466
+ def probe_gib(
467
+ gib_val: float, _p: str = prefer, _d: str = decision
468
+ ) -> tuple[object, dict[str, Any]]:
469
+ facts = stack_whatif.simulate_facts(
470
+ Machine(unified=total * GIB),
471
+ Simulation(ram_available=int(round(gib_val * GIB))),
472
+ )
473
+ res = stack_whatif.evaluate(
474
+ facts, prefer=_p, decision=_d, base_dir=base_dir
475
+ )
476
+ return _struct_key(res), dict(res)
477
+
478
+ curves[f"{total}|{prefer}|{decision}"] = _scan_curve(
479
+ _mac_auto_points(0.0, float(total)), probe_gib
480
+ )
481
+ continue
482
+ upper = int(round(total / RAM_STEP_GIB))
483
+
484
+ def probe(
485
+ step: int, _p: str = prefer, _d: str = decision
486
+ ) -> tuple[object, dict[str, Any]]:
487
+ facts = stack_whatif.simulate_facts(
488
+ Machine(unified=total * GIB),
489
+ Simulation(ram_available=int(round(step * RAM_STEP_GIB * GIB))),
490
+ )
491
+ res = stack_whatif.evaluate(facts, prefer=_p, decision=_d, base_dir=base_dir)
492
+ return _struct_key(res), dict(res)
493
+
494
+ curves[f"{total}|{prefer}|{decision}"] = _bisect_curve(
495
+ upper, RAM_STEP_GIB, probe, is_refusal=_eval_refused
496
+ )
497
+ lib_upper = int(round(total / LIB_STEP_GIB))
498
+
499
+ def probe_lib(step: int) -> tuple[object, list[str] | None]:
500
+ facts = stack_whatif.simulate_facts(
501
+ Machine(unified=total * GIB),
502
+ Simulation(ram_available=int(round(step * LIB_STEP_GIB * GIB))),
503
+ )
504
+ pick = library_pricing.smartest(facts, base_dir=base_dir)
505
+ return pick, list(pick) if pick is not None else None
506
+
507
+ lib_curve = _bisect_curve(
508
+ lib_upper, LIB_STEP_GIB, probe_lib, is_refusal=lambda pick: pick is None
509
+ )
510
+ return total, curves, lib_curve
511
+
512
+
513
+ def _splice_mac_curve(
514
+ master: list[list[Any]], tail: list[list[Any]], cut_gib: float
515
+ ) -> list[list[Any]]:
516
+ """Keep the exact 256 GiB Mac prefix strictly below ``cut_gib`` and append the tier's tail."""
517
+ prefix = [band for band in master if float(band[0]) < cut_gib]
518
+ merged = list(prefix)
519
+ for edge, val in tail:
520
+ if merged and _struct_key(merged[-1][1]) == _struct_key(val):
521
+ continue
522
+ merged.append([edge, val])
523
+ return merged
524
+
525
+
526
+ def _worker_mac_tail(
527
+ task: tuple[int, dict[str, list[list[Any]]], list[list[Any]]],
528
+ ) -> tuple[int, dict[str, list[list[Any]]], list[list[Any]]]:
529
+ """Worker: splice the 256 GiB prefix below ``working_set + 2`` and scan/bisect the top tail."""
530
+ total, master_curves, master_lib = task
531
+ ws_cap_gib = metal.default_working_set(total * GIB) / GIB + metal.HOST_KEEP_BYTES / GIB
532
+ curves: dict[str, list[list[Any]]] = {}
533
+ with _isolated_env() as base_dir:
534
+ for prefer in MAC_SWEEP_PREFERS:
535
+ for decision in SIM_DECISIONS:
536
+ if decision == "auto":
537
+ cut_gib = float(max(0, int(math.floor(ws_cap_gib))))
538
+
539
+ def probe_gib(
540
+ gib_val: float, _p: str = prefer, _d: str = decision
541
+ ) -> tuple[object, dict[str, Any]]:
542
+ facts = stack_whatif.simulate_facts(
543
+ Machine(unified=total * GIB),
544
+ Simulation(ram_available=int(round(gib_val * GIB))),
545
+ )
546
+ res = stack_whatif.evaluate(
547
+ facts, prefer=_p, decision=_d, base_dir=base_dir
548
+ )
549
+ return _struct_key(res), dict(res)
550
+
551
+ tail = _scan_curve(_mac_auto_points(cut_gib, float(total)), probe_gib)
552
+ curves[f"{total}|{prefer}|{decision}"] = _splice_mac_curve(
553
+ master_curves[f"256|{prefer}|{decision}"], tail, cut_gib
554
+ )
555
+ continue
556
+ cut_step = max(0, int(math.floor(ws_cap_gib / RAM_STEP_GIB)))
557
+ cut_gib = round(cut_step * RAM_STEP_GIB, 4)
558
+ upper = int(round(total / RAM_STEP_GIB))
559
+
560
+ def probe(
561
+ step: int, _p: str = prefer, _d: str = decision
562
+ ) -> tuple[object, dict[str, Any]]:
563
+ facts = stack_whatif.simulate_facts(
564
+ Machine(unified=total * GIB),
565
+ Simulation(ram_available=int(round(step * RAM_STEP_GIB * GIB))),
566
+ )
567
+ res = stack_whatif.evaluate(facts, prefer=_p, decision=_d, base_dir=base_dir)
568
+ return _struct_key(res), dict(res)
569
+
570
+ tail = _bisect_curve(
571
+ upper, RAM_STEP_GIB, probe, lower_steps=cut_step, is_refusal=_eval_refused
572
+ )
573
+ curves[f"{total}|{prefer}|{decision}"] = _splice_mac_curve(
574
+ master_curves[f"256|{prefer}|{decision}"], tail, cut_gib
575
+ )
576
+
577
+ lib_cut_step = max(0, int(math.floor(ws_cap_gib / LIB_STEP_GIB)))
578
+ lib_cut_gib = round(lib_cut_step * LIB_STEP_GIB, 4)
579
+ lib_upper = int(round(total / LIB_STEP_GIB))
580
+
581
+ def probe_lib(step: int) -> tuple[object, list[str] | None]:
582
+ facts = stack_whatif.simulate_facts(
583
+ Machine(unified=total * GIB),
584
+ Simulation(ram_available=int(round(step * LIB_STEP_GIB * GIB))),
585
+ )
586
+ pick = library_pricing.smartest(facts, base_dir=base_dir)
587
+ return pick, list(pick) if pick is not None else None
588
+
589
+ lib_tail = _bisect_curve(
590
+ lib_upper,
591
+ LIB_STEP_GIB,
592
+ probe_lib,
593
+ lower_steps=lib_cut_step,
594
+ is_refusal=lambda pick: pick is None,
595
+ )
596
+ lib_prefix = [band for band in master_lib if float(band[0]) < lib_cut_gib]
597
+ lib_merged = list(lib_prefix)
598
+ for edge, pick in lib_tail:
599
+ if lib_merged and lib_merged[-1][1] == pick:
600
+ continue
601
+ lib_merged.append([edge, pick])
602
+ return total, curves, lib_merged
603
+
604
+
605
+ def _intern_curves(
606
+ pool: _ResultPool, raw_curves: dict[str, list[list[Any]]]
607
+ ) -> dict[str, list[list[Any]]]:
608
+ return {
609
+ key: [[edge, pool.add(payload)] for edge, payload in bands]
610
+ for key, bands in raw_curves.items()
611
+ }
612
+
613
+
614
+ def _sweep_other_unified(pool: _ResultPool, base_dir: str) -> dict[str, dict[str, Any]]:
615
+ out: dict[str, dict[str, Any]] = {}
616
+ for vendor in OTHER_UNIFIED_VENDORS:
617
+ for total in OTHER_UNIFIED_TIERS_GIB:
618
+ facts = stack_whatif.simulate_facts(
619
+ Machine(unified=total * GIB),
620
+ Simulation(gpu_vendor=vendor, platform="linux"),
621
+ )
622
+ lib = library_pricing.smartest(facts, base_dir=base_dir)
623
+ lib_val = list(lib) if lib is not None else None
624
+ for prefer in SIM_PREFERS:
625
+ res = stack_whatif.evaluate(facts, prefer=prefer, base_dir=base_dir)
626
+ out[f"{vendor}|{total}|{prefer}"] = {
627
+ "result": pool.add(res),
628
+ "library": lib_val,
629
+ }
630
+ return out
631
+
632
+
633
+ def _policy_constants() -> dict[str, Any]:
634
+ return {
635
+ "tie_band": llm_rank.TIE_BAND,
636
+ "coin_flip": llm_rank.COIN_FLIP,
637
+ "fast_quality_band": llm_rank.FAST_QUALITY_BAND,
638
+ "worth_faster": stack_picks.WORTH_FASTER,
639
+ "usable_floor_tok_s": catalog.USABLE_FLOOR_TOK_S,
640
+ "pleasant_floor_tok_s": catalog.PLEASANT_FLOOR_TOK_S,
641
+ "mac_yield_score": llm_rank.MAC_DEFAULT_YIELD_SCORE,
642
+ "mac_ladder": list(llm_rank.MAC_LADDER),
643
+ "mac_ladder_fastest": list(llm_rank.MAC_LADDER_FASTEST),
644
+ "mac_ladder_min_gib": llm_rank.MAC_LADDER_MIN_BYTES // GIB,
645
+ "windows_fallback_id": llm_rank.WINDOWS_FALLBACK_ID,
646
+ "wddm_baseline_cap_gib": budget.DESKTOP_VRAM_BASELINE_CAP_BYTES // GIB,
647
+ "idle_used_gib": budget.IDLE_USED_BYTES // GIB,
648
+ "vision_gpu_min_gib": round(vision.GPU_MIN_TOTAL_BYTES / GIB, 1),
649
+ "warn_keep_fraction": metal.WARN_KEEP_FRACTION,
650
+ "ram_floor_gib": budget.RAM_FLOOR // GIB,
651
+ "metal_ram_floor_gib": stack_plan.METAL_RAM_FLOOR // GIB,
652
+ "harness_ram_gib": budget.HARNESS_RAM // GIB,
653
+ "agent_floor": context_policy.AGENT.floor,
654
+ "agent_preferred": context_policy.AGENT.preferred,
655
+ "agent_target": context_policy.AGENT.target,
656
+ "agent_slots": context_policy.AGENT.slots,
657
+ "reasoning_budget": stack_plan.REASONING_BUDGET,
658
+ }
659
+
660
+
661
+ def _idle_matrix(pool: _ResultPool, base_dir: str) -> list[dict[str, Any]]:
662
+ rows: list[dict[str, Any]] = []
663
+ for plat in NVIDIA_PLATFORMS:
664
+ for vram, ram in IDLE_NVIDIA_RAM_GIB.items():
665
+ facts = _nvidia_facts(plat, vram, ram, ram - 4, "13.0", 0)
666
+ smart = pool.add(stack_whatif.evaluate(facts, prefer="smartest", base_dir=base_dir))
667
+ fast = pool.add(stack_whatif.evaluate(facts, prefer="fastest", base_dir=base_dir))
668
+ rows.append(
669
+ {
670
+ "group": plat,
671
+ "label": f"{'Windows' if plat == 'win32' else 'Linux'} {vram} GB + {ram} GB RAM",
672
+ "vram": vram,
673
+ "ram": ram,
674
+ "smartest": smart,
675
+ "fastest": fast,
676
+ }
677
+ )
678
+ for total in MAC_TIERS_GIB:
679
+ facts = stack_whatif.simulate_facts(Machine(unified=total * GIB))
680
+ smart = pool.add(stack_whatif.evaluate(facts, prefer="smartest", base_dir=base_dir))
681
+ fast = pool.add(stack_whatif.evaluate(facts, prefer="fastest", base_dir=base_dir))
682
+ rows.append(
683
+ {
684
+ "group": "darwin",
685
+ "label": f"Mac {total} GB unified",
686
+ "unified": total,
687
+ "smartest": smart,
688
+ "fastest": fast,
689
+ }
690
+ )
691
+ return rows
692
+
693
+
694
+ def _default_initial() -> dict[str, Any]:
695
+ return {
696
+ "mode": "nvidia",
697
+ "platform": "win32",
698
+ "vram": 8,
699
+ "ram": 32,
700
+ "ram_avail": 28.0,
701
+ "cuda": "13.0",
702
+ "vram_used": 0,
703
+ "mac_total": 24,
704
+ "mac_avail": 21.0,
705
+ "pressure": 1,
706
+ "other_vendor": "cuda-uma",
707
+ "other_total": 64,
708
+ "prefer": "smartest",
709
+ "decision": "none",
710
+ }
711
+
712
+
713
+ def _nearest(value: int, choices: tuple[int, ...]) -> int:
714
+ return min(choices, key=lambda c: (abs(c - value), c))
715
+
716
+
717
+ def initial_from_args(args: argparse.Namespace) -> dict[str, Any]:
718
+ """Map CLI flags passed alongside ``--html`` into the page's initial simulator state."""
719
+ state = _default_initial()
720
+ raw_platform = getattr(args, "platform", None)
721
+ platform = stack_whatif.normalize_platform(raw_platform) if raw_platform else None
722
+ vram_b = parse_size(args.vram) if getattr(args, "vram", None) else None
723
+ ram_b = parse_size(args.ram) if getattr(args, "ram", None) else None
724
+ unified_b = parse_size(args.unified_memory) if getattr(args, "unified_memory", None) else None
725
+ vram_used_b = parse_size(args.vram_used) if getattr(args, "vram_used", None) else None
726
+ ram_avail_b = parse_size(args.ram_available) if getattr(args, "ram_available", None) else None
727
+ pressure = getattr(args, "pressure", None)
728
+ cuda = getattr(args, "cuda", None)
729
+ prefer = getattr(args, "prefer", None)
730
+ decision = getattr(args, "decision", None)
731
+
732
+ if prefer in SIM_PREFERS:
733
+ state["prefer"] = prefer
734
+ if decision in SIM_DECISIONS:
735
+ state["decision"] = decision
736
+ if unified_b is not None or platform == "darwin":
737
+ state["mode"] = "mac"
738
+ total = _nearest(max(8, round(unified_b / GIB)), MAC_TIERS_GIB) if unified_b else 24
739
+ state["mac_total"] = total
740
+ default_avail = round(total - metal.in_use(total * GIB) / GIB, 2)
741
+ state["mac_avail"] = (
742
+ min(float(total), round(ram_avail_b / GIB, 2))
743
+ if ram_avail_b is not None
744
+ else default_avail
745
+ )
746
+ if pressure in stack_whatif.PRESSURE_LEVELS:
747
+ state["pressure"] = pressure
748
+ return state
749
+ if platform in NVIDIA_PLATFORMS:
750
+ state["platform"] = platform
751
+ if vram_b is not None:
752
+ state["vram"] = _nearest(round(vram_b / GIB), VRAM_TIERS_GIB)
753
+ if ram_b is not None:
754
+ state["ram"] = _nearest(round(ram_b / GIB), RAM_TIERS_GIB)
755
+ state["ram_avail"] = max(0.0, float(state["ram"] - 4))
756
+ if ram_avail_b is not None:
757
+ state["ram_avail"] = min(float(state["ram"]), round(ram_avail_b / GIB, 2))
758
+ if cuda in CUDA_VERSIONS:
759
+ state["cuda"] = cuda
760
+ if vram_used_b is not None:
761
+ state["vram_used"] = _nearest(round(vram_used_b / GIB), VRAM_USED_GIB)
762
+ return state
763
+
764
+
765
+ def _default_workers() -> int:
766
+ main_mod = sys.modules.get("__main__")
767
+ if getattr(main_mod, "__file__", None) == "<stdin>":
768
+ return 1
769
+ cpus = os.cpu_count() or 1
770
+ cap = (8 if cpus >= 32 else 4) if os.environ.get("PYTEST_XDIST_WORKER") else 10
771
+ return min(cap, cpus)
772
+
773
+
774
+ def page_data(
775
+ *, initial: dict[str, Any] | None = None, workers: int | None = None
776
+ ) -> dict[str, Any]:
777
+ """Compute the complete zero-drift JSON data payload from the real planner."""
778
+ pool = _ResultPool()
779
+ ram_buckets = _ram_bucket_map()
780
+ # Schedule heavier linux/auto slices first so tail latency stays short across worker cores.
781
+ nv_tasks = [
782
+ (plat, vram, cuda, sorted({int(rep) for rep in ram_buckets[str(vram)].values()}), dec)
783
+ for dec in ("auto", "none")
784
+ for plat in ("linux", "win32")
785
+ for vram in reversed(VRAM_TIERS_GIB)
786
+ for cuda in CUDA_VERSIONS
787
+ ]
788
+ n_workers = workers if workers is not None else _default_workers()
789
+ if n_workers > 1:
790
+ mp_ctx = multiprocessing.get_context("spawn")
791
+ with ProcessPoolExecutor(max_workers=n_workers, mp_context=mp_ctx) as ex:
792
+ mac_direct_futs = [ex.submit(_worker_mac_direct, t) for t in MAC_DIRECT_TIERS_GIB]
793
+ nv_futs = [ex.submit(_worker_nvidia_slice, t) for t in nv_tasks]
794
+ mac_direct_out = [f.result() for f in mac_direct_futs]
795
+ master_256 = next(item for item in mac_direct_out if item[0] == 256)
796
+ mac_tail_futs = [
797
+ ex.submit(_worker_mac_tail, (t, master_256[1], master_256[2]))
798
+ for t in MAC_SPLICED_TIERS_GIB
799
+ ]
800
+ nv_out = [f.result() for f in nv_futs]
801
+ mac_tail_out = [f.result() for f in mac_tail_futs]
802
+ else:
803
+ mac_direct_out = [_worker_mac_direct(t) for t in MAC_DIRECT_TIERS_GIB]
804
+ master_256 = next(item for item in mac_direct_out if item[0] == 256)
805
+ mac_tail_out = [
806
+ _worker_mac_tail((t, master_256[1], master_256[2])) for t in MAC_SPLICED_TIERS_GIB
807
+ ]
808
+ nv_out = [_worker_nvidia_slice(t) for t in nv_tasks]
809
+
810
+ nvidia_curves: dict[str, list[list[Any]]] = {}
811
+ lib_nvidia: dict[str, list[list[Any]]] = {}
812
+ for curves_part, lib_part in nv_out:
813
+ nvidia_curves.update(_intern_curves(pool, curves_part))
814
+ lib_nvidia.update(lib_part)
815
+
816
+ mac_tiers = {str(t): _mac_tier_info(t) for t in MAC_TIERS_GIB}
817
+ mac_curves: dict[str, list[list[Any]]] = {}
818
+ lib_mac: dict[str, list[list[Any]]] = {}
819
+ for total, curves_part, lib_curve in (*mac_direct_out, *mac_tail_out):
820
+ mac_curves.update(_intern_curves(pool, curves_part))
821
+ lib_mac[str(total)] = lib_curve
822
+
823
+ with _isolated_env() as base_dir:
824
+ crit_facts = stack_whatif.simulate_facts(
825
+ Machine(unified=24 * GIB), Simulation(pressure=metal.PRESSURE_CRITICAL)
826
+ )
827
+ crit_id = pool.add(stack_whatif.evaluate(crit_facts, base_dir=base_dir))
828
+ other = _sweep_other_unified(pool, base_dir)
829
+ idle = _idle_matrix(pool, base_dir)
830
+
831
+ return {
832
+ "schema": SCHEMA,
833
+ "version": __version__,
834
+ "results": pool.items,
835
+ "policy": _policy_constants(),
836
+ "dimensions": {
837
+ "nvidia_platforms": list(NVIDIA_PLATFORMS),
838
+ "vram_tiers_gib": list(VRAM_TIERS_GIB),
839
+ "ram_tiers_gib": list(RAM_TIERS_GIB),
840
+ "cuda_versions": list(CUDA_VERSIONS),
841
+ "vram_used_gib": list(VRAM_USED_GIB),
842
+ "prefers": list(SIM_PREFERS),
843
+ "decisions": list(SIM_DECISIONS),
844
+ "mac_tiers_gib": list(MAC_TIERS_GIB),
845
+ "other_unified_vendors": list(OTHER_UNIFIED_VENDORS),
846
+ "other_unified_tiers_gib": list(OTHER_UNIFIED_TIERS_GIB),
847
+ },
848
+ "nvidia_ram_buckets": ram_buckets,
849
+ "nvidia": nvidia_curves,
850
+ "mac": {"tiers": mac_tiers, "critical_result": crit_id, "curves": mac_curves},
851
+ "other_unified": other,
852
+ "library": {"nvidia": lib_nvidia, "mac": lib_mac},
853
+ "idle_matrix": idle,
854
+ "initial": {**_default_initial(), **(initial or {})},
855
+ }
856
+
857
+
858
+ def build_page(*, initial: dict[str, Any] | None = None, workers: int | None = None) -> str:
859
+ """Render the self-contained interactive HTML page with planner data and JS inlined."""
860
+ page = (PAGE_DIR / "page.html").read_text(encoding="utf-8")
861
+ data = json.dumps(
862
+ page_data(initial=initial, workers=workers), ensure_ascii=False, separators=(",", ":")
863
+ )
864
+ for marker, text in (
865
+ ("/*@DATA@*/", f"const WHATIF_DATA = {data};"),
866
+ ("/*@SIM@*/", (PAGE_DIR / "sim.js").read_text(encoding="utf-8")),
867
+ ("/*@APP@*/", (PAGE_DIR / "app.js").read_text(encoding="utf-8")),
868
+ ):
869
+ page = page.replace(marker, text)
870
+ return page
871
+
872
+
873
+ def cli_html(args: argparse.Namespace) -> int:
874
+ """Handle ``localmodels stack what-if --html PATH``."""
875
+ try:
876
+ machine = Machine(
877
+ vram=parse_size(args.vram) if args.vram else None,
878
+ ram=parse_size(args.ram) if args.ram else None,
879
+ unified=parse_size(args.unified_memory) if args.unified_memory else None,
880
+ )
881
+ sim = stack_whatif.simulation_from_args(args)
882
+ if any(v is not None for v in (machine.vram, machine.ram, machine.unified)) or sim:
883
+ if machine.unified is not None or (
884
+ machine.vram is not None and machine.ram is not None
885
+ ):
886
+ stack_whatif.simulate_facts(machine, sim)
887
+ initial = initial_from_args(args)
888
+ html = build_page(initial=initial)
889
+ raw_out = str(args.html)
890
+ if raw_out == "-":
891
+ sys.stdout.write(html)
892
+ return 0
893
+ path = Path(raw_out).expanduser()
894
+ path.parent.mkdir(parents=True, exist_ok=True)
895
+ path.write_text(html, encoding="utf-8")
896
+ except (OSError, ValueError, StackError) as exc:
897
+ print(f"stack what-if: {exc}", file=sys.stderr)
898
+ return 2
899
+ print(f"wrote {path}")
900
+ return 0