@simplexai/localmodels-win32-x64 0.1.0-dev.100 → 0.1.0-dev.102

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 (33) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +31 -29
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +35 -7
  5. package/modules/localmodels/auth_proxy.py +337 -14
  6. package/modules/localmodels/catalog.json +16 -10
  7. package/modules/localmodels/engine_adapters/suite_plan.py +4 -2
  8. package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +94 -0
  9. package/modules/localmodels/guard-requirements.in +3 -0
  10. package/modules/localmodels/guard-requirements.lock +4 -4
  11. package/modules/localmodels/guard.py +2 -2
  12. package/modules/localmodels/program_scheduler.py +1198 -0
  13. package/modules/localmodels/slot_cache.py +71 -5
  14. package/modules/localmodels/speech_jobs.py +2 -0
  15. package/modules/localmodels/speech_workers.py +62 -10
  16. package/modules/localmodels/stack_capacity.py +37 -1
  17. package/modules/localmodels/stack_cli.py +1 -0
  18. package/modules/localmodels/stack_hardware.py +18 -16
  19. package/modules/localmodels/stack_plan.py +21 -0
  20. package/modules/localmodels/stack_progress.py +15 -0
  21. package/modules/localmodels/stack_run.py +25 -2
  22. package/modules/localmodels/stack_suite.py +54 -12
  23. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.6.txt → strata-poly-serve-0.2.20-poly.7.txt} +1 -1
  24. package/modules/localmodels/suite.py +10 -1
  25. package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev102.dist-info}/METADATA +1 -1
  26. package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev102.dist-info}/RECORD +28 -26
  27. package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev102.dist-info}/licenses/NOTICE +1 -1
  28. package/package.json +1 -1
  29. package/tool.json +1 -1
  30. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +0 -94
  31. /package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev102.dist-info}/WHEEL +0 -0
  32. /package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev102.dist-info}/entry_points.txt +0 -0
  33. /package/modules/{simplex_localmodels-0.1.0.dev100.dist-info → simplex_localmodels-0.1.0.dev102.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -363,13 +363,59 @@ def count(body: bytes, slot_dir: Path, tally: Tally) -> None:
363
363
  log("a new prompt prefix leads the traffic; prefix.json rewritten")
364
364
 
365
365
 
366
+ def _int_flag(cmd: list[str], *names: str, minimum: int = 1) -> int | None:
367
+ for name in names:
368
+ raw = flag(cmd, name)
369
+ if raw is None:
370
+ continue
371
+ try:
372
+ value = int(raw)
373
+ except ValueError:
374
+ continue
375
+ if value >= minimum:
376
+ return value
377
+ return None
378
+
379
+
380
+ def _program_defaults(cmd: list[str]) -> dict[str, Any]:
381
+ """Derive default scheduler geometry hints from wrapped llama-server flags."""
382
+ defaults: dict[str, Any] = {}
383
+ window = _int_flag(cmd, "-c", "--ctx-size", minimum=1)
384
+ if window is not None:
385
+ defaults["window_tokens"] = window
386
+ slots = _int_flag(cmd, "-np", "--parallel", minimum=1)
387
+ if slots is not None:
388
+ defaults["slots"] = slots
389
+ kv_k = flag(cmd, "-ctk") or flag(cmd, "--cache-type-k")
390
+ if kv_k and kv_k.lower() in ("f16", "q8_0", "q4_0"):
391
+ defaults["kv_k"] = kv_k.lower()
392
+ kv_v = flag(cmd, "-ctv") or flag(cmd, "--cache-type-v")
393
+ if kv_v and kv_v.lower() in ("f16", "q8_0", "q4_0"):
394
+ defaults["kv_v"] = kv_v.lower()
395
+ cache_ram = _int_flag(cmd, "-cram", "--cache-ram", minimum=0)
396
+ if cache_ram is not None:
397
+ defaults["prompt_cache_mib"] = cache_ram
398
+ return defaults
399
+
400
+
366
401
  def handler(
367
- upstream: int, slot_dir: Path, tally: Tally, key: str
402
+ upstream: int,
403
+ slot_dir: Path,
404
+ tally: Tally,
405
+ key: str,
406
+ *,
407
+ scheduler: Any = None,
368
408
  ) -> type[http.server.BaseHTTPRequestHandler]:
369
409
  """auth_proxy's forwarding, with no key check of its own: llama-server checks the caller's
370
410
  key as before (and leaves /health open). A chat request's body is counted on the way when it
371
411
  carries that key: a caller the server will refuse has no say in which prefix is kept."""
372
- forward: Any = auth_proxy.handler(None, upstream, pass_auth=True)
412
+ forward: Any = auth_proxy.handler(
413
+ None,
414
+ upstream,
415
+ pass_auth=True,
416
+ scheduler=scheduler,
417
+ control_auth_key=key or None,
418
+ )
373
419
  bearer = ("Bearer " + key).encode()
374
420
 
375
421
  class Counting(forward): # type: ignore[misc]
@@ -404,7 +450,15 @@ def end_with_me(server_pid: int) -> subprocess.Popen[bytes] | None:
404
450
 
405
451
 
406
452
  def main(argv: list[str]) -> int:
407
- cmd = argv
453
+ parsed = auth_proxy.parse_program_flags(argv)
454
+ if parsed is None:
455
+ print(
456
+ "usage: slot_cache.py [--program-aware ...] LLAMA_SERVER [ARG...] "
457
+ "(with --port, --api-key-file and --slot-save-path)",
458
+ file=sys.stderr,
459
+ )
460
+ return 2
461
+ program_overrides, cmd = parsed
408
462
  host, port = flag(cmd, "--host") or "127.0.0.1", flag(cmd, "--port")
409
463
  key_file, slots = flag(cmd, "--api-key-file"), flag(cmd, "--slot-save-path")
410
464
  if not cmd or port is None or key_file is None or slots is None:
@@ -414,6 +468,13 @@ def main(argv: list[str]) -> int:
414
468
  file=sys.stderr,
415
469
  )
