@simplexai/localmodels-darwin-arm64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.36

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 (143) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +141 -99
  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 +7 -1
  11. package/modules/localmodels/catalog.json +286 -12
  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-strata-0.1.59.1.json +31 -0
  22. package/modules/localmodels/engines.json +57 -1
  23. package/modules/localmodels/engines.py +6 -2
  24. package/modules/localmodels/estimator.py +21 -7
  25. package/modules/localmodels/frontend.py +4 -4
  26. package/modules/localmodels/gateway.py +14 -4
  27. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  28. package/modules/localmodels/gateway_bifrost.py +70 -57
  29. package/modules/localmodels/gateway_probe.py +3 -4
  30. package/modules/localmodels/gguf.py +7 -0
  31. package/modules/localmodels/harness.py +24 -25
  32. package/modules/localmodels/harness_gateway.py +19 -10
  33. package/modules/localmodels/harness_probe.py +33 -6
  34. package/modules/localmodels/hosts.py +73 -9
  35. package/modules/localmodels/install.py +36 -6
  36. package/modules/localmodels/library_cli.py +179 -0
  37. package/modules/localmodels/library_convert.py +132 -0
  38. package/modules/localmodels/library_gateway.py +471 -0
  39. package/modules/localmodels/library_jobs.py +314 -0
  40. package/modules/localmodels/library_model.py +246 -0
  41. package/modules/localmodels/library_pricing.py +347 -0
  42. package/modules/localmodels/library_serve.py +348 -0
  43. package/modules/localmodels/library_state.py +373 -0
  44. package/modules/localmodels/library_status.py +349 -0
  45. package/modules/localmodels/llm_rank.py +77 -8
  46. package/modules/localmodels/memcalc.py +7 -30
  47. package/modules/localmodels/metal.py +26 -0
  48. package/modules/localmodels/metal_probe.py +11 -7
  49. package/modules/localmodels/plan_envelope.py +4 -1
  50. package/modules/localmodels/preparation.py +49 -0
  51. package/modules/localmodels/probe.py +8 -8
  52. package/modules/localmodels/process_identity.py +536 -9
  53. package/modules/localmodels/quant_formats.py +123 -0
  54. package/modules/localmodels/recommend.py +32 -3
  55. package/modules/localmodels/recommend_cli.py +8 -4
  56. package/modules/localmodels/records.py +1 -0
  57. package/modules/localmodels/remote_ops.py +104 -6
  58. package/modules/localmodels/remote_ops_download.py +17 -2
  59. package/modules/localmodels/remote_ops_prepare.py +425 -0
  60. package/modules/localmodels/remote_ops_remove.py +40 -7
  61. package/modules/localmodels/remote_ops_service.py +110 -8
  62. package/modules/localmodels/remote_ops_verify.py +15 -2
  63. package/modules/localmodels/runtime_auth.py +31 -1
  64. package/modules/localmodels/runtime_cli.py +3 -4
  65. package/modules/localmodels/runtime_io.py +50 -6
  66. package/modules/localmodels/service_autostart.py +45 -1
  67. package/modules/localmodels/service_control.py +13 -0
  68. package/modules/localmodels/service_deployment.py +12 -3
  69. package/modules/localmodels/service_jobs.py +33 -4
  70. package/modules/localmodels/service_probe.py +67 -13
  71. package/modules/localmodels/service_stop.py +152 -0
  72. package/modules/localmodels/service_worker.py +9 -1
  73. package/modules/localmodels/services_cli.py +50 -6
  74. package/modules/localmodels/setup_inspection.py +34 -25
  75. package/modules/localmodels/setup_text.py +118 -0
  76. package/modules/localmodels/sizecalc.py +625 -0
  77. package/modules/localmodels/sizecalc_cli.py +249 -0
  78. package/modules/localmodels/stack.py +69 -17
  79. package/modules/localmodels/stack_args.py +91 -19
  80. package/modules/localmodels/stack_auto.py +78 -0
  81. package/modules/localmodels/stack_binding.py +23 -35
  82. package/modules/localmodels/stack_card.py +195 -0
  83. package/modules/localmodels/stack_cleanup.py +379 -0
  84. package/modules/localmodels/stack_clients.py +4 -1
  85. package/modules/localmodels/stack_compose.py +173 -206
  86. package/modules/localmodels/stack_console.py +2 -0
  87. package/modules/localmodels/stack_decision.py +3 -2
  88. package/modules/localmodels/stack_down.py +189 -0
  89. package/modules/localmodels/stack_events.py +54 -0
  90. package/modules/localmodels/stack_hardware.py +30 -34
  91. package/modules/localmodels/stack_journal.py +29 -8
  92. package/modules/localmodels/stack_ledger.py +411 -0
  93. package/modules/localmodels/stack_lifecycle.py +162 -167
  94. package/modules/localmodels/stack_llm_ram.py +57 -5
  95. package/modules/localmodels/stack_memory.py +721 -0
  96. package/modules/localmodels/stack_picks.py +147 -0
  97. package/modules/localmodels/stack_plan.py +143 -25
  98. package/modules/localmodels/stack_ports.py +22 -0
  99. package/modules/localmodels/stack_preflight.py +699 -0
  100. package/modules/localmodels/stack_review.py +123 -5
  101. package/modules/localmodels/stack_rollback.py +2 -0
  102. package/modules/localmodels/stack_route.py +256 -0
  103. package/modules/localmodels/stack_run.py +11 -0
  104. package/modules/localmodels/stack_suite.py +107 -20
  105. package/modules/localmodels/stack_summary.py +65 -4
  106. package/modules/localmodels/stack_try.py +354 -0
  107. package/modules/localmodels/stack_try_client.py +194 -0
  108. package/modules/localmodels/stack_try_docs.py +139 -0
  109. package/modules/localmodels/stack_up.py +8 -1
  110. package/modules/localmodels/stack_update.py +29 -4
  111. package/modules/localmodels/stack_verify.py +3 -1
  112. package/modules/localmodels/stack_view.py +10 -11
  113. package/modules/localmodels/stack_view_apply.py +4 -2
  114. package/modules/localmodels/stack_view_events.py +2 -1
  115. package/modules/localmodels/stack_view_serve.py +3 -0
  116. package/modules/localmodels/stack_view_text.py +1 -1
  117. package/modules/localmodels/stack_view_words.py +4 -1
  118. package/modules/localmodels/stack_warm.py +574 -0
  119. package/modules/localmodels/stack_whatif.py +558 -0
  120. package/modules/localmodels/suite.py +48 -39
  121. package/modules/localmodels/tool_archive.py +40 -0
  122. package/modules/localmodels/tools.json +8 -0
  123. package/modules/localmodels/transport.py +1 -0
  124. package/modules/localmodels/vision.py +8 -1
  125. package/modules/localmodels/web/sizecalc/app.js +431 -0
  126. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  127. package/modules/localmodels/web/sizecalc/page.html +362 -0
  128. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  129. package/modules/localmodels/web/view/i18n.js +1 -1
  130. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  131. package/modules/localmodels/web/view/logo-codex.png +0 -0
  132. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  133. package/modules/localmodels/web/view/view.css +4 -0
  134. package/modules/localmodels/web/view/view.js +15 -6
  135. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/METADATA +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev36.dist-info/RECORD +242 -0
  137. package/package.json +1 -1
  138. package/tool.json +1 -1
  139. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/WHEEL +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/entry_points.txt +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/NOTICE +0 -0
  143. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,249 @@
