@simplexai/localmodels-darwin-x64 0.1.0-dev.63 → 0.1.0-dev.64

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 (72) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +71 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +15 -2
  5. package/modules/localmodels/catalog.json +34 -0
  6. package/modules/localmodels/catalog.py +26 -4
  7. package/modules/localmodels/catalog_recipes.py +37 -1
  8. package/modules/localmodels/context_policy.py +6 -1
  9. package/modules/localmodels/debug_mode.py +85 -103
  10. package/modules/localmodels/deploy.py +41 -6
  11. package/modules/localmodels/download-mirrors.json +126 -6
  12. package/modules/localmodels/draft_spec.py +122 -0
  13. package/modules/localmodels/engine_adapters/__init__.py +4 -0
  14. package/modules/localmodels/engine_adapters/auxiliary.py +27 -0
  15. package/modules/localmodels/engine_adapters/base.py +40 -0
  16. package/modules/localmodels/engine_adapters/strata_poly.py +57 -0
  17. package/modules/localmodels/engine_adapters/suite_plan.py +394 -0
  18. package/modules/localmodels/engines-prism-b12178-03ec600.json +7 -7
  19. package/modules/localmodels/install.py +15 -0
  20. package/modules/localmodels/library_convert.py +2 -8
  21. package/modules/localmodels/library_elastic.py +2 -118
  22. package/modules/localmodels/library_jobs.py +1 -2
  23. package/modules/localmodels/library_poly.py +3 -2
  24. package/modules/localmodels/library_pricing.py +122 -13
  25. package/modules/localmodels/library_serve.py +4 -6
  26. package/modules/localmodels/memcalc_cli.py +2 -2
  27. package/modules/localmodels/planning/__init__.py +3 -0
  28. package/modules/localmodels/{memcalc_load.py → planning/memcalc_load.py} +1 -1
  29. package/modules/localmodels/{sizecalc.py → planning/sizecalc.py} +1 -1
  30. package/modules/localmodels/service_deployment.py +2 -1
  31. package/modules/localmodels/sizecalc_cli.py +10 -2
  32. package/modules/localmodels/speech_worker_sensevoice.py +30 -0
  33. package/modules/localmodels/stack.py +2 -4
  34. package/modules/localmodels/stack_arena.py +2 -2
  35. package/modules/localmodels/stack_auto.py +1 -1
  36. package/modules/localmodels/stack_aux_gpu.py +4 -2
  37. package/modules/localmodels/stack_card.py +2 -2
  38. package/modules/localmodels/stack_cleanup.py +3 -2
  39. package/modules/localmodels/stack_compose.py +9 -1
  40. package/modules/localmodels/stack_ledger.py +2 -1
  41. package/modules/localmodels/stack_mcp.py +1 -1
  42. package/modules/localmodels/stack_memory.py +3 -3
  43. package/modules/localmodels/stack_run.py +16 -0
  44. package/modules/localmodels/stack_suite.py +4 -3
  45. package/modules/localmodels/stack_try.py +2 -1
  46. package/modules/localmodels/stack_up.py +15 -30
  47. package/modules/localmodels/stack_view_llm.py +12 -7
  48. package/modules/localmodels/stack_warm.py +6 -3
  49. package/modules/localmodels/stack_whatif.py +1 -1
  50. package/modules/localmodels/suite.py +6 -334
  51. package/modules/localmodels/tui_views.py +17 -2
  52. package/modules/localmodels/web/index.html +595 -226
  53. package/modules/localmodels/web/sizecalc/app.js +34 -40
  54. package/modules/localmodels/web/sizecalc/calc.js +3 -3
  55. package/modules/localmodels/web/sizecalc/page.html +4 -3
  56. package/modules/localmodels/web/view/fleet.html +18 -3
  57. package/modules/localmodels/web/view/fleet.js +135 -14
  58. package/modules/localmodels/web/view/i18n.js +4 -0
  59. package/modules/localmodels/web/view/index.html +16 -0
  60. package/modules/localmodels/web/view/nav.js +49 -0
  61. package/modules/localmodels/web/view/theme.js +1 -1
  62. package/modules/localmodels/web/view/view.css +51 -15
  63. package/modules/localmodels/web/view/view.js +22 -4
  64. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/METADATA +1 -1
  65. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/RECORD +68 -61
  66. package/package.json +1 -1
  67. package/tool.json +1 -1
  68. /package/modules/localmodels/{memcalc.py → planning/memcalc.py} +0 -0
  69. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/WHEEL +0 -0
  70. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/entry_points.txt +0 -0
  71. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/licenses/NOTICE +0 -0
  72. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,122 @@