416
470
  return 2
471
+ try:
472
+ scheduler = auth_proxy.build_program_scheduler(
473
+ program_overrides, defaults=_program_defaults(cmd)
474
+ )
475
+ except (ImportError, ValueError) as exc:
476
+ print(f"slot_cache: program-aware scheduler error: {exc}", file=sys.stderr)
477
+ return 2
417
478
  os.umask(0o077) # the prefix, the tally and the saved slots hold prompt text
418
479
  with open(key_file, encoding="utf-8") as f:
419
480
  key = f.read().strip()
@@ -424,8 +485,9 @@ def main(argv: list[str]) -> int:
424
485
  tally = Tally(slot_dir)
425
486
  if not (slot_dir / PREFIX_FILE).exists():
426
487
  tally.kept = None # write the leading prefix again
427
- proxy = auth_proxy.bind_server((host, int(port)), handler(upstream, slot_dir, tally, key))
428
- proxy.daemon_threads = True
488
+ proxy = auth_proxy.bind_server(
489
+ (host, int(port)), handler(upstream, slot_dir, tally, key, scheduler=scheduler)
490
+ )
429
491
  child = subprocess.Popen(inner)
430
492
  guard = end_with_me(child.pid)
431
493
 
@@ -446,9 +508,13 @@ def main(argv: list[str]) -> int:
446
508
  args=(Server(upstream, key), slot_dir, cmd, tally, child),
447
509
  daemon=True,
448
510
  ).start()
511
+ if scheduler is not None:
512
+ scheduler.start()
449
513
  try:
450
514
  proxy.serve_forever()
451
515
  finally:
516
+ if scheduler is not None:
517
+ scheduler.stop()
452
518
  proxy.server_close()
453
519
  if child.poll() is None:
454
520
  child.terminate()