1
+ """The ``sizecalc`` command line: options, help, the text report and the HTML page."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections.abc import Mapping
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from localmodels import catalog, cli_help, sizecalc
13
+ from localmodels.memcalc import GIB, KIB, MemcalcError, parse_params, parse_size, parse_tokens
14
+
15
+ PAGE_DIR = Path(__file__).parent / "web" / "sizecalc"
16
+ _VERDICT = {"fits": "fits", "offload": "fits with system RAM", "no": "-"}
17
+
18
+
19
+ def _verdict(row: Mapping[str, Any]) -> str:
20
+ convert = row.get("format_support") == "convert" and row["verdict"] != "no"
21
+ return _VERDICT[row["verdict"]] + (" (convert)" if convert else "")
22
+
23
+
24
+ def _gib(n: float) -> str:
25
+ return f"{n / GIB:.1f}"
26
+
27
+
28
+ def _speed(row: Mapping[str, Any]) -> str:
29
+ tok = row["decode_ceiling_tok_s"]
30
+ return f"{tok:,.0f}" if tok >= 10 else f"{tok:.1f}" if tok else ""
31
+
32
+
33
+ def render(data: Mapping[str, Any]) -> str:
34
+ model, fmt, posture = data["model"], data["format"], data["posture"]
35
+ params = model["params"] / 1e9
36
+ kind = (
37
+ f"MoE, {params:.1f}B total / {model['active_params'] / 1e9:.1f}B active"
38
+ if model["kind"] == "moe"
39
+ else f"dense, {params:.1f}B parameters"
40
+ )
41
+ run = data["runtime"]
42
+ slots = posture["slots"]
43
+ lines = [
44
+ f"{kind} · {fmt['name']} ({fmt['family']}, {fmt['bits_per_weight']} bits/weight)",
45
+ f"weight file {data['file_bytes'] / 1e9:.2f} GB ({_gib(data['file_bytes'])} GiB)",
46
+ f"KV {data['kv_bytes_per_token'] / KIB:.0f} KiB/token at f16 ({data['kv_source']})"
47
+ f" · context {posture['context']:,} x {slots} slot{'s' if slots > 1 else ''},"
48
+ f" KV {posture['kv_type']}",
49
+ f"running on {fmt['default_engine']}: weights {_gib(run['weights'])} + KV {_gib(run['kv'])}"
50
+ f" + overhead {_gib(run['overhead'])} = {_gib(run['total'])} GiB",
51
+ ]
52
+ mag = data["magnitude"]
53
+ label = sizecalc.TIER_LABEL
54
+ detail = {tier: text for tier, _, text in sizecalc.TIERS}
55
+ if mag["fits"]:
56
+ lines.append(f"class: {label[mag['fits']]} ({detail[mag['fits']]})")
57
+ else:
58
+ lines.append("class: larger than one 8-GPU server; needs several nodes")
59
+ if mag["fits"] and mag["fits_as_is"] != mag["fits"]:
60
+ as_is = label[mag["fits_as_is"]] if mag["fits_as_is"] else "several nodes"
61
+ lines.append(
62
+ f" that tier needs a GGUF or MLX build of the same size; as {fmt['name']}: {as_is}"
63
+ )
64
+ if mag["runs"] and mag["runs"] != mag["fits"]:
65
+ lines.append(f" with system RAM offload it also runs on: {label[mag['runs']]}")
66
+ lines += ["", f"{'tier':<22} {'smallest device':<30} {'verdict':<21} {'tok/s<=':>8}"]
67
+ for t in data["tiers"]:
68
+ lines.append(f"{t['label']:<22} {t['name'] or '':<30} {_verdict(t):<21} {_speed(t):>8}")
69
+ if data["devices"]:
70
+ lines += _device_lines(data["devices"])
71
+ lines += ["", "same model in other formats:"]
72
+ for r in data["ladder"]:
73
+ mark = "*" if r["current"] else " "
74
+ where = label[r["fits"]] if r["fits"] else "several nodes"
75
+ if r["fits"] and r["fits_as_is"] != r["fits"]:
76
+ as_is = label[r["fits_as_is"]] if r["fits_as_is"] else "several nodes"
77
+ where += f" after converting; as given: {as_is}"
78
+ lines.append(
79
+ f" {mark}{r['format']:<10} {r['bits']:>6.2f} bpw {r['file_bytes'] / 1e9:>9.1f} GB"
80
+ f" fits from: {where}"
81
+ )
82
+ for note in data["notes"]:
83
+ lines.append(f"note: {note}")
84
+ lines.append(
85
+ "Estimates for sizing, not measurements. tok/s<= is the bandwidth ceiling of one "
86
+ "sequence's decode; measured runs reach roughly half to four fifths of it."
87
+ )
88
+ return "\n".join(lines)
89
+
90
+
91
+ def _device_lines(rows: list[dict[str, Any]]) -> list[str]:
92
+ out = [
93
+ "",
94
+ f"{'device':<30} {'engine':<10} {'format':<9} {'need GiB':>9} {'usable':>8} "
95
+ f"{'verdict':<21} {'tok/s<=':>8}",
96
+ ]
97
+ for r in rows:
98
+ out.append(
99
+ f"{r['name']:<30} {r['engine']:<10} {r['format_support']:<9}"
100
+ f" {_gib(r['need']['total']):>9} {_gib(r['usable_bytes']):>8}"
101
+ f" {_verdict(r):<21} {_speed(r):>8}"
102
+ )
103
+ return out
104
+
105
+
106
+ def page_data() -> dict[str, Any]:
107
+ """``sizecalc.page_data()`` with each catalog example's file size and KV per token read
108
+ from catalog.json."""
109
+ data = sizecalc.page_data()
110
+ entries = {e.id: e for e in catalog.load_catalog_file()}
111
+ for example in data["examples"]:
112
+ if "catalog" in example:
113
+ entry_id, quant = example.pop("catalog")
114
+ variant = next(v for v in entries[entry_id].variants if v.quant == quant)
115
+ example["file_bytes"] = variant.size_bytes
116
+ entry = entries[entry_id]
117
+ example["kv_per_token"] = entry.full_layers * entry.per_layer_f16
118
+ return data
119
+
120
+
121
+ def build_page() -> str:
122
+ """The self-contained HTML page with this module's tables inlined."""
123
+ page = (PAGE_DIR / "page.html").read_text(encoding="utf-8")
124
+ data = json.dumps(page_data(), ensure_ascii=False, separators=(",", ":"))
125
+ for marker, text in (
126
+ ("/*@DATA@*/", f"const SIZECALC_DATA = {data};"),
127
+ ("/*@CALC@*/", (PAGE_DIR / "calc.js").read_text(encoding="utf-8")),
128
+ ("/*@APP@*/", (PAGE_DIR / "app.js").read_text(encoding="utf-8")),
129
+ ):
130
+ page = page.replace(marker, text)
131
+ return page
132
+
133
+
134
+ HELP = (
135
+ "Size a model from its shape and weight format: the weight file, the memory running it "
136
+ "takes, and the smallest class of device that holds it, from phone to an 8-GPU server. "
137
+ "Give two of --params, --quant and --file-size and the third follows; --active makes it "
138
+ "MoE. The KV cache per token is guessed from the active parameters and --attention unless "
139
+ "--kv-per-token gives it (memcalc prints it for a real model). Consumer NVIDIA cards may "
140
+ "offload to system RAM the way llama.cpp does: routed experts (--n-cpu-moe) for MoE, whole "
141
+ "layers for dense models. Offline; nothing is read or downloaded. --html writes an "
142
+ "interactive page with the same tables."
143
+ )
144
+ EXAMPLES = [
145
+ ("%(prog)s --params 27B --quant Q4_K_M", "a dense 27B in the common GGUF"),
146
+ ("%(prog)s --params 30.5B --active 3.3B --quant Q4_K_M --context 64k", "an MoE"),
147
+ ("%(prog)s --params 671B --active 37B --quant FP8 --attention mla", "DeepSeek V3"),
148
+ ("%(prog)s --file-size 18.6GB --quant Q4_K_M", "how many parameters is this file"),
149
+ ("%(prog)s --params 8B --file-size 4.9GB --devices all", "every device"),
150
+ ("%(prog)s --html model-size.html", "the interactive page"),
151
+ ]
152
+
153
+
154
+ def add_parser(sub: Any) -> None:
155
+ p = sub.add_parser(
156
+ "sizecalc", help="weight file, memory and device class from params and quant (offline)"
157
+ )
158
+ p.add_argument("--params", metavar="N", help="total parameters such as 27B or 1.2T")
159
+ p.add_argument("--active", metavar="N", help="active parameters per token; makes it MoE")
160
+ p.add_argument(
161
+ "--quant", metavar="FORMAT", help="Q4_K_M, AWQ-INT4, FP8, NVFP4, MLX-4BIT, EXL3-4.0 or bpw"
162
+ )
163
+ p.add_argument("--file-size", metavar="SIZE", help="weight file size such as 16.4GB")
164
+ p.add_argument(
165
+ "--attention",
166
+ default="full",
167
+ choices=sorted(sizecalc.ATTENTION_KV_SHARE),
168
+ help="attention kind for the KV guess (default full)",
169
+ )
170
+ p.add_argument("--kv-per-token", metavar="SIZE", help="f16 K+V bytes per token, e.g. 64KiB")
171
+ p.add_argument(
172
+ "--context",
173
+ default=str(sizecalc.DEFAULT_CONTEXT),
174
+ metavar="TOKENS",
175
+ help="context per slot, e.g. 8k or 64k (default 8192)",
176
+ )
177
+ p.add_argument("--slots", type=int, default=1, help="parallel sequences (default 1)")
178
+ p.add_argument(
179
+ "--kv",
180
+ default="f16",
181
+ choices=sorted(sizecalc.KV_BYTES_PER_ELEM),
182
+ help="KV cache type (default f16)",
183
+ )
184
+ p.add_argument(
185
+ "--host-ram", default="64GiB", metavar="SIZE", help="a PC's system RAM (default 64GiB)"
186
+ )
187
+ p.add_argument("--devices", metavar="IDS", help="comma-separated device ids, or all")
188
+ p.add_argument("--json", action="store_true", help="print localmodels.sizecalc/v1 JSON")
189
+ p.add_argument("--html", metavar="PATH", help="write the interactive page and exit")
190
+ cli_help.document(
191
+ p,
192
+ HELP,
193
+ examples=EXAMPLES,
194
+ sections=[
195
+ ("devices", ", ".join(d.id for d in sizecalc.DEVICES)),
196
+ ("exit status", "0 printed · 2 bad input (message on stderr)"),
197
+ ],
198
+ )
199
+
200
+
201
+ def _devices(text: str | None) -> list[str]:
202
+ if not text:
203
+ return []
204
+ if text.strip().lower() == "all":
205
+ return [d.id for d in sizecalc.DEVICES]
206
+ ids = [i.strip() for i in text.split(",") if i.strip()]
207
+ unknown = [i for i in ids if i not in sizecalc.DEVICE_IDS]
208
+ if unknown:
209
+ raise MemcalcError(f"unknown device {', '.join(unknown)}; see --help for the list")
210
+ return ids
211
+
212
+
213
+ def cli(args: argparse.Namespace) -> int:
214
+ if args.html:
215
+ path = Path(args.html).expanduser()
216
+ try:
217
+ path.write_text(build_page(), encoding="utf-8")
218
+ except OSError as exc:
219
+ print(f"sizecalc: {exc}", file=sys.stderr)
220
+ return 2
221
+ print(f"wrote {path}")
222
+ return 0
223
+ try:
224
+ s, notes = sizecalc.shape(
225
+ params=parse_params(args.params) if args.params else None,
226
+ active=parse_params(args.active) if args.active else None,
227
+ fmt=args.quant,
228
+ file_bytes=parse_size(args.file_size) if args.file_size else None,
229
+ attention=args.attention,
230
+ kv_per_token=parse_size(args.kv_per_token) if args.kv_per_token else None,
231
+ )
232
+ posture = sizecalc.Posture(
233
+ context=parse_tokens(args.context),
234
+ slots=max(1, args.slots),
235
+ kv_type=args.kv,
236
+ host_ram=parse_size(args.host_ram),
237
+ )
238
+ data = sizecalc.report(s, posture, notes, _devices(args.devices))
239
+ except MemcalcError as exc:
240
+ print(f"sizecalc: {exc}", file=sys.stderr)
241
+ return 2
242
+ if args.json:
243
+ json.dump(data, sys.stdout, ensure_ascii=False, indent=1)
244
+ sys.stdout.write("\n")
245
+ else:
246
+ if not args.devices:
247
+ data = {**data, "devices": []}
248
+ print(render(data))
249
+ return 0
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import argparse
6
6
  import contextlib