1
+ """Optional external speculative-decoding drafter pricing and flags (e.g. DSpark on Metal).
2
+
3
+ Unlike built-in MTP heads, an external drafter such as ``dspark-Inkling-2-Mini-Q8_0.gguf`` is a
4
+ separate pinned GGUF paired with ``--model-draft``, ``--spec-type``, and ``--spec-draft-n-max``.
5
+ It is strictly headroom-gated: admitted only after window, KV precision, slots, ubatch, and GPU
6
+ vision are chosen, and only when the device still keeps ``METAL_DRAFT_HEADROOM_BYTES`` free. It
7
+ never degrades context length, KV precision, or vision, and never passes ``-devd`` (DSpark borrows
8
+ the target model's embeddings and LM head)."""
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping
13
+ from dataclasses import dataclass, replace
14
+
15
+ from localmodels.context_policy import (
16
+ METAL_CTX_CHECKPOINTS,
17
+ AgentPosture,
18
+ LaunchPlan,
19
+ WindowDecision,
20
+ )
21
+ from localmodels.estimator import HardwareBudget
22
+
23
+ GIB = 1 << 30
24
+ # Spare device budget kept before enabling an optional Metal drafter (matches Metal ubatch).
25
+ METAL_DRAFT_HEADROOM_BYTES = 1 << 30
26
+ # Relative KV element size versus q8_0 (34/32 B/elem), matching estimator._KV_DTYPE_BYTES_PER_ELEM.
27
+ _KV_SCALE_VS_Q8 = {"f16": 64 / 34, "q8_0": 1.0, "q4_0": 18 / 34}
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class DraftSpec:
32
+ """Catalog metadata for an optional backend-gated speculative drafter."""
33
+
34
+ spec_type: str # llama-server --spec-type value (e.g. "draft-dspark")
35
+ n_max: int # llama-server --spec-draft-n-max value (e.g. 4)
36
+ weights_bytes: int # pinned drafter GGUF size_bytes
37
+ overhead_bytes: int # fixed compute/scratch buffer added on the device
38
+ kv_bytes_per_token: int # full-attention KV bytes/token at q8_0/q8_0
39
+ kv_swa_bytes: int = 0 # fixed sliding-window KV bytes
40
+ backends: tuple[str, ...] = ("metal",)
41
+
42
+
43
+ def device_bytes(spec: DraftSpec, window: int, kv_types: tuple[str, str]) -> int:
44
+ """Device memory added by the drafter at ``window`` and ``kv_types``."""
45
+ k_scale = _KV_SCALE_VS_Q8.get(kv_types[0], 1.0)
46
+ v_scale = _KV_SCALE_VS_Q8.get(kv_types[1], 1.0)
47
+ kv_ratio = (k_scale + v_scale) / 2.0
48
+ kv_full = int(max(0, window) * spec.kv_bytes_per_token * kv_ratio)
49
+ return spec.weights_bytes + spec.overhead_bytes + spec.kv_swa_bytes + kv_full
50
+
51
+
52
+ def llama_args(path: str, spec_type: str, n_max: int) -> list[str]:
53
+ """llama-server flags for an active external drafter; never emits ``-devd``."""
54
+ if not path or not spec_type or n_max <= 0:
55
+ return []
56
+ return [
57
+ "--model-draft",
58
+ path,
59
+ "--spec-type",
60
+ spec_type,
61
+ "--spec-draft-n-max",
62
+ str(n_max),
63
+ ]
64
+
65
+
66
+ def launch_keys(decision: WindowDecision) -> dict[str, object]:
67
+ """Plan ``launch`` keys emitted only when an optional drafter is active."""
68
+ if decision.draft_n_max <= 0 or not decision.draft_type:
69
+ return {}
70
+ return {
71
+ "draft_type": decision.draft_type,
72
+ "draft_n_max": decision.draft_n_max,
73
+ "draft_bytes": decision.draft_bytes,
74
+ }
75
+
76
+
77
+ def active(launch: Mapping[str, object]) -> bool:
78
+ """Whether a plan's ``launch`` block enables an optional external drafter."""
79
+ raw = launch.get("draft_n_max")
80
+ return isinstance(raw, int) and not isinstance(raw, bool) and raw > 0
81
+
82
+
83
+ def priced(
84
+ spec: DraftSpec | None,
85
+ planned: LaunchPlan,
86
+ budget: HardwareBudget,
87
+ posture: AgentPosture,
88
+ ) -> LaunchPlan:
89
+ """Admit ``spec`` onto an already-fitted agent launch when backend and headroom allow.
90
+
91
+ Never shortens the window, lowers KV precision, drops GPU vision, or triggers spill.
92
+ """
93
+ decision = planned.decision
94
+ if spec is None or posture.draft == "off" or not isinstance(decision, WindowDecision):
95
+ return planned
96
+ if decision.spilled or decision.mtp_draft_depth > 0:
97
+ return planned
98
+ backend = (
99
+ "metal"
100
+ if (budget.uma and budget.platform == "darwin")
101
+ or posture.ctx_checkpoints == METAL_CTX_CHECKPOINTS
102
+ else "cuda"
103
+ if not budget.uma
104
+ else ""
105
+ )
106
+ if backend not in spec.backends:
107
+ return planned
108
+ cost = device_bytes(spec, decision.window, decision.kv_types)
109
+ if decision.vram_bytes + cost + METAL_DRAFT_HEADROOM_BYTES > budget.usable_vram_bytes:
110
+ return planned
111
+ note = f"speculation: {spec.spec_type} n_max={spec.n_max} (+{cost / GIB:.2f} GiB)"
112
+ return replace(
113
+ planned,
114
+ decision=replace(
115
+ decision,
116
+ vram_bytes=decision.vram_bytes + cost,
117
+ draft_type=spec.spec_type,
118
+ draft_n_max=spec.n_max,
119
+ draft_bytes=cost,
120
+ reasons=[*decision.reasons, note],
121
+ ),
122
+ )
@@ -0,0 +1,4 @@
1
+ """Per-engine plan adapters. ``suite_plan.build_plan`` assembles every catalog component's
2
+ deployment plan and asks the adapter for its runtime (``adapter_for``) only where engines differ:
3
+ Strata and PolyStrata (``strata_poly``) or every other server (``auxiliary``). The hooks are in
4
+ ``base.EngineAdapter``; see docs/local-models/architecture.md#子包."""
@@ -0,0 +1,27 @@
1
+ """Every runtime that is not Strata: the CPU embedding, reranker, STT and TTS servers and the
2
+ llama.cpp CUDA (or Metal) engine of a GPU component."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from localmodels.engine_adapters.base import EngineAdapter
7
+ from localmodels.records import ReleaseEngine
8
+
9
+ LLAMA_RUNTIMES = ("llama.cpp", "llama.cpp-cpu")
10
+ # Prebuilt CPU engines that load their shared libraries from the engine directory.
11
+ CPU_BUILDS = ("llama.cpp-cpu", "whisper.cpp-cpu")
12
+
13
+
14
+ class AuxAdapter(EngineAdapter):
15
+ """A plain server for ``runtime``; only llama.cpp picks its device and only the prebuilt
16
+ CPU engines (or any engine on a card) need ``LD_LIBRARY_PATH``."""
17
+
18
+ def __init__(self, runtime: str) -> None:
19
+ self.runtime = runtime
20
+
21
+ def device_args(self, *, apple: bool, on_gpu: bool) -> list[str]:
22
+ if apple and self.runtime in LLAMA_RUNTIMES:
23
+ return ["--device", "MTL0" if on_gpu else "none"]
24
+ return []
25
+
26
+ def library_path(self, engine: ReleaseEngine, *, on_gpu: bool) -> str | None:
27
+ return engine["dir"] if self.runtime in CPU_BUILDS or on_gpu else None
@@ -0,0 +1,40 @@
1
+ """The hooks where one engine's plan differs from another's (``suite_plan.build_plan``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from localmodels.probe import HostFacts
8
+ from localmodels.records import ReleaseEngine
9
+ from localmodels.suite import SuiteOptions, SuiteRecipe
10
+
11
+
12
+ class EngineAdapter:
13
+ """What a runtime adds to the shared suite plan. The defaults are a plain server with no
14
+ serve profile, which is what every non-Strata runtime is."""
15
+
16
+ def on_gpu(self, r: SuiteRecipe) -> bool:
17
+ """Whether the component holds a card (and so needs ``SuiteOptions.gpu``)."""
18
+ return bool(r.get("vram_bytes"))
19
+
20
+ def check(self, facts: HostFacts, r: SuiteRecipe) -> None:
21
+ """Refuse a host the engine has no build for, before anything is planned."""
22
+
23
+ def reader_args(self, reader: str) -> list[str]:
24
+ """Serve-profile flags that turn the picture reader on (``reader`` is not off)."""
25
+ return []
26
+
27
+ def finish_profile(self, profile: dict[str, Any], options: SuiteOptions) -> None:
28
+ """Engine defaults written into the serve profile after the recipe's own entries."""
29
+
30
+ def device_args(self, *, apple: bool, on_gpu: bool) -> list[str]:
31
+ """Flags that pick the engine's device, appended to the recipe's argv."""
32
+ return []
33
+
34
+ def library_path(self, engine: ReleaseEngine, *, on_gpu: bool) -> str | None:
35
+ """The ``LD_LIBRARY_PATH`` the engine's shared libraries need, if any."""
36
+ return None
37
+
38
+ def launch_keys(self, profile: dict[str, object]) -> dict[str, object]:
39
+ """Plan ``launch`` keys read from the rendered serve profile."""
40
+ return {}
@@ -0,0 +1,57 @@
1
+ """Strata and PolyStrata: MoE engines that keep experts in host RAM beside a GPU cache and run
2
+ from a ``strata-profile.json`` serve profile written beside the service."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Any, cast
7
+
8
+ from localmodels.engine_adapters.base import EngineAdapter
9
+ from localmodels.plan_envelope import PlanError
10
+ from localmodels.probe import HostFacts
11
+ from localmodels.records import ReleaseEngine
12
+ from localmodels.suite import SuiteOptions, SuiteRecipe
13
+
14
+
15
+ class StrataAdapter(EngineAdapter):
16
+ """Strata's own engine: CUDA only."""
17
+
18
+ def on_gpu(self, r: SuiteRecipe) -> bool:
19
+ return True
20
+
21
+ def check(self, facts: HostFacts, r: SuiteRecipe) -> None:
22
+ if facts["platform"] == "darwin":
23
+ raise PlanError("Strata recipes need CUDA and cannot run on Apple Silicon Metal")
24
+
25
+ def reader_args(self, reader: str) -> list[str]:
26
+ return ["--vision"]
27
+
28
+ def finish_profile(self, profile: dict[str, Any], options: SuiteOptions) -> None:
29
+ if options.reasoning_budget:
30
+ # strata-<model>.json's default for requests that name none (Strata DETAILS, v0.2.4).
31
+ profile["reasoning_budget_tokens"] = options.reasoning_budget
32
+
33
+ def library_path(self, engine: ReleaseEngine, *, on_gpu: bool) -> str | None:
34
+ return None
35
+
36
+ def launch_keys(self, profile: dict[str, object]) -> dict[str, object]:
37
+ launch: dict[str, object] = {"slots": int(str(profile.get("parallel") or 1))}
38
+ args = cast("list[str]", profile.get("args") or [])
39
+ if "--mtp" in args and "--spec" in args:
40
+ launch["mtp_draft_depth"] = int(args[args.index("--spec") + 1])
41
+ return launch
42
+
43
+
44
+ class PolyStrataAdapter(StrataAdapter):
45
+ """PolyStrata's strata-poly, started by its Python server; it has a Metal build too."""
46
+
47
+ def check(self, facts: HostFacts, r: SuiteRecipe) -> None:
48
+ return None
49
+
50
+ def reader_args(self, reader: str) -> list[str]:
51
+ return []
52
+
53
+ def finish_profile(self, profile: dict[str, Any], options: SuiteOptions) -> None:
54
+ # PolyStrata's server enables prompt-start warm-up only when opt-in warm_start is true,
55
+ # and maps parallel: 2 to --batch 2 (WHI-1059 / WHI-1012).
56
+ profile.setdefault("warm_start", True)
57
+ profile.setdefault("parallel", 2)
@@ -0,0 +1,394 @@
1
+ """The deployment plan for one suite component (``suite.SuiteRecipe``) from its catalog
2
+ template. Everything here is shared by every runtime; where engines differ the plan asks the
3
+ runtime's adapter (``adapter_for``)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import sys
9
+ import urllib.parse
10
+ from pathlib import Path
11
+ from typing import Any, cast
12
+
13
+ from localmodels import catalog as cat
14
+ from localmodels import hosts, reuse, suite, vision
15
+ from localmodels.component import front_venv, venv_python
16
+ from localmodels.engine_adapters.auxiliary import AuxAdapter
17
+ from localmodels.engine_adapters.base import EngineAdapter
18
+ from localmodels.engine_adapters.strata_poly import PolyStrataAdapter, StrataAdapter
19
+ from localmodels.engines import engine_lock_path, release_engine, select_engine_build
20
+ from localmodels.frontend import MIN_PYTHON
21
+ from localmodels.plan_envelope import (
22
+ Deployment,
23
+ PlanError,
24
+ cpu_threads,
25
+ deployment,
26
+ plan_envelope,
27
+ verified_in_place,
28
+ )
29
+ from localmodels.probe import HostFacts
30
+ from localmodels.records import ModelSpec, Plan, ReleaseEngine, ReusableFile
31
+ from localmodels.suite import (
32
+ AUTH_PROXY,
33
+ NO_SWAP,
34
+ PACKAGE_DIR,
35
+ POLY_SERVER,
36
+ SERVERS,
37
+ SLICE,
38
+ SOURCES,
39
+ TTS_SERVER,
40
+ SuiteFile,
41
+ SuiteOptions,
42
+ SuiteRecipe,
43
+ )
44
+
45
+ ADAPTERS: dict[str, EngineAdapter] = {
46
+ "strata": StrataAdapter(),
47
+ "strata-poly": PolyStrataAdapter(),
48
+ }
49
+
50
+
51
+ def adapter_for(runtime: str) -> EngineAdapter:
52
+ """The adapter of a recipe's ``runtime``: Strata's two engines, else a plain server."""
53
+ return ADAPTERS.get(runtime) or AuxAdapter(runtime)
54
+
55
+
56
+ def _engine(r: SuiteRecipe, facts: HostFacts, base_dir: str, backend: str) -> ReleaseEngine:
57
+ build = select_engine_build(facts, backend, engine_lock_path(r["engine"]))
58
+ return release_engine(build, base_dir)
59
+
60
+
61
+ def venv_engine(r: SuiteRecipe, base_dir: str) -> ReleaseEngine:
62
+ """The Python of the recipe's hash-locked venv; the requirements file is its pin. stack is
63
+ local-only, so the venv is made from the Python planning runs on."""
64
+ if sys.version_info < MIN_PYTHON:
65
+ need = ".".join(map(str, MIN_PYTHON))
66
+ raise PlanError(
67
+ f"its Python environment needs Python {need} or newer; this host has {sys.version.split()[0]}"
68
+ )
69
+ venv = front_venv(base_dir, r["venv"])
70
+ return {"source": "venv", "binary": venv_python(venv), "build": r["venv"], "dir": venv}
71
+
72
+
73
+ def _threads(r: SuiteRecipe, facts: HostFacts) -> int:
74
+ return int(r["threads"]) if r.get("threads") else cpu_threads(facts)
75
+
76
+
77
+ def _formatted(value: object, values: dict[str, str]) -> object:
78
+ if isinstance(value, str):
79
+ return value.format(**values)
80
+ if isinstance(value, list):
81
+ return [_formatted(v, values) for v in value]
82
+ if isinstance(value, dict):
83
+ return {k: _formatted(v, values) for k, v in value.items()}
84
+ return value
85
+
86
+
87
+ def _reuse(files: list[ReusableFile], specs: list[SuiteFile], roots: tuple[str, ...]) -> None:
88
+ """Point each file at a same-size copy under a --reuse-from directory (at its catalog path)
89
+ on the destination's filesystem; the download step hard-links it only after the SHA256
90
+ matches. A copy elsewhere cannot be linked, so it is not counted as saved download."""
91
+ for f, spec in zip(files, specs, strict=True):
92
+ for root in roots:
93
+ candidate = Path(root).expanduser() / spec["path"]
94
+ if (
95
+ candidate.is_file()
96
+ and candidate.stat().st_size == f["size_bytes"]
97
+ and candidate.stat().st_dev == reuse.device(str(Path(f["dest"]).expanduser()))
98
+ ):
99
+ f["reuse"] = str(candidate)
100
+ break
101
+
102
+
103
+ def _plan_files(
104
+ r: SuiteRecipe, options: SuiteOptions, model_dir: str, reader: str
105
+ ) -> list[ReusableFile]:
106
+ template = SOURCES[r.get("source", "hf")]
107
+ files: list[ReusableFile] = []
108
+ specs = [
109
+ f for f in cast("list[SuiteFile]", r["files"]) if reader != "off" or not f.get("vision")
110
+ ]
111
+ for f in specs: # catalog files may name their own source
112
+ repo, revision = f.get("repo", r["repo"]), f.get("revision", r["revision"])
113
+ url = "" if f.get("derived") else f.get("url") or template
114
+ files.append(
115
+ {
116
+ "repo": repo,
117
+ "path": f["path"],
118
+ "revision": revision,
119
+ "size_bytes": f["size_bytes"],
120
+ "sha256": f["sha256"],
121
+ "local_name": f.get("local_name", f["path"].rsplit("/", 1)[-1]),
122
+ "dest": f"{model_dir}/{f.get('local_name', f['path'])}",
123
+ "url": url.format(
124
+ hf=options.hf_endpoint,
125
+ repo=repo,
126
+ revision=revision,
127
+ path=urllib.parse.quote(f["path"]),
128
+ catalog_dir=cat.CATALOG_PATH.parent,
129
+ ),
130
+ }
131
+ )
132
+ if f.get("derived"):
133
+ files[-1]["generated"] = True
134
+ _reuse(files, specs, options.reuse_from)
135
+ missing = [
136
+ s["path"]
137
+ for f, s in zip(files, specs, strict=True)
138
+ if s.get("derived") and not f.get("reuse") and not verified_in_place(f)
139
+ ]
140
+ if missing and not r.get("preparation"):
141
+ raise PlanError(
142
+ f"{r['id']} has no pinned preparation recipe for {len(missing)} generated files "
143
+ f"(such as {missing[0]}); point --reuse-from at an existing Strata model directory"
144
+ )
145
+ return files
146
+
147
+
148
+ def _profile_template(
149
+ facts: HostFacts,
150
+ r: SuiteRecipe,
151
+ options: SuiteOptions,
152
+ files: list[ReusableFile],
153
+ values: dict[str, str],
154
+ reader: str,
155
+ ) -> dict[str, Any]:
156
+ """Build the rendered Strata/PolyStrata ``strata-profile.json`` template."""
157
+ adapter = adapter_for(r["runtime"])
158
+ profile_template = dict(r.get("profile") or {})
159
+ if reader != "off":
160
+ projector = next(f for f in files if f["local_name"] == r["vision"]["mmproj"])
161
+ values["vision_mmproj"] = projector["dest"]
162
+ cores = int(facts.get("cpu", {}).get("logical_cores") or 2)
163
+ profile_template["vision"] = vision.strata_section(reader, cores, exe="{vision_exe}")
164
+ if extra := adapter.reader_args(reader):
165
+ profile_template["args"] = [*cast("list[str]", profile_template["args"]), *extra]
166
+ if options.gpu and r.get("card_args"):
167
+ # Under --gpu-memory the reserve also holds what the share leaves out of the real card
168
+ # (stack_gpu_memory.LEFT_OUT, stack_suite.poly_reserve_mib), so the room is counted on it.
169
+ left_out = int(cast("dict[str, int]", options.gpu).get("share_left_out_bytes", 0))
170
+ room = options.gpu["total_bytes"] + left_out - (options.vram_reserve_mib << 20)
171
+ profile_template["args"] = [
172
+ *cast("list[str]", profile_template["args"]),
173
+ *(
174
+ a
175
+ for group in r["card_args"]
176
+ if room >= group["at_least_bytes"]
177
+ and facts["platform"] in group.get("platforms", [facts["platform"]])
178
+ for a in group["args"]
179
+ ),
180
+ ]
181
+ adapter.finish_profile(profile_template, options)
182
+ return profile_template
183
+
184
+
185
+ def _values(
186
+ facts: HostFacts,
187
+ r: SuiteRecipe,
188
+ options: SuiteOptions,
189
+ engine: ReleaseEngine,
190
+ files: list[ReusableFile],
191
+ where: Deployment,
192
+ ) -> dict[str, str]:
193
+ """The placeholders the recipe's argv, env, profile and preparation are formatted with."""
194
+ base = options.base_dir.rstrip("/")
195
+ model_dir = f"{base}/models/{r['id']}"
196
+ windows = facts["platform"] == "win32"
197
+ return {
198
+ "engine": engine["binary"],
199
+ "engine_dir": engine["dir"],
200
+ "vision_exe": f"{engine['dir']}/strata-vision.exe"
201
+ if windows
202
+ else f"{engine['dir']}/strata-vision",
203
+ "model_dir": model_dir,
204
+ "hf_endpoint": options.hf_endpoint,
205
+ "model": files[0]["dest"] if files else model_dir,
206
+ "weights_sha256": files[0]["sha256"] if files else "",
207
+ "alias": r.get("alias", r["id"]),
208
+ "port": str(where.port),
209
+ "key_file": where.api_key_file,
210
+ "deploy_dir": where.deploy_dir,
211
+ "threads": str(_threads(r, facts)),
212
+ "gpu_uuid": options.gpu["uuid"] if options.gpu else "",
213
+ "vram_reserve_mib": str(options.vram_reserve_mib),
214
+ "expert_cache": options.expert_cache,
215
+ "auth_proxy": f"{where.deploy_dir}/{AUTH_PROXY}",
216
+ "tts_server": f"{where.deploy_dir}/{TTS_SERVER}",
217
+ "poly_server": f"{where.deploy_dir}/{POLY_SERVER}",
218
+ "python": venv_python(front_venv(base, r["venv"])) if r.get("venv") else "",
219
+ }
220
+
221
+
222
+ def _argv(r: SuiteRecipe, values: dict[str, str], host_id: str, device: list[str]) -> list[str]:
223
+ argv = [a.format(**values) for a in r["argv"]]
224
+ argv[0] = (
225
+ sys.executable
226
+ if host_id == hosts.LOCAL_ID and r.get("auth_proxy") and argv[0] == "python3"
227
+ else argv[0]
228
+ )
229
+ return argv + device
230
+
231
+
232
+ def _env(
233
+ r: SuiteRecipe, values: dict[str, str], library_path: str | None, apple: bool
234
+ ) -> dict[str, str]:
235
+ env = {k: v.format(**values) for k, v in r.get("env", {}).items()}
236
+ env.setdefault("CUDA_VISIBLE_DEVICES", values["gpu_uuid"])
237
+ if library_path is not None:
238
+ env.setdefault("LD_LIBRARY_PATH", library_path)
239
+ if apple:
240
+ env.pop("CUDA_VISIBLE_DEVICES", None)
241
+ env.pop("LD_LIBRARY_PATH", None)
242
+ return env
243
+
244
+
245
+ def _limits(r: SuiteRecipe, added_mib: int) -> dict[str, str]:
246
+ """The unit's ceilings, raised by what parked conversations and the picture reader add
247
+ (both live in the engine's own cgroup); swap stays off."""
248
+ return {
249
+ k: f"{(suite.size_bytes(v) >> 20) + added_mib}M"
250
+ if added_mib and k in ("MemoryHigh", "MemoryMax")
251
+ else v
252
+ for k, v in {**r.get("limits", {}), **NO_SWAP}.items()
253
+ }
254
+
255
+
256
+ def _placement(options: SuiteOptions, on_gpu: bool, threads: int) -> dict[str, object]:
257
+ gpu = options.gpu if on_gpu else None
258
+ return {
259
+ "id": "gpu" if on_gpu else "cpu",
260
+ "label": f"GPU {gpu['index']}" if gpu else f"CPU {threads} threads",
261
+ "pooled": False,
262
+ "gpus": [{"index": gpu["index"], "uuid": gpu["uuid"], "name": gpu["name"]}] if gpu else [],
263
+ }
264
+
265
+
266
+ def _launch(
267
+ r: SuiteRecipe,
268
+ options: SuiteOptions,
269
+ values: dict[str, str],
270
+ profile: dict[str, Any],
271
+ reader: str,
272
+ parking_mib: int,
273
+ added_mib: int,
274
+ ) -> dict[str, object]:
275
+ return {
276
+ "window": r.get("context", 0),
277
+ "spilled": False,
278
+ "spill_bytes": 0,
279
+ "reasons": [r.get("note", "")],
280
+ "threads": int(values["threads"]),
281
+ "memory_estimate_bytes": r["memory_estimate_bytes"] + (added_mib << 20),
282
+ "vram_bytes": r.get("vram_bytes", 0)
283
+ + (vision.strata_gpu_mib(r.get("vision") or {}, reader) << 20),
284
+ **({"preparation": _formatted(r["preparation"], values)} if r.get("preparation") else {}),
285
+ **({"conversation_cache_mib": parking_mib} if r.get("conversation_cache") else {}),
286
+ **adapter_for(r["runtime"]).launch_keys(profile),
287
+ **({"vision": reader} if reader != "off" else {}),
288
+ # The same keys as a decision front's: stack apply builds the venv before the unit.
289
+ **(
290
+ {
291
+ "frontend_requirements": r["venv"],
292
+ "frontend_base_dir": options.base_dir,
293
+ "frontend_bytes": r.get("venv_bytes", 0),
294
+ }
295
+ if r.get("venv")
296
+ else {}
297
+ ),
298
+ }
299
+
300
+
301
+ def _config_files(
302
+ r: SuiteRecipe, where: Deployment, values: dict[str, str], profile: dict[str, Any]
303
+ ) -> dict[str, str]:
304
+ """The files written beside the service: its serve profile and the Python it runs."""
305
+ config: dict[str, str] = {}
306
+ if profile:
307
+ rendered = _formatted(profile, values)
308
+ config[f"{where.deploy_dir}/strata-profile.json"] = json.dumps(rendered, indent=1) + "\n"
309
+ if r.get("auth_proxy"):
310
+ config[values["auth_proxy"]] = (PACKAGE_DIR / AUTH_PROXY).read_text(encoding="utf-8")
311
+ if server := SERVERS.get(r["runtime"]):
312
+ config[f"{where.deploy_dir}/{server}"] = (PACKAGE_DIR / server).read_text(encoding="utf-8")
313
+ return config
314
+
315
+
316
+ def _readiness(plan: Plan, r: SuiteRecipe) -> None:
317
+ """What the readiness check needs beyond the contract: its input, time and token limit."""
318
+ if r.get("fixture"):
319
+ plan["fixture"] = r["fixture"]
320
+ if r.get("verify_timeout_s"):
321
+ plan["verify_timeout_s"] = r["verify_timeout_s"]
322
+ if r.get("input_tokens"):
323
+ plan["input_tokens"] = r["input_tokens"]
324
+
325
+
326
+ def _parking_values(r: SuiteRecipe, parking_mib: int) -> dict[str, str]:
327
+ """Strata conversation parking's placeholders: the granted budget and the recipe's rest."""
328
+ parking = r.get("conversation_cache")
329
+ if not parking:
330
+ return {}
331
+ return {
332
+ "conversation_cache_mib": str(parking_mib),
333
+ "conversation_cache_slots": str(parking["slots"]),
334
+ "conversation_cache_min_free_mib": str(parking["min_free_mib"]),
335
+ "conversation_cache_min_tokens": str(parking["min_tokens"]),
336
+ }
337
+
338
+
339
+ def _model(r: SuiteRecipe) -> ModelSpec:
340
+ return {
341
+ "id": r["id"],
342
+ "display_name": r.get("display_name") or f"{r.get('alias', r['id'])} ({r['runtime']})",
343
+ "repo": r["repo"],
344
+ "quant": r["version"],
345
+ "model_id": r.get("alias", r["id"]),
346
+ "validated": r.get("status") == "validated",
347
+ }
348
+
349
+
350
+ def build_plan(host_id: str, facts: HostFacts, r: SuiteRecipe, options: SuiteOptions) -> Plan:
351
+ """The deployment plan for one suite component from its catalog template."""
352
+ adapter = adapter_for(r["runtime"])
353
+ base = options.base_dir.rstrip("/")
354
+ on_gpu = adapter.on_gpu(r)
355
+ if on_gpu and options.gpu is None:
356
+ raise PlanError(f"{r['id']} needs an idle NVIDIA GPU")
357
+ apple = facts["platform"] == "darwin" and facts["arch"] == "arm64"
358
+ adapter.check(facts, r)
359
+ backend = ("metal" if apple else "cuda") if on_gpu else "cpu"
360
+ engine = _engine(r, facts, base, backend) if r.get("engine") else venv_engine(r, base)
361
+ reader = options.vision_reader if r.get("vision") else "off"
362
+ files = _plan_files(r, options, f"{base}/models/{r['id']}", reader)
363
+ port = options.port or int(r.get("port") or 0)
364
+ where = deployment(r["id"], port, base, taken=hosts.deployment_dirs(host_id))
365
+ values = _values(facts, r, options, engine, files, where)
366
+ parking_mib = options.conversation_cache_mib if r.get("conversation_cache") else 0
367
+ profile = _profile_template(facts, r, options, files, values, reader)
368
+ values |= _parking_values(r, parking_mib)
369
+ added_mib = parking_mib + vision.strata_ram_mib(r.get("vision") or {}, reader)
370
+ plan = plan_envelope(
371
+ host_id,
372
+ facts,
373
+ where,
374
+ model=_model(r),
375
+ files=files,
376
+ engine=engine,
377
+ placement=_placement(options, on_gpu, int(values["threads"])),
378
+ launch=_launch(r, options, values, profile, reader, parking_mib, added_mib),
379
+ service={
380
+ "argv": _argv(r, values, host_id, adapter.device_args(apple=apple, on_gpu=on_gpu)),
381
+ "env": _env(r, values, adapter.library_path(engine, on_gpu=on_gpu), apple),
382
+ "limits": _limits(r, added_mib),
383
+ "slice": SLICE,
384
+ "slice_limits": {**options.slice_limits, **NO_SWAP},
385
+ },
386
+ endpoint={"model": r.get("alias", r["id"]), "contract": r.get("contract", "chat")},
387
+ warnings=[],
388
+ )
389
+ if config := _config_files(r, where, values, profile):
390
+ plan["service"]["config_files"] = config
391
+ if r.get("health_path"):
392
+ plan["service"]["health_path"] = r["health_path"]
393
+ _readiness(plan, r)
394
+ return plan