@@ -340,6 +340,8 @@ def _select_whisper_engine(
340
340
  elif host.get("gpu_vendor_class") in ("amd", "intel"):
341
341
  backends.append("vulkan")
342
342
  backends.append("cpu")
343
+ if not include_gpu_engine and host.get("platform") == "darwin" and host.get("arch") == "arm64":
344
+ backends.append("metal")
343
345
 
344
346
  for backend in backends:
345
347
  try:
@@ -11,6 +11,7 @@ import re
11
11
  import subprocess
12
12
  import sys
13
13
  import time
14
+ import unicodedata
14
15
  import urllib.error
15
16
  import urllib.parse
16
17
  import urllib.request
@@ -41,6 +42,13 @@ from localmodels.speech_model import EffectiveDevice, SpeechError
41
42
  SENSEVOICE_REQUIREMENTS = "speech-sv.txt"
42
43
  # Simplified-Chinese prompt injected ONLY when language == "zh" and speech is present.
43
44
  ZH_SIMPLIFIED_PROMPT = "\u4ee5\u4e0b\u662f\u666e\u901a\u8bdd\u7684\u53e5\u5b50\u3002"
45
+ # whisper.cpp keeps at most max_context text tokens before the audio, the initial prompt included;
46
+ # 0 (the anti-loop default) silently drops the prompt, so zh speech allows a small window for
47
+ # ZH_SIMPLIFIED_PROMPT while silence and all non-zh requests keep 0.
48
+ WHISPER_ZH_PROMPT_MAX_CONTEXT = "64"
49
+ _ZH_PROMPT_LEAD_RE = re.compile(rf"^(?:\s*{re.escape(ZH_SIMPLIFIED_PROMPT)})+\s*")
50
+ _ZH_PROMPT_TRAIL_RE = re.compile(rf"\s*(?:{re.escape(ZH_SIMPLIFIED_PROMPT)}\s*)+$")
51
+ _LINE_BREAK_RE = re.compile(r"\s*\n\s*")
44
52
  SILENCE_RMS_THRESHOLD = 150.0 # int16 RMS noise floor (~-46.8 dBFS)
45
53
  WORKER_STOP_GRACE_S = 3.0 # whisper-server b5454 hangs on SIGTERM -> SIGKILL after 3s
46
54
  WORKER_READY_TIMEOUT_S = 60.0
@@ -564,11 +572,12 @@ def resolve_whisper_binary(
564
572
  if spec.engine_tag:
565
573
  lock_path = engines.engine_lock_path(spec.engine_tag)
566
574
  if lock_path.is_file():
567
- backends = (
568
- [decision.effective_device, "cpu"]
569
- if decision.effective_device != "cpu"
570
- else ["cpu"]
571
- )
575
+ if decision.effective_device != "cpu":
576
+ backends = [decision.effective_device, "cpu"]
577
+ elif sys.platform == "darwin":
578
+ backends = ["cpu", "metal"]
579
+ else:
580
+ backends = ["cpu"]
572
581
  for backend in backends:
573
582
  eng_dir_path = (
574
583
  Path(os.path.expanduser(base_dir)) / "engines" / f"{spec.engine_tag}-{backend}"
@@ -736,17 +745,52 @@ def spawn_real_worker(
736
745
  return _launch_worker_process(spec, decision, argv, env, port, state_dir)
737
746
 
738
747
 
748
+ def _unspaced(character: str) -> bool:
749
+ # Wide and full-width characters (ideographs, kana, full-width punctuation) are written
750
+ # without spaces between them.
751
+ return unicodedata.east_asian_width(character) in ("W", "F")
752
+
753
+
754
+ def single_line(text: str) -> str:
755
+ """Join the lines whisper-server returns (one per segment) as the text is written: a space
756
+ between words, none between characters of a script written without spaces."""
757
+
758
+ def join(match: re.Match[str]) -> str:
759
+ before = text[match.start() - 1] if match.start() > 0 else ""
760
+ after = text[match.end()] if match.end() < len(text) else ""
761
+ if not before or not after or _unspaced(before) or _unspaced(after):
762
+ return ""
763
+ return " "
764
+
765
+ return _LINE_BREAK_RE.sub(join, text).strip()
766
+
767
+
768
+ def strip_zh_prompt_echo(text: str) -> str:
769
+ """Strip verbatim leading or trailing echoes of ``ZH_SIMPLIFIED_PROMPT``."""
770
+ cleaned = _ZH_PROMPT_LEAD_RE.sub("", text)
771
+ cleaned = _ZH_PROMPT_TRAIL_RE.sub("", cleaned)
772
+ return cleaned.strip()
773
+
774
+
775
+ def _clean_whisper_text(raw: str, *, strip_zh_echo: bool) -> str:
776
+ cleaned = single_line(raw)
777
+ return strip_zh_prompt_echo(cleaned) if strip_zh_echo else cleaned
778
+
779
+
739
780
  def _normalize_segments(
740
781
  raw_segments: object,
741
782
  text: str,
742
783
  duration: float,
784
+ *,
785
+ normalize_text: Callable[[str], str] | None = None,
743
786
  ) -> list[dict[str, object]]:
744
787
  segments: list[dict[str, object]] = []
745
788
  if isinstance(raw_segments, list):
746
789
  for seg in raw_segments:
747
790
  if not isinstance(seg, dict):
748
791
  continue
749
- seg_text = str(seg.get("text") or "").strip()
792
+ raw_seg = str(seg.get("text") or "")
793
+ seg_text = normalize_text(raw_seg) if normalize_text is not None else raw_seg.strip()
750
794
  if not seg_text:
751
795
  continue
752
796
  try:
@@ -802,6 +846,9 @@ def call_whisper_worker(
802
846
  response_format: str,
803
847
  ) -> dict[str, object]:
804
848
  """Forward a WAV transcription to ``whisper-server`` with hallucination & zh prompt guards."""
849
+ use_zh_prompt = (
850
+ language == "zh" or language.startswith("zh-")
851
+ ) and rms >= SILENCE_RMS_THRESHOLD
805
852
  fields: list[tuple[str, str]] = [
806
853
  ("response_format", "verbose_json"),
807
854
  ("language", language),
@@ -810,19 +857,24 @@ def call_whisper_worker(
810
857
  ("entropy_thold", "2.4"),
811
858
  ("logprob_thold", "-1.0"),
812
859
  ("suppress_nst", "true"),
813
- ("max_context", "0"),
860
+ ("max_context", WHISPER_ZH_PROMPT_MAX_CONTEXT if use_zh_prompt else "0"),
814
861
  ]
815
- if (language == "zh" or language.startswith("zh-")) and rms >= SILENCE_RMS_THRESHOLD:
862
+ if use_zh_prompt:
816
863
  fields.append(("prompt", ZH_SIMPLIFIED_PROMPT))
817
864
  body, content_type = build_multipart_body(fields, "audio.wav", wav_data)
818
865
  url = f"http://127.0.0.1:{worker.port}/v1/audio/transcriptions"
819
866
  parsed = _post_worker(url, body, content_type, worker)
820
- text = str(parsed.get("text") or "").strip()
867
+ text = _clean_whisper_text(str(parsed.get("text") or ""), strip_zh_echo=use_zh_prompt)
821
868
  detected = normalize_whisper_language(str(parsed.get("language") or ""))
822
869
  lang_out = detected or ("" if language == "auto" else language)
823
870
  dur_raw = parsed.get("duration")
824
871
  dur_out = round(float(dur_raw), 3) if isinstance(dur_raw, int | float) else round(duration, 3)
825
- segments = _normalize_segments(parsed.get("segments"), text, dur_out)
872
+ segments = _normalize_segments(
873
+ parsed.get("segments"),
874
+ text,
875
+ dur_out,
876
+ normalize_text=lambda seg: _clean_whisper_text(seg, strip_zh_echo=use_zh_prompt),
877
+ )
826
878
  _ = response_format
827
879
  return {"text": text, "language": lang_out, "duration": dur_out, "segments": segments}
828
880
 
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
  from dataclasses import replace
11
11
 
12
12
  from localmodels import catalog as cat
13
- from localmodels import component, context_policy, gpu_specs, llm_rank, metal
13
+ from localmodels import component, context_policy, gpu_specs, llm_rank, metal, suite
14
14
  from localmodels.context_policy import AGENT, AgentPosture, cache_floor_bytes, posture_for
15
15
  from localmodels.deploy import DEFAULT_BASE_DIR
16
16
  from localmodels.engine_adapters import llama_cpp
@@ -23,6 +23,7 @@ from localmodels.estimator import (
23
23
  from localmodels.plan_envelope import PlanError
24
24
  from localmodels.planning.budget import gib
25
25
  from localmodels.probe import GPU, HostFacts
26
+ from localmodels.records import Plan
26
27
  from localmodels.stack_plan import CapacityFit, Hardware, StackOptions
27
28
 
28
29
  WDDM_NOTE = (
@@ -48,6 +49,41 @@ def decision_reserve(card_budget_bytes: int, options: StackOptions) -> int:
48
49
  return min(fitting) if fitting else 0
49
50
 
50
51
 
52
+ def start_floor(part: Plan) -> int:
53
+ """The least free VRAM a part's engine starts in, 0 when its recipe sets none. A PolyStrata
54
+ expert cache shrinks to what is free above ``launch.min_vram_free_bytes``, so its
55
+ ``vram_bytes`` is a ceiling. A plan saved before plans carried the floor takes the catalog
56
+ recipe's by model id."""
57
+ launch = part["launch"]
58
+ if "min_vram_free_bytes" in launch:
59
+ return int(str(launch["min_vram_free_bytes"]))
60
+ try:
61
+ recipe = suite.recipe(part["model"].get("id", ""))
62
+ except PlanError:
63
+ return 0
64
+ return suite.gpu_bytes(recipe, str(launch.get("vision", "off")))[1]
65
+
66
+
67
+ def start_need(vram_bytes: int, floor: int, card: GPU, options: StackOptions | None) -> int:
68
+ """Free VRAM a GPU part needs on ``card`` to start: the one measure for planning a shared
69
+ Strata card, every recipe (stack_suite), the check before ``stack apply`` starts a part and
70
+ ``stack up``.
71
+ ``options`` adds the smallest decision model kept beside the LLM (``stack apply``'s LLM and
72
+ planning); ``stack up`` starts each part on its own and passes None.
73
+
74
+ With a floor (``start_floor``): the floor, the decision reserve and VRAM_MARGIN. The engine's
75
+ own ``--vram-reserve-mib`` already keeps the display and its overshoot out of the expert
76
+ cache, so the 1 GiB agent reserve is not added again. Without one, ``vram_bytes`` with the
77
+ agent reserve (``stack apply``) or VRAM_MARGIN (``stack up``), as before."""
78
+ reserve = (
79
+ decision_reserve(component.auto_budget(card["total_bytes"]), options) if options else 0
80
+ )
81
+ if floor > 0:
82
+ return floor + reserve + component.VRAM_MARGIN
83
+ margin = AGENT_VRAM_RESERVE_BYTES if options is not None else component.VRAM_MARGIN
84
+ return vram_bytes + margin + reserve
85
+
86
+
51
87
  def device(facts: HostFacts, index: int) -> GPU:
52
88
  """Card ``index`` of ``cards``: an NVIDIA card, or a Mac's Metal GPU."""
53
89
  found = metal.device(facts)
@@ -144,6 +144,7 @@ def apply_cli(
144
144
  plan_id=plan_id,
145
145
  attempt_id=attempt_ids[-1] if attempt_ids else None,
146
146
  cause=stack_run.cause_of(exc, started=bool(attempt_ids)),
147
+ counts=stack_run.cause_counts(exc),
147
148
  )
148
149
 
149
150
  def emit_progress(event: stack_events.ProgressEvent) -> None:
@@ -10,7 +10,6 @@ from typing import Any, cast
10
10
  from localmodels import catalog as cat
11
11
  from localmodels import (
12
12
  catalog_recipes,
13
- component,
14
13
  gpu_specs,
15
14
  llm_rank,
16
15
  metal,
@@ -20,7 +19,6 @@ from localmodels import (
20
19
  suite,
21
20
  )
22
21
  from localmodels.context_policy import AgentPosture, posture_for
23
- from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
24
22
  from localmodels.planning.budget import (
25
23
  gib,
26
24
  holders,
@@ -33,6 +31,8 @@ from localmodels.records import Plan
33
31
  from localmodels.stack_capacity import decision_reserve as decision_reserve
34
32
  from localmodels.stack_capacity import device as device
35
33
  from localmodels.stack_capacity import llm_budget as llm_budget
34
+ from localmodels.stack_capacity import start_floor as start_floor
35
+ from localmodels.stack_capacity import start_need as start_need
36
36
  from localmodels.stack_picks import picks
37
37
  from localmodels.stack_plan import (
38
38
  Card,
@@ -41,6 +41,7 @@ from localmodels.stack_plan import (
41
41
  LlmFit,
42
42
  StackError,
43
43
  StackOptions,
44
+ VramShortError,
44
45
  default_options,
45
46
  platform_error,
46
47
  )
@@ -181,7 +182,8 @@ def check_shared_start(
181
182
  part: Plan, facts: HostFacts, *, options: StackOptions | None = None
182
183
  ) -> None:
183
184
  """Recheck free VRAM before starting. Shared or not, an unknown owner of other GPU work no
184
- longer refuses (roadmap decision 60): the card's free memory, less the margins, decides."""
185
+ longer refuses (roadmap decision 60): the card's free memory against ``start_need`` decides;
186
+ too little raises VramShortError (STACK_VRAM_INSUFFICIENT)."""
185
187
  from localmodels import hosts, stack_lifecycle
186
188
 
187
189
  for record in hosts.records("local"):
@@ -198,24 +200,24 @@ def check_shared_start(
198
200
  and rows[0]["health"] in ("ok", "ready")
199
201
  ):
200
202
  return # The verified healthy backend is already resident; no new allocation.
201
- needed = int(str(part["launch"].get("vram_bytes") or 0))
203
+ vram = int(str(part["launch"].get("vram_bytes") or 0))
204
+ floor = start_floor(part)
202
205
  assigned = cast(list[dict[str, Any]], part["placement"].get("gpus") or [])
203
- if needed <= 0 or not assigned:
206
+ if vram <= 0 or not assigned:
204
207
  raise StackError("the GPU-sharing model has no VRAM budget or no approved GPU placement")
205
208
  for target in assigned:
206
209
  card = next((g for g in facts.get("gpus") or [] if g["uuid"] == target["uuid"]), None)
207
- reserve = (
208
- decision_reserve(component.auto_budget(card["total_bytes"]), options)
209
- if card and options
210
- else 0
211
- )
212
- margin = AGENT_VRAM_RESERVE_BYTES if options is not None else component.VRAM_MARGIN
213
- if card is None or card["free_bytes"] < needed + margin + reserve:
214
- free = gib(card["free_bytes"]) if card else "no such card"
210
+ if card is None:
215
211
  raise StackError(
216
- f"free VRAM too low for the approved shared model ({free} free, "
217
- f"{gib(needed + margin + reserve)} needed); close programs that use the GPU "
218
- "and retry"
212
+ "the approved GPU of the model is not on this computer now; plan again"
213
+ )
214
+ needed = start_need(vram, floor, card, options)
215
+ if card["free_bytes"] < needed:
216
+ raise VramShortError(
217
+ f"free VRAM too low for the approved model ({gib(card['free_bytes'])} free, "
218
+ f"{gib(needed)} needed); close programs that use the GPU and retry",
219
+ free_bytes=card["free_bytes"],
220
+ required_bytes=needed,
219
221
  )
220
222
 
221
223
 
@@ -130,8 +130,29 @@ class StackReplanError(StackGuardError, PlanError):
130
130
  """A guarded rebuild still satisfies the existing PlanError catch contract."""
131
131
 
132
132
 
133
+ class VramShortError(StackGuardError):
134
+ """Too little free VRAM to start an approved GPU part; carries only the two byte counts."""
135
+
136
+ def __init__(self, message: str, *, free_bytes: int, required_bytes: int) -> None:
137
+ super().__init__(
138
+ message,
139
+ cause_code="STACK_VRAM_INSUFFICIENT",
140
+ public_message="free VRAM is too low to start the model; close programs that use "
141
+ "the GPU and retry",
142
+ )
143
+ self.free_bytes = free_bytes
144
+ self.required_bytes = required_bytes
145
+
146
+
133
147
  def guard_details(exc: BaseException) -> dict[str, object]:
134
148
  """Project only typed guard metadata; the lower event layer validates its values."""
149
+ if isinstance(exc, VramShortError):
150
+ return {
151
+ "causeCode": exc.cause_code,
152
+ "changedFields": exc.changed_fields,
153
+ "freeBytes": exc.free_bytes,
154
+ "requiredBytes": exc.required_bytes,
155
+ }
135
156
  if isinstance(exc, StackGuardError):
136
157
  return {"causeCode": exc.cause_code, "changedFields": exc.changed_fields}
137
158
  return {}
@@ -18,6 +18,16 @@ __all__ = ["JsonlObserver", "ProgressObserver", "PublicProgress", "forward", "re
18
18
 
19
19
  # Shared section names; approval.py continues to own the authorization checks.
20
20
  ERROR_PLAN_FIELDS = frozenset(STACK_PLAN_SECTIONS)
21
+ _MAX_SAFE_INT = (1 << 53) - 1 # JavaScript's safe integer range
22
+
23
+
24
+ def byte_counts(metadata: Mapping[str, object]) -> dict[str, int]:
25
+ """``freeBytes`` and ``requiredBytes`` of a STACK_VRAM_INSUFFICIENT guard, only when both
26
+ are plain non-negative integers in JavaScript's safe range; else none."""
27
+ counts = {key: metadata.get(key) for key in ("freeBytes", "requiredBytes")}
28
+ if all(type(v) is int and 0 <= v <= _MAX_SAFE_INT for v in counts.values()):
29
+ return {key: int(str(v)) for key, v in counts.items()}
30
+ return {}
21
31
 
22
32
 
23
33
  class JsonlObserver:
@@ -84,11 +94,13 @@ def error(code: int, details: Mapping[str, object] | None = None) -> int:
84
94
  cause = "STACK_APPLY_INTERRUPTED" if code == 130 else "STACK_APPLY_FAILED"
85
95
  category = "interrupted" if code == 130 else "execution"
86
96
  fields: list[str] | None = None
97
+ counts: dict[str, int] = {}
87
98
  guards = {
88
99
  "STACK_PLAN_CHANGED",
89
100
  "STACK_APPROVAL_MISMATCH",
90
101
  "STACK_REPLAN_FAILED",
91
102
  "STACK_APPLY_LOCKED",
103
+ "STACK_VRAM_INSUFFICIENT",
92
104
  }
93
105
  metadata = details if isinstance(details, Mapping) else {}
94
106
  cause_code = metadata.get("causeCode")
@@ -105,6 +117,8 @@ def error(code: int, details: Mapping[str, object] | None = None) -> int:
105
117
  ):
106
118
  cause, category = cause_code, "guard"
107
119
  fields = [field for field in changed if field in ERROR_PLAN_FIELDS] or None
120
+ if cause_code == "STACK_VRAM_INSUFFICIENT":
121
+ counts = byte_counts(metadata)
108
122
  event = {
109
123
  "schema": "localmodels.stack-error/v1",
110
124
  "event": "error",
@@ -112,6 +126,7 @@ def error(code: int, details: Mapping[str, object] | None = None) -> int:
112
126
  "category": category,
113
127
  "causeCode": cause,
114
128
  **({"changedFields": fields} if fields is not None else {}),
129
+ **counts,
115
130
  }
116
131
  print(json.dumps(event), flush=True)
117
132
  return code
@@ -11,7 +11,7 @@ from datetime import datetime, timezone
11
11
  from typing import Any, Literal
12
12
  from uuid import UUID, uuid4
13
13
 
14
- from localmodels import console, hosts
14
+ from localmodels import console, hosts, stack_progress
15
15
  from localmodels.approval import digest
16
16
  from localmodels.contracts import decode
17
17
  from localmodels.plan_envelope import utc_now
@@ -25,6 +25,7 @@ from localmodels.stack_plan import (
25
25
  StackRecord,
26
26
  command,
27
27
  deployments,
28
+ guard_details,
28
29
  )
29
30
 
30
31
  RunState = Literal["running", "completed", "failed", "interrupted"]
@@ -470,6 +471,10 @@ CAUSES = {
470
471
  "STACK_REPLAN_FAILED": "planning again from this computer's current state failed; "
471
472
  "run stack plan again on this computer",
472
473
  "STACK_APPLY_LOCKED": "another stack apply is running",
474
+ # Raised before a GPU part starts, also after execution began; free_bytes and
475
+ # required_bytes say by how much.
476
+ "STACK_VRAM_INSUFFICIENT": "free VRAM is too low to start the model; close programs that "
477
+ "use the GPU and retry",
473
478
  "STACK_APPLY_INTERRUPTED": "interrupted",
474
479
  "STACK_APPLY_REJECTED": "the plan could not be loaded or checked; "
475
480
  "run the same command without --json to see why",
@@ -601,6 +606,10 @@ def component_failure(record: StackRecord) -> tuple[list[str], tuple[str, str]]
601
606
  return failed, ("STACK_COMPONENT_FAILED", CAUSES["STACK_COMPONENT_FAILED"])
602
607
 
603
608
 
609
+ # Guard codes that keep their own cause when raised after execution started.
610
+ _AFTER_START = frozenset({"STACK_VRAM_INSUFFICIENT"})
611
+
612
+
604
613
  def cause_of(exc: BaseException, *, started: bool) -> tuple[str, str]:
605
614
  """(cause code, fixed message) for an apply that raised ``exc``: a guard's own code (and its
606
615
  literal public sentence when it has one), else interrupted, failed after starting, or
@@ -608,13 +617,25 @@ def cause_of(exc: BaseException, *, started: bool) -> tuple[str, str]:
608
617
  if isinstance(exc, KeyboardInterrupt):
609
618
  return "STACK_APPLY_INTERRUPTED", CAUSES["STACK_APPLY_INTERRUPTED"]
610
619
  code = getattr(exc, "cause_code", None)
611
- if isinstance(code, str) and code in CAUSES and not started:
620
+ if isinstance(code, str) and code in CAUSES and (not started or code in _AFTER_START):
612
621
  public = getattr(exc, "public_message", "")
613
622
  return code, public if isinstance(public, str) and public else CAUSES[code]
614
623
  code = "STACK_APPLY_FAILED" if started else "STACK_APPLY_REJECTED"
615
624
  return code, CAUSES[code]
616
625
 
617
626
 
627
+ def cause_counts(exc: BaseException) -> dict[str, int]:
628
+ """``free_bytes`` and ``required_bytes`` of a STACK_VRAM_INSUFFICIENT guard, else none."""
629
+ if getattr(exc, "cause_code", None) != "STACK_VRAM_INSUFFICIENT":
630
+ return {}
631
+ counts = stack_progress.byte_counts(guard_details(exc))
632
+ return (
633
+ {"free_bytes": counts["freeBytes"], "required_bytes": counts["requiredBytes"]}
634
+ if counts
635
+ else {}
636
+ )
637
+
638
+
618
639
  def machine_result(
619
640
  record: StackRecord | None,
620
641
  state: str,
@@ -624,6 +645,7 @@ def machine_result(
624
645
  attempt_id: str | None = None,
625
646
  plan: StackPlan | None = None,
626
647
  cause: tuple[str, str] | None = None,
648
+ counts: Mapping[str, int] | None = None,
627
649
  ) -> int:
628
650
  view = project(record, plan)
629
651
  if record is not None and (view is None or (state == "completed" and not view["ok"])):
@@ -662,6 +684,7 @@ def machine_result(
662
684
  else {}
663
685
  ),
664
686
  **({"cause_code": cause[0], "message": cause[1]} if cause else {}),
687
+ **(counts if cause and counts else {}),
665
688
  },
666
689
  separators=(",", ":"),
667
690
  )
@@ -32,6 +32,7 @@ from localmodels.planning.budget import (
32
32
  from localmodels.planning.llm_ram import prompt_cache_bytes, prompt_cache_fit
33
33
  from localmodels.probe import GPU, HostFacts
34
34
  from localmodels.records import Plan
35
+ from localmodels.stack_capacity import start_need
35
36
  from localmodels.stack_plan import (
36
37
  HARNESS_RAM,
37
38
  RAM_FLOOR,
@@ -262,10 +263,12 @@ def _suite_gpu(
262
263
  gpu: int | None = None,
263
264
  *,
264
265
  share_gpu: bool = False,
266
+ free_needed: Callable[[GPU], int] | None = None,
265
267
  ) -> GPU:
266
268
  """The card of the running Strata LLM, else the best idle card (``gpu``: only that one). A
267
269
  running plan without a GPU (WHI-169: a synthetic or CPU plan of the same name) runs on no
268
- suite card."""
270
+ suite card. Shared, a card at least ``need`` large passes with ``free_needed(card)`` free,
271
+ at least what the check before start will ask (``stack_capacity.start_need``)."""
269
272
  placed = running["placement"].get("gpus") if running is not None else None
270
273
  cards_of_running = (
271
274
  [c for c in placed if isinstance(c, dict)] if isinstance(placed, list) else []
@@ -290,21 +293,53 @@ def _suite_gpu(
290
293
  free = gib(mac["free_bytes"])
291
294
  raise StackError(f"{llm['id']} needs {gib(need)} of unified memory, {free} is free")
292
295
  return mac
293
- candidates = sharing_cards(facts, need) if share_gpu else idle_cards(facts, need)
296
+ if share_gpu and free_needed is not None:
297
+ candidates = [
298
+ g
299
+ for g in sharing_cards(facts, 0)
300
+ if g["total_bytes"] >= need and g["free_bytes"] >= free_needed(g)
301
+ ]
302
+ else:
303
+ candidates = sharing_cards(facts, need) if share_gpu else idle_cards(facts, need)
294
304
  cards = [g for g in candidates if gpu is None or g["index"] == gpu]
295
- if not cards:
296
- held_by = holders(facts)
305
+ if cards:
306
+ return cards[0]
307
+ which = "an" if gpu is None else f"GPU {gpu} to be an"
308
+ if share_gpu and free_needed is not None:
297
309
  seen = "; ".join(
298
- f"GPU {g['index']} {gib(g['total_bytes'])}"
299
- + "".join(f", {why}" for why in held_by.get(g["uuid"], ["idle"]))
300
- for g in facts.get("gpus") or []
310
+ f"GPU {g['index']} {gib(g['total_bytes'])}, {gib(g['free_bytes'])} free"
311
+ + (f" of {gib(free_needed(g))} needed" if g["total_bytes"] >= need else "")
312
+ for g in sharing_cards(facts, 0)
301
313
  )
302
- which = "an" if gpu is None else f"GPU {gpu} to be an"
303
314
  raise StackError(
304
- f"{llm['id']} needs {which} NVIDIA GPU with no compute processes and at least "
305
- f"{gib(need)} of memory; this host: {seen or 'no NVIDIA GPU'}"
315
+ f"{llm['id']} needs {which} NVIDIA GPU of at least {gib(need)} with enough free "
316
+ f"VRAM for it; this host: {seen or 'no NVIDIA GPU'}"
306
317
  )
307
- return cards[0]
318
+ held_by = holders(facts)
319
+ seen = "; ".join(
320
+ f"GPU {g['index']} {gib(g['total_bytes'])}"
321
+ + "".join(f", {why}" for why in held_by.get(g["uuid"], ["idle"]))
322
+ for g in facts.get("gpus") or []
323
+ )
324
+ raise StackError(
325
+ f"{llm['id']} needs {which} NVIDIA GPU with no compute processes and at least "
326
+ f"{gib(need)} of memory; this host: {seen or 'no NVIDIA GPU'}"
327
+ )
328
+
329
+
330
+ def _free_to_plan(recipe: suite.SuiteRecipe, card: GPU, options: StackOptions) -> int:
331
+ """The free VRAM a shared ``card`` needs for the recipe: never less than ``stack apply`` asks
332
+ before it starts it (``stack_capacity.start_need`` on its plan's ``vram_bytes`` and floor
333
+ there, with the picture reader this card gets and the decision reserve), and never less
334
+ than the recipe's ``vram_bytes``. A PolyStrata floor is enough to start, not to run at
335
+ speed: on a card another program is using, Windows pages the expert cache in and out
336
+ (MR !781 homewin acceptance, 2026-12-01: 6.5 GiB free decoded about 11 tok/s), so shared
337
+ planning keeps the full-cache size until the engine sizes its cache by the real free VRAM."""
338
+ reader = vision.strata_mode(
339
+ options.get("vision", "off"), card["total_bytes"], bool(recipe.get("vision"))
340
+ )
341
+ vram, floor = suite.gpu_bytes(recipe, reader)
342
+ return max(int(recipe.get("vram_bytes", 0)), start_need(vram, floor, card, options))
308
343
 
309
344
 
310
345
  def strata_parts(
@@ -334,7 +369,14 @@ def strata_parts(
334
369
  unified = metal.supported(facts) and llm_recipe["runtime"] == "strata-poly"
335
370
  need = unified_bytes(llm_recipe) if unified else int(llm_recipe.get("vram_bytes", 0))
336
371
  gpu = _suite_gpu(
337
- facts, llm_recipe, need, running_llm, options.get("gpu"), share_gpu=options["share_gpu"]
372
+ facts,
373
+ llm_recipe,
374
+ need,
375
+ running_llm,
376
+ options.get("gpu"),
377
+ share_gpu=options["share_gpu"],
378
+ # A shared card: at least what stack apply checks before it starts the LLM.
379
+ free_needed=None if unified else (lambda card: _free_to_plan(llm_recipe, card, options)),
338
380
  )
339
381
  # Strata's own free margin, the decision model, and its growth.
340
382
  reserve = STRATA_FREE_MIB + ((vram + DECISION_VRAM_GROWTH) >> 20) if vram else STRATA_FREE_MIB