7
+ import copy
7
8
  import json
8
9
  import os
9
10
  import secrets
@@ -22,16 +23,24 @@ from localmodels import (
22
23
  gateway,
23
24
  harness,
24
25
  hosts,
26
+ stack_card,
25
27
  stack_client_settings,
28
+ stack_down,
26
29
  stack_events,
27
30
  stack_journal,
31
+ stack_ledger,
32
+ stack_memory,
33
+ stack_preflight,
28
34
  stack_progress,
29
35
  stack_rollback,
30
36
  stack_run,
37
+ stack_try,
31
38
  stack_up,
32
39
  stack_update,
33
40
  stack_view_agent,
34
41
  stack_view_hub_cli,
42
+ stack_warm,
43
+ stack_whatif,
35
44
  )
36
45
  from localmodels import stack_decision as decide
37
46
  from localmodels import stack_doctor as day2
@@ -45,10 +54,10 @@ from localmodels.probe import HostFacts
45
54
  from localmodels.records import Plan, ProgressEvent
46
55
  from localmodels.stack_args import add_parser as add_parser
47
56
  from localmodels.stack_args import add_plan_arguments as add_plan_arguments
57
+ from localmodels.stack_args import conversation_cache as _conversation_cache
48
58
  from localmodels.stack_args import options_from_args as options_from_args
