@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,721 @@
1
+ """``stack memory``: the VRAM and RAM one LLM would hold under the stack's llama.cpp posture, from a
2
+ few inputs and without probing this computer.
3
+
4
+ MODEL is named the way ``stack plan --llm`` names it (a catalog id, or an HF GGUF repo
5
+ ``owner/name[:QUANT]``) or the way ``memcalc`` reads one (a local .gguf, config.json or directory,
6
+ or a safetensors repo id). Pricing goes through the calls the plan makes: the card through
7
+ ``estimator.agent_footprint_parts`` plus the projector (``vision``); host RAM on a card through
8
+ ``estimator.LLAMA_HOST_BASE_BYTES`` and ``context_checkpoint_bytes``; a Mac's host side through
9
+ ``context_policy.metal_checkpoint_bytes`` and ``cache_floor_bytes``, as ``deploy`` prices it.
10
+ Budgets follow ``stack plan``: a card keeps ``AGENT_VRAM_RESERVE_BYTES`` back and the host keeps
11
+ ``RAM_FLOOR``; a Mac keeps macOS's share (``metal.in_use``), ``metal.HOST_KEEP_BYTES`` and the
12
+ display's share. Every number is an estimate; a measured run outranks it.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ import sys
21
+ from collections.abc import Callable, Mapping, Sequence
22
+ from dataclasses import dataclass, field, replace
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from localmodels import catalog, cli_help, estimator, hf_repo, metal, vision
27
+ from localmodels.context_policy import (
28
+ AGENT,
29
+ METAL_CTX_CHECKPOINTS,
30
+ cache_floor_bytes,
31
+ metal_checkpoint_bytes,
32
+ posture_for,
33
+ )
34
+ from localmodels.estimator import LayerKind, ModelProfile
35
+ from localmodels.memcalc import (
36
+ KV_TYPES,
37
+ MemcalcError,
38
+ parse_params,
39
+ parse_size,
40
+ parse_tokens,
41
+ quant_bits,
42
+ )
43
+ from localmodels.memcalc_load import WeightOptions, load_model
44
+ from localmodels.plan_envelope import PlanError
45
+ from localmodels.stack_plan import RAM_FLOOR
46
+
47
+ SCHEMA = "localmodels.stack-memory/v1"
48
+ GIB, MIB = 1 << 30, 1 << 20
49
+ DEFAULT_CONTEXTS = (65536, 131072, 262144)
50
+ MAX_SLOTS = 64 # the largest concurrency max_slots searches
51
+ MAX_CONTEXT = 1 << 24 # the longest per-slot context max_context searches
52
+ DEVICE_PARTS = ("weights", "kv", "state", "compute", "draft", "process", "vision")
53
+ HOST_PARTS = ("embedding", "process", "checkpoints", "prompt_cache", "vision")
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Subject:
58
+ """The model being priced: its estimator profile and what the report says about it."""
59
+
60
+ name: str
61
+ source: str # "catalog", "hf-gguf", "gguf" or "config.json"
62
+ quant: str
63
+ profile: ModelProfile
64
+ weights_source: str
65
+ projector_bytes: int = 0 # the image projector file; 0 when the model has none
66
+ runtime: str = "llama.cpp"
67
+ mtp: bool | None = None # an MTP head: True, False (known absent) or None (unknown)
68
+ context_source: str = "" # where n_ctx_train comes from: a catalog cap or the model's own
69
+ notes: tuple[str, ...] = ()
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Posture:
74
+ """The launch the estimate assumes: ``-c``, ``-np``, ``-ctk/-ctv``, ``-ub`` and the rest."""
75
+
76
+ kv_types: tuple[str, str] = AGENT.kv_types[0]
77
+ slots: int = AGENT.slots
78
+ shared: bool = True # one --kv-unified pool of `context` tokens; False: slots x context
79
+ ubatch: int = AGENT.ubatch
80
+ mtp: bool = False
81
+ vision: str = vision.DEFAULT # one of vision.READERS
82
+ # --cache-ram; None is the floor the stack guarantees ahead of the window (2048 MiB on a card,
83
+ # cache_floor_bytes on a Mac). It grows the cache toward AGENT.prompt_cache_mib only from RAM
84
+ # left over (stack_llm_ram), so the floor is what has to fit.
85
+ prompt_cache: int | None = None
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Machine:
90
+ """The memory the estimate is checked against; every field optional."""
91
+
92
+ vram: int | None = None # one discrete card's total memory
93
+ vram_used: int = 0 # what other processes hold on it
94
+ ram: int | None = None # host RAM beside a discrete card
95
+ unified: int | None = None # a Mac's unified memory
96
+ working_set: int | None = None # the Mac's Metal working set; default: Apple's share
97
+
98
+ @property
99
+ def metal(self) -> bool:
100
+ return self.unified is not None
101
+
102
+
103
+ METAL = posture_for(AGENT, "metal") # Metal's checkpoint count and KV ladder
104
+
105
+
106
+ @dataclass
107
+ class Priced:
108
+ device: dict[str, int] = field(default_factory=dict)
109
+ host: dict[str, int] = field(default_factory=dict)
110
+
111
+ @property
112
+ def device_total(self) -> int:
113
+ return sum(self.device.values())
114
+
115
+ @property
116
+ def host_total(self) -> int:
117
+ return sum(self.host.values())
118
+
119
+
120
+ # ── naming the model ───────────────────────────────────────────────────
121
+
122
+
123
+ def _from_entry(entry: catalog.CatalogEntry, quant: str | None, source: str) -> Subject:
124
+ variants = {v.quant.lower(): v for v in entry.variants}
125
+ if quant is None:
126
+ variant = entry.variants[-1] # the variant stack plan picks without --quant
127
+ elif quant.lower() in variants:
128
+ variant = variants[quant.lower()]
129
+ else:
130
+ names = ", ".join(v.quant for v in entry.variants)
131
+ raise MemcalcError(f"{entry.id} has no quant {quant}; it has {names}")
132
+ notes = []
133
+ if entry.runtime != "llama.cpp":
134
+ notes.append(f"{entry.id} runs on {entry.runtime}; priced as llama.cpp")
135
+ return Subject(
136
+ name=entry.id,
137
+ source=source,
138
+ quant=variant.quant,
139
+ profile=estimator.eager(entry.profile(variant)), # the agent argv has no --lazy-mode
140
+ weights_source=f"{variant.quant} files, {variant.size_bytes / GIB:.2f} GiB",
141
+ projector_bytes=entry.mmproj.size_bytes if entry.mmproj else 0,
142
+ runtime=entry.runtime,
143
+ mtp=entry.mtp_capable,
144
+ context_source="catalog" if source == "catalog" else "gguf header",
145
+ notes=tuple(notes),
146
+ )
147
+
148
+
149
+ def resolve(
150
+ spec: str,
151
+ *,
152
+ quant: str | None = None,
153
+ params: str | None = None,
154
+ weights: str | None = None,
155
+ endpoint: str = "https://huggingface.co",
156
+ entries: tuple[catalog.CatalogEntry, ...] | None = None,
157
+ entry_for: Callable[..., catalog.CatalogEntry] = hf_repo.entry_for,
158
+ ) -> Subject:
159
+ """The model ``spec`` names: a catalog id or GGUF repo (``stack plan --llm``), else whatever
160
+ ``memcalc`` reads (a local file or directory, or a safetensors repo id)."""
161
+ entries = catalog.load_catalog_file() if entries is None else entries
162
+ local = Path(spec).expanduser().exists()
163
+ known = any(spec in (e.id, e.variants[-1].model_id) for e in entries)
164
+ gguf_repo = hf_repo.spec_parts(spec) is not None and (
165
+ ":" in spec.rpartition("/")[2] or spec.rstrip("/").lower().endswith("gguf")
166
+ )
167
+ if not local and (known or gguf_repo):
168
+ if params or weights:
169
+ raise MemcalcError(
170
+ "--params and --weights apply to a .gguf, config.json or safetensors repo; "
171
+ f"{spec} is priced from its files (--quant picks a variant)"
172
+ )
173
+ entry = entry_for(spec, entries, api=endpoint)
174
+ return _from_entry(entry, quant, "catalog" if known else "hf-gguf")
175
+ if not local and hf_repo.spec_parts(spec) is None:
176
+ close = hf_repo.close_ids(spec, [e.id for e in entries])
177
+ hint = f"; did you mean {' or '.join(close)}?" if close else ""
178
+ raise MemcalcError(
179
+ f"catalog has no model {spec}{hint} (name a catalog id, an HF repo owner/name[:QUANT], "
180
+ "or a local .gguf, config.json or directory)"
181
+ )
182
+ bits = quant_bits(quant) if quant else None
183
+ opts = WeightOptions(
184
+ weights=parse_size(weights) if weights else None,
185
+ params=parse_params(params) if params else None,
186
+ bits=bits,
187
+ )
188
+ model = load_model(spec, opts, endpoint=endpoint)
189
+ notes = list(model.notes)
190
+ if model.has_vision:
191
+ notes.append("the model reads images; its projector is not priced (no projector file)")
192
+ return Subject(
193
+ name=model.name,
194
+ source=model.source,
195
+ quant=quant or "",
196
+ profile=estimator.eager(model.profile),
197
+ weights_source=model.weights_source,
198
+ mtp=True if model.profile.mtp_layer_bytes else None,
199
+ context_source="gguf header" if model.source == "gguf" else "config.json",
200
+ notes=tuple(notes),
201
+ )
202
+
203
+
204
+ # ── pricing ────────────────────────────────────────────────────────────
205
+
206
+
207
+ def vision_mode(subject: Subject, posture: Posture, machine: Machine) -> str:
208
+ """Where the projector runs: the plan's 23.5 GiB rule for ``auto``; "off" without one."""
209
+ if not subject.projector_bytes:
210
+ return "off"
211
+ size = machine.vram if machine.vram is not None else 1 << 62
212
+ return vision.reader(posture.vision, size, unified=machine.metal)
213
+
214
+
215
+ def auto_reader(
216
+ subject: Subject, posture: Posture, machine: Machine, contexts: Sequence[int]
217
+ ) -> tuple[str, str]:
218
+ """``auto``'s reader and why. Like ``vision.priced``, a GPU reader on a card may never cost
219
+ the model anything: when it would shorten the longest context asked for, it moves to the
220
+ CPU. On a Mac either reader takes the same memory, so it stays on the GPU."""
221
+ mode = vision_mode(subject, posture, machine)
222
+ if posture.vision != "auto" or mode != "gpu" or machine.metal or machine.vram is None:
223
+ return mode, ""
224
+ want = max(contexts)
225
+ on_gpu = max_context(subject, replace(posture, vision="gpu"), machine)
226
+ on_cpu = max_context(subject, replace(posture, vision="cpu"), machine)
227
+ if on_gpu < min(on_cpu, want):
228
+ return "cpu", (
229
+ "the picture reader runs on the CPU: on the GPU it would cut the longest context "
230
+ f"from {min(on_cpu, want):,} to {on_gpu:,} tokens (stack plan's rule)"
231
+ )
232
+ return mode, ""
233
+
234
+
235
+ def price(subject: Subject, posture: Posture, context: int, *, metal_host: bool) -> Priced:
236
+ """Device and host bytes for ``posture.slots`` sequences of ``context`` tokens each."""
237
+ profile = subject.profile
238
+ window = context if posture.shared else context * posture.slots
239
+ device: dict[str, int] = dict(
240
+ estimator.agent_footprint_parts(
241
+ profile,
242
+ window,
243
+ slots=posture.slots,
244
+ kv_types=posture.kv_types,
245
+ ubatch=posture.ubatch,
246
+ mtp=posture.mtp,
247
+ )
248
+ )
249
+ mode = posture.vision
250
+ device["vision"] = subject.projector_bytes + vision.LLAMA_ENCODER_BYTES if mode == "gpu" else 0
251
+ embedding = 0 if profile.tied_embeddings else profile.embd_table_bytes
252
+ reader = subject.projector_bytes if mode == "cpu" else 0
253
+ if metal_host: # deploy's Metal host side: embeddings, checkpoints, the cache floor
254
+ host = {
255
+ "embedding": embedding,
256
+ "process": 0,
257
+ "checkpoints": metal_checkpoint_bytes(profile, METAL, posture.slots, posture.kv_types),
258
+ "prompt_cache": cache_floor_bytes(METAL, profile)
259
+ if posture.prompt_cache is None
260
+ else posture.prompt_cache,
261
+ "vision": reader,
262
+ }
263
+ else: # estimator.llama_host_bytes plus the --cache-ram floor
264
+ host = {
265
+ "embedding": embedding,
266
+ "process": estimator.LLAMA_HOST_BASE_BYTES,
267
+ "checkpoints": posture.slots
268
+ * estimator.LLAMA_CTX_CHECKPOINTS
269
+ * estimator.context_checkpoint_bytes(profile, posture.kv_types),
270
+ "prompt_cache": AGENT.prompt_cache_min_mib * MIB
271
+ if posture.prompt_cache is None
272
+ else posture.prompt_cache,
273
+ "vision": reader,
274
+ }
275
+ return Priced(device=device, host=host)
276
+
277
+
278
+ def device_budget(machine: Machine, host_total: int) -> tuple[int | None, str]:
279
+ """The device bytes the LLM may use, and the rule that set them; (None, "") without one."""
280
+ if machine.unified is not None:
281
+ total = machine.unified
282
+ working = machine.working_set or metal.default_working_set(total)
283
+ room = total - metal.in_use(total) - metal.HOST_KEEP_BYTES - host_total
284
+ if working <= room:
285
+ rule = f"Metal working set {working / GIB:.2f} GiB less the display's share"
286
+ else:
287
+ rule = (
288
+ f"{total / GIB:.0f} GiB less macOS {metal.in_use(total) / GIB:.1f} GiB, the "
289
+ f"stack's {metal.HOST_KEEP_BYTES / GIB:.0f} GiB, host side "
290
+ f"{host_total / GIB:.2f} GiB and the display's share"
291
+ )
292
+ return min(working, room) - estimator.METAL_VRAM_RESERVE_BYTES, rule
293
+ if machine.vram is not None:
294
+ rule = (
295
+ f"{machine.vram / GIB:.2f} GiB card less {machine.vram_used / GIB:.2f} GiB in use and "
296
+ f"the {estimator.AGENT_VRAM_RESERVE_BYTES / GIB:.0f} GiB reserve"
297
+ )
298
+ return machine.vram - machine.vram_used - estimator.AGENT_VRAM_RESERVE_BYTES, rule
299
+ return None, ""
300
+
301
+
302
+ def host_room(machine: Machine) -> int | None:
303
+ """Host RAM the LLM may use beside a card: RAM less the plan's floor; None when not given
304
+ (a Mac's host side is inside its device budget)."""
305
+ return None if machine.ram is None or machine.metal else machine.ram - RAM_FLOOR
306
+
307
+
308
+ def verdict(machine: Machine, priced: Priced) -> tuple[bool | None, bool | None]:
309
+ """(device fits, host fits); None where the machine does not say."""
310
+ budget, _ = device_budget(machine, priced.host_total)
311
+ room = host_room(machine)
312
+ return (
313
+ None if budget is None else priced.device_total <= budget,
314
+ None if room is None else priced.host_total <= room,
315
+ )
316
+
317
+
318
+ def _fits(subject: Subject, posture: Posture, machine: Machine, context: int) -> bool:
319
+ device, host = verdict(machine, price(subject, posture, context, metal_host=machine.metal))
320
+ return bool(device) and host is not False
321
+
322
+
323
+ def max_context(subject: Subject, posture: Posture, machine: Machine) -> int:
324
+ """The longest context (at most MAX_CONTEXT) that fits the card and the host: the shared
325
+ pool's -c with ``posture.shared``, else each slot's; 0 when none does."""
326
+ if not _fits(subject, posture, machine, 1):
327
+ return 0
328
+ lo, hi = 1, MAX_CONTEXT
329
+ while lo < hi:
330
+ mid = (lo + hi + 1) // 2
331
+ if _fits(subject, posture, machine, mid):
332
+ lo = mid
333
+ else:
334
+ hi = mid - 1
335
+ return lo
336
+
337
+
338
+ def max_slots(subject: Subject, posture: Posture, machine: Machine, context: int) -> int:
339
+ """How many sequences of ``context`` tokens fit when each owns its KV (``-c N*T``)."""
340
+ best = 0
341
+ for n in range(1, MAX_SLOTS + 1):
342
+ if not _fits(subject, replace(posture, slots=n, shared=False), machine, context):
343
+ break
344
+ best = n
345
+ return best
346
+
347
+
348
+ def report(
349
+ subject: Subject, posture: Posture, machine: Machine, contexts: Sequence[int]
350
+ ) -> dict[str, Any]:
351
+ """The ``localmodels.stack-memory/v1`` document."""
352
+ if posture.mtp and subject.mtp is False:
353
+ raise MemcalcError(f"{subject.name} has no MTP head; --mtp does not apply")
354
+ mode, why = auto_reader(subject, posture, machine, contexts)
355
+ posture = replace(posture, vision=mode)
356
+ p = subject.profile
357
+ train = p.n_ctx_train
358
+ rows = []
359
+ for context in contexts:
360
+ priced = price(subject, posture, context, metal_host=machine.metal)
361
+ budget, _ = device_budget(machine, priced.host_total)
362
+ device_fits, host_fits = verdict(machine, priced)
363
+ row: dict[str, Any] = {
364
+ "context": context,
365
+ "n_ctx": context if posture.shared else context * posture.slots,
366
+ "device": {**priced.device, "total": priced.device_total},
367
+ "host": {**priced.host, "total": priced.host_total},
368
+ }
369
+ if budget is not None:
370
+ row["device_budget"] = budget
371
+ row["device_fits"] = device_fits
372
+ row["fits"] = bool(device_fits) and host_fits is not False
373
+ row["max_slots"] = max_slots(subject, posture, machine, context)
374
+ if host_fits is not None:
375
+ row["host_fits"] = host_fits
376
+ if train and context > train:
377
+ row["beyond_train_context"] = True
378
+ rows.append(row)
379
+ budget, rule = device_budget(
380
+ machine, price(subject, posture, 1, metal_host=machine.metal).host_total
381
+ )
382
+ notes = list(subject.notes) + ([why] if why else [])
383
+ if machine.metal and posture.kv_types[0] != posture.kv_types[1]:
384
+ notes.append(
385
+ "Metal's flash attention has kernels for matching K/V types only; mixed is slow"
386
+ )
387
+ if posture.mtp and not p.mtp_layer_bytes:
388
+ notes.append("MTP blocks of unknown size stay in the weights (priced on the card)")
389
+ counts = {kind: sum(1 for k, _ in p.layers if k == kind) for kind in LayerKind}
390
+ out: dict[str, Any] = {
391
+ "schema": SCHEMA,
392
+ "model": {
393
+ "name": subject.name,
394
+ "source": subject.source,
395
+ "quant": subject.quant,
396
+ "runtime": subject.runtime,
397
+ "architecture": p.architecture,
398
+ "moe": p.moe,
399
+ "weights_bytes": p.weights_bytes,
400
+ "weights_source": subject.weights_source,
401
+ "train_context": train,
402
+ "context_source": subject.context_source,
403
+ "layers": {
404
+ "full_attention": counts[LayerKind.FULL],
405
+ "window": counts[LayerKind.SWA],
406
+ "recurrent": counts[LayerKind.RECURRENT],
407
+ },
408
+ "window_size": p.swa_window,
409
+ "kv_bytes_per_token": _kv_per_token(p, posture.kv_types),
410
+ "recurrent_state_bytes": estimator.recurrent_state_bytes(p, slots=1),
411
+ "projector_bytes": subject.projector_bytes,
412
+ },
413
+ "posture": {
414
+ "engine": "llama.cpp",
415
+ "backend": "metal" if machine.metal else "cuda",
416
+ "kv_types": list(posture.kv_types),
417
+ "slots": posture.slots,
418
+ "pool": "shared" if posture.shared else "split",
419
+ "ubatch": posture.ubatch,
420
+ "mtp": posture.mtp,
421
+ "vision": mode,
422
+ "prompt_cache_bytes": rows[0]["host"]["prompt_cache"] if rows else 0,
423
+ "context_checkpoints": METAL_CTX_CHECKPOINTS
424
+ if machine.metal
425
+ else estimator.LLAMA_CTX_CHECKPOINTS,
426
+ },
427
+ "machine": _machine_doc(machine),
428
+ "rows": rows,
429
+ "notes": notes,
430
+ "estimate": True,
431
+ }
432
+ if budget is not None:
433
+ out["device_budget"] = budget
434
+ out["budget_rule"] = rule
435
+ out["max_context"] = max_context(subject, posture, machine)
436
+ out["max_context_is"] = "the shared pool (-c)" if posture.shared else "each slot's"
437
+ room = host_room(machine)
438
+ if room is not None:
439
+ out["host_room"] = room
440
+ return out
441
+
442
+
443
+ def _kv_per_token(profile: ModelProfile, kv_types: tuple[str, str]) -> int:
444
+ """KV bytes one more token costs in the full-attention layers."""
445
+ full = replace(profile, layers=[(k, b) for k, b in profile.layers if k == LayerKind.FULL])
446
+ return estimator.kv_pool_bytes(full, 1 << 20, kv_types) >> 20
447
+
448
+
449
+ def _machine_doc(machine: Machine) -> dict[str, Any]:
450
+ if machine.unified is not None:
451
+ return {
452
+ "kind": "unified",
453
+ "unified_bytes": machine.unified,
454
+ "working_set_bytes": machine.working_set or metal.default_working_set(machine.unified),
455
+ "macos_reserve_bytes": metal.in_use(machine.unified),
456
+ "stack_keep_bytes": metal.HOST_KEEP_BYTES,
457
+ }
458
+ if machine.vram is not None:
459
+ doc: dict[str, Any] = {
460
+ "kind": "discrete",
461
+ "vram_bytes": machine.vram,
462
+ "vram_used_bytes": machine.vram_used,
463
+ }
464
+ if machine.ram is not None:
465
+ doc["ram_bytes"] = machine.ram
466
+ doc["ram_floor_bytes"] = RAM_FLOOR
467
+ return doc
468
+ return {"kind": "none"}
469
+
470
+
471
+ # ── text ───────────────────────────────────────────────────────────────
472
+
473
+
474
+ def _g(n: float) -> str:
475
+ return f"{n / GIB:.2f}"
476
+
477
+
478
+ def _tokens(n: int) -> str:
479
+ return f"{n // 1024}K" if n >= 1024 and n % 1024 == 0 else f"{n:,}"
480
+
481
+
482
+ def render(data: Mapping[str, Any]) -> str:
483
+ m, posture = data["model"], data["posture"]
484
+ layers = m["layers"]
485
+ split = [f"{layers['full_attention']} full attention"]
486
+ if layers["window"]:
487
+ split.append(f"{layers['window']} window ({m['window_size']:,} tokens)")
488
+ if layers["recurrent"]:
489
+ split.append(f"{layers['recurrent']} recurrent")
490
+ kv = "/".join(posture["kv_types"])
491
+ pool = (
492
+ f"-c T -np {posture['slots']} --kv-unified"
493
+ if posture["pool"] == "shared"
494
+ else f"-c {posture['slots']}xT -np {posture['slots']}"
495
+ )
496
+ lines = [
497
+ f"{m['name']} {m['quant']} ("
498
+ + ", ".join(x for x in (m["architecture"], "MoE" if m["moe"] else "", m["source"]) if x)
499
+ + ")",
500
+ f"layers: {', '.join(split)}; KV {m['kv_bytes_per_token'] / 1024:.1f} KiB/token at {kv}"
501
+ + (
502
+ f"; context limit {m['train_context']:,} ({m['context_source']})"
503
+ if m["train_context"]
504
+ else ""
505
+ ),
506
+ f"weights {_g(m['weights_bytes'])} GiB ({m['weights_source']})",
507
+ f"posture: llama.cpp {posture['backend']}, {pool}, ubatch {posture['ubatch']}, "
508
+ f"vision {posture['vision']}" + (", MTP" if posture["mtp"] else ""),
509
+ "",
510
+ ]
511
+ cols = ["weights", "kv", "state", "compute", "process", "vision"]
512
+ budgeted = "device_budget" in data
513
+ head = (
514
+ [f"{'context':>8}"]
515
+ + [f"{c:>8}" for c in cols]
516
+ + [f"{'device':>8}", f"{'host':>8}"]
517
+ + ([f"{'fits':>5}", f"{'slots':>5}"] if budgeted else [])
518
+ )
519
+ lines.append(" ".join(head) + " (GiB; fits: card and host; slots: each owning T)")
520
+ for row in data["rows"]:
521
+ d = row["device"]
522
+ cells = [f"{_tokens(row['context']):>8}"]
523
+ cells += [f"{_g(d[c] + (d['draft'] if c == 'compute' else 0)):>8}" for c in cols]
524
+ cells += [f"{_g(d['total']):>8}", f"{_g(row['host']['total']):>8}"]
525
+ if budgeted:
526
+ cells += [f"{'yes' if row['fits'] else 'no':>5}", f"{row['max_slots']:>5}"]
527
+ mark = " beyond the context limit" if row.get("beyond_train_context") else ""
528
+ mark += " host RAM short" if row.get("host_fits") is False else ""
529
+ lines.append(" ".join(cells) + mark)
530
+ if budgeted:
531
+ lines.append("")
532
+ lines.append(f"device budget {_g(data['device_budget'])} GiB: {data['budget_rule']}")
533
+ if "host_room" in data:
534
+ lines.append(f"host RAM room {_g(data['host_room'])} GiB (RAM less the 4 GiB floor)")
535
+ best, limit = data["max_context"], m["train_context"]
536
+ beyond = f", beyond the {limit:,}-token context limit" if limit and best > limit else ""
537
+ shared = posture["pool"] == "shared"
538
+ what = (
539
+ f"longest shared pool (-c, all {posture['slots']} slots together)"
540
+ if shared
541
+ else "longest context per slot"
542
+ )
543
+ lines.append(f"{what}: {best:,} tokens{beyond}" if best else "does not fit at any context")
544
+ names = {
545
+ "embedding": "embedding table",
546
+ "process": "llama-server process",
547
+ "checkpoints": "context checkpoints",
548
+ "prompt_cache": f"prompt cache (--cache-ram {posture['prompt_cache_bytes'] >> 20} MiB)",
549
+ "vision": "picture reader",
550
+ }
551
+ host = data["rows"][0]["host"] if data["rows"] else {}
552
+ lines.append("host: " + ", ".join(n for k, n in names.items() if host.get(k)))
553
+ for note in data["notes"]:
554
+ lines.append(f"note: {note}")
555
+ lines.append("Estimates, not measurements.")
556
+ return "\n".join(lines)
557
+
558
+
559
+ # ── command line ───────────────────────────────────────────────────────
560
+
561
+ HELP = (
562
+ "Read-only: the VRAM and host RAM one LLM would take under the stack's llama.cpp posture, "
563
+ "split into weights, KV cache, recurrent state, compute buffer, process, projector, and the "
564
+ "host side (embedding table, process, context checkpoints, prompt cache). Probes nothing: "
565
+ "give the card (--vram) or the Mac (--unified-memory) to get fits, the longest context per "
566
+ "slot and how many slots of each context fit. MODEL is a catalog id or an HF GGUF repo "
567
+ "owner/name[:QUANT] as for `stack plan --llm`, or a local .gguf, config.json or directory, "
568
+ "or a safetensors repo id as for `memcalc`. Prices match `stack plan`; all are estimates."
569
+ )
570
+ EXAMPLES = [
571
+ ("%(prog)s qwen3.8-27b --vram 24GiB --ram 64GiB", "the 24GB tier"),
572
+ ("%(prog)s qwen3.6-35b-a3b --context 128k --slots 4 --pool split --json", "4 full slots"),
573
+ ("%(prog)s qwen3.8-27b-iq3s --unified-memory 24GiB --kv q4_0", "a 24 GB Mac"),
574
+ ("%(prog)s unsloth/gemma-3-27b-it-GGUF:Q4_K_M --vram 24GiB", "an HF GGUF repo"),
575
+ ("%(prog)s ./config.json --params 8B --quant Q4_K_M --vram 16GiB", "any config.json"),
576
+ ]
577
+
578
+
579
+ def add_parser(actions: Any) -> None:
580
+ p = actions.add_parser(
581
+ "memory", help="VRAM and RAM one LLM would take, from a few inputs (read-only)"
582
+ )
583
+ p.add_argument("model", metavar="MODEL", help="catalog id, owner/name[:QUANT], or a file")
584
+ what = p.add_argument_group("model")
585
+ what.add_argument("--quant", metavar="Q", help="catalog variant, or bits for --params")
586
+ what.add_argument("--params", metavar="N", help="parameter count such as 27B (config.json)")
587
+ what.add_argument(
588
+ "--weights", metavar="SIZE", help="weight bytes of a .gguf or config.json model"
589
+ )
590
+ launch = p.add_argument_group("launch posture (stack plan's defaults)")
591
+ launch.add_argument(
592
+ "--context",
593
+ default="",
594
+ metavar="LIST",
595
+ help="per-slot tokens, comma-separated: 64k,128k,262144 or max (default 64k,128k,256k)",
596
+ )
597
+ launch.add_argument("--slots", type=int, default=AGENT.slots, help="-np (default 2)")
598
+ launch.add_argument(
599
+ "--pool",
600
+ choices=("shared", "split"),
601
+ default="shared",
602
+ help="shared: one --kv-unified pool of T tokens (the stack's); split: -c slots x T",
603
+ )
604
+ launch.add_argument(
605
+ "--kv", default="q8_0/q8_0", metavar="K/V", help="f16, q8_0 or q4_0 (default q8_0/q8_0)"
606
+ )
607
+ launch.add_argument("--ubatch", type=int, default=AGENT.ubatch, help="-ub (default 512)")
608
+ launch.add_argument("--mtp", action="store_true", help="price MTP speculation's draft context")
609
+ launch.add_argument(
610
+ "--vision",
611
+ choices=vision.READERS,
612
+ default=vision.DEFAULT,
613
+ help="projector placement (default auto: GPU on cards of 23.5 GiB and up unless it "
614
+ "shortens the context asked for, and on a Mac)",
615
+ )
616
+ launch.add_argument(
617
+ "--prompt-cache",
618
+ type=int,
619
+ default=None,
620
+ metavar="MIB",
621
+ help="--cache-ram (default: the floor the stack guarantees, 2048 on a card and up to that "
622
+ "on a Mac; it grows to 8192 from spare RAM; 0 off)",
623
+ )
624
+ where = p.add_argument_group("machine (optional; adds fits, longest context, slots)")
625
+ kind = where.add_mutually_exclusive_group()
626
+ kind.add_argument("--vram", metavar="SIZE", help="the card's total memory, e.g. 24GiB")
627
+ kind.add_argument("--unified-memory", metavar="SIZE", help="a Mac's memory, e.g. 64GiB")
628
+ where.add_argument("--vram-used", metavar="SIZE", help="memory others hold on the card")
629
+ where.add_argument(
630
+ "--ram", metavar="SIZE", help="host RAM beside the card; fits then needs RAM too"
631
+ )
632
+ where.add_argument("--working-set", metavar="SIZE", help="Mac GPU limit after sysctl")
633
+ p.add_argument(
634
+ "--endpoint",
635
+ default=os.environ.get("HF_ENDPOINT", "https://huggingface.co"),
636
+ help="Hub base URL for repo ids (default $HF_ENDPOINT or huggingface.co)",
637
+ )
638
+ p.add_argument("--json", action="store_true", help="print localmodels.stack-memory/v1 JSON")
639
+ cli_help.document(
640
+ p,
641
+ HELP,
642
+ examples=EXAMPLES,
643
+ sections=[
644
+ ("output", f"a table, or {SCHEMA} with --json (bytes, per context row)"),
645
+ ("exit status", "0 printed · 2 bad input or unknown model (message on stderr)"),
646
+ ],
647
+ )
648
+
649
+
650
+ def _kv_types(text: str) -> tuple[str, str]:
651
+ names = [t.strip().lower() for t in text.replace(",", "/").split("/")]
652
+ if len(names) == 1:
653
+ names *= 2
654
+ if len(names) != 2 or any(n not in KV_TYPES for n in names):
655
+ raise MemcalcError(f"--kv {text!r}: use one of {', '.join(KV_TYPES)}, or K/V")
656
+ return names[0], names[1]
657
+
658
+
659
+ def _contexts(text: str, train: int) -> list[int]:
660
+ if not text:
661
+ picked = [c for c in DEFAULT_CONTEXTS if not train or c <= train]
662
+ return picked or [train]
663
+ out = []
664
+ for item in (c.strip() for c in text.split(",")):
665
+ if item.lower() == "max":
666
+ if not train:
667
+ raise MemcalcError("--context max: the model declares no training context")
668
+ out.append(train)
669
+ elif item:
670
+ out.append(parse_tokens(item))
671
+ if not out or any(c <= 0 for c in out):
672
+ raise MemcalcError(f"--context {text!r}: give positive lengths such as 64k,128k")
673
+ return out
674
+
675
+
676
+ def _size(text: str | None) -> int | None:
677
+ return parse_size(text) if text else None
678
+
679
+
680
+ def cli(args: argparse.Namespace) -> int:
681
+ try:
682
+ cache = args.prompt_cache
683
+ if args.slots < 1 or args.ubatch < 1 or (cache is not None and cache < 0):
684
+ raise MemcalcError("--slots and --ubatch must be at least 1, --prompt-cache 0 or more")
685
+ subject = resolve(
686
+ args.model,
687
+ quant=args.quant,
688
+ params=args.params,
689
+ weights=args.weights,
690
+ endpoint=args.endpoint,
691
+ )
692
+ posture = Posture(
693
+ kv_types=_kv_types(args.kv),
694
+ slots=args.slots,
695
+ shared=args.pool == "shared",
696
+ ubatch=args.ubatch,
697
+ mtp=args.mtp,
698
+ vision=args.vision,
699
+ prompt_cache=None if cache is None else cache * MIB,
700
+ )
701
+ machine = Machine(
702
+ vram=_size(args.vram),
703
+ vram_used=_size(args.vram_used) or 0,
704
+ ram=_size(args.ram),
705
+ unified=_size(args.unified_memory),
706
+ working_set=_size(args.working_set),
707
+ )
708
+ if machine.working_set and not machine.metal:
709
+ raise MemcalcError("--working-set applies to --unified-memory only")
710
+ data = report(
711
+ subject, posture, machine, _contexts(args.context, subject.profile.n_ctx_train)
712
+ )
713
+ except (MemcalcError, PlanError, OSError, ValueError) as exc:
714
+ print(f"stack memory: {exc}", file=sys.stderr)
715
+ return 2
716
+ if args.json:
717
+ json.dump(data, sys.stdout, ensure_ascii=False, indent=1)
718
+ sys.stdout.write("\n")
719
+ else:
720
+ print(render(data))
721
+ return 0