49
59
  from localmodels.stack_compose import agent_posture, compose, running_record
50
60
  from localmodels.stack_console import Board
51
- from localmodels.stack_hardware import conversation_cache as _conversation_cache
52
61
  from localmodels.stack_plan import (
53
62
  HARNESS_RAM,
54
63
  RAM_FLOOR,
@@ -105,6 +114,13 @@ def build(
105
114
  seen = app.probe(hosts.LOCAL_ID) if facts is None else facts
106
115
  if error := platform_error(seen["platform"], options.get("profile"), seen["arch"]):
107
116
  raise StackError(error)
117
+ # The preflight checks the Mac as it is, before --unified-memory prices a smaller one.
118
+ raw = copy.deepcopy(seen)
119
+ if seen["platform"] == "win32" and options.get("gateway") == "bifrost":
120
+ raise StackError( # the default follows the computer planning; --facts may be another's
121
+ "Bifrost has no Windows build; plan Windows facts with --gateway magpie, the gateway"
122
+ " stack plan picks on Windows itself"
123
+ )
108
124
  seen = hardware.assumed(seen, options.get("unified_memory"))
109
125
  resolver = deploy.catalog_pins if options.get("offline") else deploy.resolve_files
110
126
  context = approved
@@ -121,16 +137,35 @@ def build(
121
137
  tools_dir=tools_dir, approved=context["harness"] if context else None, private_clients=True
122
138
  )
123
139
  if options.get("update"):
124
- return stack_update.compose(seen, tools, options, resolver=resolver)
125
- if approved is not None:
140
+ plan = stack_update.compose(seen, tools, options, resolver=resolver)
141
+ elif approved is not None:
126
142
  # A retry with the same approval: the GPU memory the approved plan's own running parts
127
143
  # hold was free when the plan was made, so price the card as then. Otherwise a started
128
144
  # LLM (outside the suite slice) leaves --llm auto no card to fit (aws-l4, 2026-11-09).
129
145
  seen = stack_update.reclaimed(seen, _own_running_pids(approved))
130
- return compose(
146
+ plan = compose(
131
147
  seen, tools, options, resolver=resolver, approved=approved, previous=_attempted
132
148
  )
133
- return stack_update.with_replaced(compose(seen, tools, options, resolver=resolver))
149
+ else:
150
+ plan = stack_update.with_replaced(compose(seen, tools, options, resolver=resolver))
151
+ if approved is None and isinstance(plan, dict) and "ram" in raw and "disk" in raw:
152
+ # Apply rebuilds the plan to prove it unchanged; it has already probed and needs no
153
+ # second read-only report (and would see its own apply lock). Partial facts have no
154
+ # disk or RAM reading for the checks.
155
+ plan["preflight"] = stack_preflight.check(plan, raw, live=facts is None, priced=seen)
156
+ if (
157
+ approved is None
158
+ and isinstance(plan, dict)
159
+ and plan.get("hardware")
160
+ and options["llm"] == "auto"
161
+ and not options.get("update")
162
+ ):
163
+ # The other choice for this computer, for the summary and install's prompt; like the
164
+ # rest of ``hardware`` it is an observation and not part of the approval.
165
+ offered = hardware.view(seen, options, agent_posture(options)).get("picks")
166
+ if offered:
167
+ plan["hardware"]["picks"] = offered
168
+ return plan
134
169
 
135
170
 
136
171
  def _attempted(name: str, port: int) -> Plan | None:
@@ -321,18 +356,7 @@ def execute(
321
356
  """Run a plan that passed its gate (apply's, or stack_rollback's) under the apply lock."""
322
357
  session = stack_run.new_session(plan, rollback_from)
323
358
  parts: dict[str, Component] = {}
324
- order = (
325
- "tools",
326
- "decision",
327
- "llm",
328
- "embedding",
329
- "rerank",
330
- "stt",
331
- "tts",
332
- "search",
333
- "gateway",
334
- "acceptance",
335
- )
359
+ order = ("tools", *stack_events.APPLY_ORDER, "acceptance")
336
360
 
337
361
  def persist(current: str | None = None) -> StackRecord:
338
362
  components = [parts[k] for k in order if k in parts]
@@ -402,6 +426,13 @@ def _run_components(
402
426
  component_output("llm", plan["llm"], True),
403
427
  do,
404
428
  )
429
+ if fast := plan.get("llm_fast"):
430
+ persist("llm_fast")
431
+ keys["llm_fast"] = service_key(fast)
432
+ parts["llm_fast"] = _deploy_aux(
433
+ "llm_fast", fast, keys["llm_fast"], component_output("llm_fast", fast), do
434
+ )
435
+ persist(None)
405
436
  front = plan.get("decision_front")
406
437
  if plan["decision"] is not None and front is not None:
407
438
  persist("decision")
@@ -458,6 +489,12 @@ def _run_components(
458
489
 
459
490
  blockers = [name for name in ("tools", "llm") if parts[name]["status"] != "ok"]
460
491
  decision_ok = "decision" in parts and parts["decision"]["status"] == "ok"
492
+ if plan.get("llm_fast"):
493
+ blockers += [
494
+ name
495
+ for name in ("llm_fast", "decision")
496
+ if name not in parts or parts[name]["status"] != "ok"
497
+ ]
461
498
  if blockers:
462
499
  parts["gateway"] = stack_run.skipped("gateway", ", ".join(blockers) + " failed")
463
500
  parts["acceptance"] = stack_run.skipped("acceptance", "gateway not wired")
@@ -521,12 +558,18 @@ _WAITS = {
521
558
  "verify": "Sending acceptance requests to the running stack…",
522
559
  "doctor": "Checking services, ports, gateway and tools…",
523
560
  "up": "Starting services that are not running and waiting for health checks…",
561
+ "down": "Stopping the gateway and the stack's services…",
524
562
  }
525
563
 
526
564
 
527
565
  def _day2(args: argparse.Namespace) -> int:
528
566
  handlers = {
529
567
  "up": stack_up.cli,
568
+ "down": stack_down.cli,
569
+ "warm": stack_warm.cli,
570
+ "try": stack_try.cli,
571
+ "ledger": stack_ledger.cli,
572
+ "card": stack_card.cli,
530
573
  "rollback": stack_rollback.cli,
531
574
  "view": board.cli,
532
575
  "clients": stack_client_settings.cli,
@@ -548,6 +591,11 @@ def cli(args: argparse.Namespace) -> int:
548
591
  if args.stack_command in (
549
592
  *day2.COMMANDS,
550
593
  "up",
594
+ "down",
595
+ "warm",
596
+ "try",
597
+ "ledger",
598
+ "card",
551
599
  "rollback",
552
600
  "view",
553
601
  "clients",
@@ -558,6 +606,10 @@ def cli(args: argparse.Namespace) -> int:
558
606
  if args.stack_command == "decisions":
559
607
  print(decide.listing())
560
608
  return 0
609
+ if args.stack_command == "memory":
610
+ return stack_memory.cli(args)
611
+ if args.stack_command == "what-if":
612
+ return stack_whatif.cli(args)
561
613
  facts = (
562
614
  decode(json.loads(args.facts.read_text(encoding="utf-8")), HostFacts)
563
615
  if getattr(args, "facts", None)
@@ -15,30 +15,50 @@ from localmodels import (
15
15
  cli_help,
16
16
  deploy,
17
17
  harness,
18
+ stack_card,
18
19
  stack_debug,
20
+ stack_down,
21
+ stack_ledger,
22
+ stack_memory,
19
23
  stack_ports,
20
24
  stack_rollback,
21
25
  stack_suite,
26
+ stack_try,
22
27
  stack_up,
23
28
  stack_update,
24
29
  stack_view_agent,
25
30
  stack_view_hub_cli,
26
31
  stack_view_serve,
32
+ stack_warm,
33
+ stack_whatif,
27
34
  vision,
28
35
  )
29
36
  from localmodels import stack_decision as decide
30
37
  from localmodels import stack_doctor as day2
31
38
  from localmodels import stack_hardware as hardware
32
39
  from localmodels.context_policy import AGENT, window_k
33
- from localmodels.stack_hardware import conversation_cache as conversation_cache
34
- from localmodels.stack_plan import PREFERENCES, REASONING_BUDGET, StackOptions
40
+ from localmodels.stack_plan import PREFERENCES, REASONING_BUDGET, StackOptions, default_gateway
35
41
 
36
42
  Parsers: TypeAlias = "argparse._SubParsersAction[argparse.ArgumentParser]"
37
43
 
38
44
  GROUPS = (
39
- ("plan", ("plan", "hardware", "decisions")),
40
- ("install", ("install", "apply", "up", "rollback")),
41
- ("operate", ("status", "view", "view-hub", "view-agent", "verify", "doctor")),
45
+ ("plan", ("plan", "hardware", "memory", "what-if", "decisions")),
46
+ ("install", ("install", "apply", "up", "down", "rollback")),
47
+ (
48
+ "operate",
49
+ (
50
+ "status",
51
+ "warm",
52
+ "try",
53
+ "ledger",
54
+ "card",
55
+ "view",
56
+ "view-hub",
57
+ "view-agent",
58
+ "verify",
59
+ "doctor",
60
+ ),
61
+ ),
42
62
  ("clean up", ("remove", "prune")),
43
63
  ("for installers and agents", ("capabilities", "commands", "clients")),
44
64
  )
@@ -51,17 +71,25 @@ Nothing is downloaded or started until you approve a saved plan.
51
71
 
52
72
  typical flow:
53
73
  1. hardware what this computer can run (read-only)
74
+ memory MODEL VRAM and RAM one LLM would take, no probe (read-only)
75
+ what-if hardware upgrades and what they unlock (read-only)
54
76
  2. plan price the whole stack, save it, print the apply command
55
77
  3. apply PLAN --approve ID install that plan with live progress, then verify it
56
78
  (install does 2 and 3 with a y/N prompt in between)
57
- 4. status, verify, doctor day-2 checks; up starts the stack again after a reboot
58
- 5. plan --update, rollback replace what changed; go back to the previous accepted plan"""
79
+ 4. status, verify, doctor day-2 checks; up starts the stack again after a reboot,
80
+ down stops it (nothing is removed)
81
+ warm free memory, warm the LLM, print its measured speed
82
+ 5. plan --update, rollback replace what changed; go back to the previous accepted plan
83
+ 6. remove uninstall everything but the downloads (--purge: those too)"""
59
84
  AGENTS = """\
60
- Read-only: hardware, decisions, plan (saves a file), status, view, verify, doctor, commands,
61
- clients, and rollback without --approve.
85
+ Read-only: hardware, memory, what-if, decisions, plan (saves a file), status, view, verify, doctor,
86
+ commands, clients, ledger, card (writes a local SVG), remove --dry-run, and rollback without
87
+ --approve. warm sends the LLM two short requests and changes nothing else (--sudo also runs
88
+ macOS purge).
62
89
  Installs only an approved plan: apply PLAN --approve ID, rollback --approve ID; install asks
63
- y/N (--yes skips). Also changes things: up (starts what was installed), remove, prune --yes.
64
- Machine output: --json on plan, hardware, status, view, verify, doctor, up, apply, clients.
90
+ y/N (--yes skips). Also changes things: up (starts what was installed), down (stops it), remove, prune --yes.
91
+ Machine output: --json on plan, hardware, memory, what-if, status, view, verify, doctor, up, down, apply,
92
+ clients, warm, ledger.
65
93
  `%(prog)s commands --json` describes every subcommand and option as JSON.
66
94
  Progress bars draw only on a terminal; piped output is plain lines (NO_COLOR also honored)."""
67
95
  EXIT = (
@@ -82,6 +110,13 @@ def _tokens(value: str) -> int:
82
110
  return tokens
83
111
 
84
112
 
113
+ def conversation_cache(value: str) -> str:
114
+ value = value.strip().lower()
115
+ if value in ("auto", "off") or (value.isdigit() and int(value) > 0):
116
+ return value
117
+ raise argparse.ArgumentTypeError("auto, off, or a positive whole number of MiB, e.g. 4096")
118
+
119
+
85
120
  def _budget(value: str) -> int:
86
121
  """A thinking budget in tokens; 0 or off removes the cap."""
87
122
  if value.strip().lower() == "off":
@@ -115,9 +150,11 @@ def options_from_args(args: argparse.Namespace) -> StackOptions:
115
150
  "offline": args.offline,
116
151
  "reasoning_budget": args.reasoning_budget,
117
152
  }
153
+ if getattr(args, "route", None):
154
+ options["route"] = args.route
118
155
  if args.context is not None: # only when given, so plans made without it keep their ids
119
156
  options["context"] = args.context
120
- options["gateway"] = getattr(args, "gateway", None) or harness.DEFAULT_GATEWAY
157
+ options["gateway"] = getattr(args, "gateway", None) or default_gateway()
121
158
  options["vision"] = getattr(args, "vision", None) or vision.DEFAULT
122
159
  if getattr(args, "prefer", "smartest") != "smartest": # only when given, like --gpu
123
160
  options["prefer"] = args.prefer
@@ -149,7 +186,15 @@ def add_plan_arguments(plan: argparse.ArgumentParser) -> None:
149
186
  default="smartest",
150
187
  help="what auto optimizes (roadmap decision 26): smartest, the highest installed "
151
188
  "SimplexAI score that fits (default); concurrent, at least two requests decoding "
152
- "together; fast, the fastest model within a few points of the smartest",
189
+ "together; fast, the fastest model within a few points of the smartest; fastest, the "
190
+ "highest decode speed that fits whatever its score (the second choice `stack hardware` "
191
+ "and `install` offer)",
192
+ )
193
+ choose.add_argument(
194
+ "--route",
195
+ choices=["none", "fastest"],
196
+ action=cli_help.ComponentSelection,
197
+ help="add the fastest LLM for easy turns (Bifrost and a decision model required)",
153
198
  )
154
199
  decide.add_arguments(choose)
155
200
  stack_suite.add_arguments(choose)
@@ -379,6 +424,8 @@ def _inspect(actions: Parsers) -> None:
379
424
  )
380
425
  seen.add_argument("--json", action="store_true", help="print the readings as JSON")
381
426
  hardware.add_arguments(seen)
427
+ stack_memory.add_parser(actions)
428
+ stack_whatif.add_parser(actions)
382
429
  cli_help.document(
383
430
  seen,
384
431
  "Read-only: each GPU's model, VRAM (total, used, free, usable by the agent LLM), spec "
@@ -475,6 +522,11 @@ def _day2(actions: Parsers) -> None:
475
522
  day2.add_parsers(actions)
476
523
  _clients(actions)
477
524
  stack_up.add_parser(actions)
525
+ stack_down.add_parser(actions)
526
+ stack_warm.add_parser(actions)
527
+ stack_try.add_parser(actions)
528
+ stack_ledger.add_parser(actions)
529
+ stack_card.add_parser(actions)
478
530
  stack_rollback.add_parser(actions)
479
531
  stack_view_serve.add_parser(actions)
480
532
  stack_view_hub_cli.add_parser(actions)
@@ -504,13 +556,33 @@ def _day2(actions: Parsers) -> None:
504
556
  "check: no new plan, no download, no reinstall. A changed stack needs apply.",
505
557
  [("%(prog)s", "the last accepted plan"), ("%(prog)s --timeout 300", "")],
506
558
  ),
559
+ "down": (
560
+ "stop the stack's services and its gateway; nothing is removed",
561
+ "Stop the gateway this tool started, then every service a stack apply under this "
562
+ "state directory deployed, each only through its own unit or process receipt. "
563
+ "Units stay enabled and nothing is deleted or forgotten, so `stack up` starts the "
564
+ "same stack again; a global magpie.service, external services and deployments "
565
+ "made outside `stack` are left running. Nothing running is a success. Exit 0 all "
566
+ "stopped, 1 any stop failed, 2 refused (another apply is running).",
567
+ [("%(prog)s", ""), ("%(prog)s --json", "localmodels.stack-down/v1, for installers")],
568
+ ),
507
569
  "remove": (
508
- "undo what this tool installed; model files and logs stay",
509
- "Undo what the owned manifest records: gateway wiring, pi's default model, stack "
510
- "services, the gateway this tool started, its tools and slice. Other deployments are "
511
- "listed and left alone. --purge also deletes model files and deployment directories "
512
- "after listing them and asking for a confirmation word (--yes skips the word).",
513
- [("%(prog)s", "keep weights for a later install"), ("%(prog)s --purge", "")],
570
+ "uninstall the stack; only downloaded files stay (--purge: those too)",
571
+ "Uninstall what the owned manifest records for the stack: gateway wiring, pi's "
572
+ "default model, the services with their directories and logs, the gateway and its "
573
+ "data, the unpacked tools and the engines only this stack ran, saved plans and run "
574
+ "records. What was downloaded and verified stays (the model files and the tool and "
575
+ "engine archives), so the next install needs no download; --purge deletes that too "
576
+ "after listing every file and asking for a confirmation word (--yes skips the "
577
+ "word). Deployments made outside `stack`, or recorded under another state "
578
+ "directory, are listed and left alone unless --all. --dry-run lists what would go "
579
+ "and what would stay and changes nothing.",
580
+ [
581
+ ("%(prog)s --dry-run", "what an uninstall would delete and keep"),
582
+ ("%(prog)s", "uninstall, keep the downloads for the next install"),
583
+ ("%(prog)s --purge", "uninstall and delete the downloads too"),
584
+ ("%(prog)s --all", "also the deployments made outside `stack`"),
585
+ ],
514
586
  ),
515
587
  "rollback": (
516
588
  "go back to the previous accepted plan; read-only without --approve",