@simplexai/localmodels-linux-arm64 0.1.0-dev.64 → 0.1.0-dev.66

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 (127) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +125 -121
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/approval.py +5 -3
  6. package/modules/localmodels/auth_proxy.py +34 -2
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +504 -18
  9. package/modules/localmodels/catalog.py +2 -1
  10. package/modules/localmodels/catalog_recipes.py +3 -0
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +1 -1
  13. package/modules/localmodels/custom_hub.py +54 -6
  14. package/modules/localmodels/custom_probe.py +33 -5
  15. package/modules/localmodels/debug_stub_server.py +34 -1
  16. package/modules/localmodels/deploy.py +45 -285
  17. package/modules/localmodels/deployment_lifecycle.py +167 -0
  18. package/modules/localmodels/download-mirrors.json +43 -3
  19. package/modules/localmodels/draft_spec.py +43 -1
  20. package/modules/localmodels/engine_adapters/__init__.py +4 -2
  21. package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
  22. package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
  23. package/modules/localmodels/engines-b11583.json +9 -5
  24. package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
  25. package/modules/localmodels/engines.json +9 -5
  26. package/modules/localmodels/gateway.py +124 -13
  27. package/modules/localmodels/gateway_accept.py +1 -6
  28. package/modules/localmodels/gateway_cli.py +13 -24
  29. package/modules/localmodels/gateway_ops.py +185 -0
  30. package/modules/localmodels/gateway_server.py +3 -2
  31. package/modules/localmodels/harness.py +13 -16
  32. package/modules/localmodels/harness_core.py +4 -9
  33. package/modules/localmodels/harness_gateway.py +18 -6
  34. package/modules/localmodels/harness_probe.py +64 -3
  35. package/modules/localmodels/hosts.py +22 -34
  36. package/modules/localmodels/library_convert.py +3 -3
  37. package/modules/localmodels/library_custom.py +15 -13
  38. package/modules/localmodels/library_elastic.py +27 -13
  39. package/modules/localmodels/library_jobs.py +151 -28
  40. package/modules/localmodels/library_model.py +22 -2
  41. package/modules/localmodels/library_order.py +5 -4
  42. package/modules/localmodels/library_poly.py +2 -2
  43. package/modules/localmodels/library_pricing.py +34 -318
  44. package/modules/localmodels/library_serve.py +20 -12
  45. package/modules/localmodels/library_smoke.py +8 -1
  46. package/modules/localmodels/library_state.py +12 -0
  47. package/modules/localmodels/library_status.py +26 -16
  48. package/modules/localmodels/llm_rank.py +1 -1
  49. package/modules/localmodels/magpie_legacy.py +160 -0
  50. package/modules/localmodels/magpie_setup.py +6 -1
  51. package/modules/localmodels/pi_profile.py +3 -7
  52. package/modules/localmodels/plan_envelope.py +1 -1
  53. package/modules/localmodels/{budget.py → planning/budget.py} +56 -33
  54. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/recommend.py +1 -1
  57. package/modules/localmodels/recommend_cli.py +3 -4
  58. package/modules/localmodels/remote_ops_mirrors.py +55 -19
  59. package/modules/localmodels/residency_host.py +1 -1
  60. package/modules/localmodels/service_control.py +4 -4
  61. package/modules/localmodels/service_deployment.py +4 -4
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +29 -2
  64. package/modules/localmodels/setup_inspection_harness.py +5 -2
  65. package/modules/localmodels/setup_text.py +6 -0
  66. package/modules/localmodels/setup_upgrade.py +3 -12
  67. package/modules/localmodels/slot_cache.py +1 -3
  68. package/modules/localmodels/speech_admission.py +17 -5
  69. package/modules/localmodels/speech_catalog.py +5 -1
  70. package/modules/localmodels/speech_cli.py +5 -5
  71. package/modules/localmodels/speech_jobs.py +103 -20
  72. package/modules/localmodels/speech_model.py +2 -0
  73. package/modules/localmodels/speech_server.py +132 -9
  74. package/modules/localmodels/speech_state.py +11 -0
  75. package/modules/localmodels/speech_worker_sensevoice.py +215 -19
  76. package/modules/localmodels/speech_workers.py +79 -7
  77. package/modules/localmodels/stack.py +15 -6
  78. package/modules/localmodels/stack_auto.py +10 -4
  79. package/modules/localmodels/stack_aux_gpu.py +1 -1
  80. package/modules/localmodels/stack_binding.py +24 -143
  81. package/modules/localmodels/stack_capacity.py +4 -4
  82. package/modules/localmodels/stack_card.py +1 -1
  83. package/modules/localmodels/stack_cleanup.py +3 -3
  84. package/modules/localmodels/stack_cli.py +3 -0
  85. package/modules/localmodels/stack_client_settings.py +9 -2
  86. package/modules/localmodels/stack_compose.py +42 -9
  87. package/modules/localmodels/stack_console.py +2 -2
  88. package/modules/localmodels/stack_debug.py +1 -1
  89. package/modules/localmodels/stack_decision.py +1 -1
  90. package/modules/localmodels/stack_doctor.py +10 -7
  91. package/modules/localmodels/stack_down.py +3 -3
  92. package/modules/localmodels/stack_gpu_memory.py +1 -1
  93. package/modules/localmodels/stack_hardware.py +3 -3
  94. package/modules/localmodels/stack_hardware_text.py +1 -1
  95. package/modules/localmodels/stack_lifecycle.py +7 -7
  96. package/modules/localmodels/stack_memory.py +1 -1
  97. package/modules/localmodels/stack_mlx.py +1 -1
  98. package/modules/localmodels/stack_plan.py +18 -13
  99. package/modules/localmodels/stack_ports.py +60 -29
  100. package/modules/localmodels/stack_preflight.py +4 -3
  101. package/modules/localmodels/stack_remove.py +13 -6
  102. package/modules/localmodels/stack_review.py +3 -5
  103. package/modules/localmodels/stack_rollback.py +1 -1
  104. package/modules/localmodels/stack_route.py +5 -4
  105. package/modules/localmodels/stack_suite.py +17 -4
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +8 -13
  108. package/modules/localmodels/stack_up.py +10 -9
  109. package/modules/localmodels/stack_update.py +2 -1
  110. package/modules/localmodels/stack_verify.py +4 -30
  111. package/modules/localmodels/stack_view.py +6 -4
  112. package/modules/localmodels/stack_view_apply.py +2 -2
  113. package/modules/localmodels/stack_view_text.py +2 -6
  114. package/modules/localmodels/stack_view_tick.py +2 -2
  115. package/modules/localmodels/stack_view_words.py +5 -2
  116. package/modules/localmodels/stack_warm.py +1 -1
  117. package/modules/localmodels/suite.py +1 -1
  118. package/modules/localmodels/tui_views.py +11 -5
  119. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/METADATA +1 -1
  120. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/RECORD +122 -118
  121. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/NOTICE +3 -0
  122. package/package.json +1 -1
  123. package/tool.json +1 -1
  124. package/modules/localmodels/library_vram.py +0 -123
  125. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/WHEEL +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/entry_points.txt +0 -0
  127. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -5,7 +5,10 @@ separate pinned GGUF paired with ``--model-draft``, ``--spec-type``, and ``--spe
5
5
  It is strictly headroom-gated: admitted only after window, KV precision, slots, ubatch, and GPU
6
6
  vision are chosen, and only when the device still keeps ``METAL_DRAFT_HEADROOM_BYTES`` free. It
7
7
  never degrades context length, KV precision, or vision, and never passes ``-devd`` (DSpark borrows
8
- the target model's embeddings and LM head)."""
8
+ the target model's embeddings and LM head). Two later gates can still leave it off: deploy drops it
9
+ on an engine older than ``DraftSpec.min_engine`` (engine_adapters.llama_cpp.drafter_engine_ok), and the stack drops it
10
+ when, on unified memory, it would leave ``--cache-ram`` below the full prompt cache
11
+ (planning.llm_ram.drafter_costs_cache)."""
9
12
 
10
13
  from __future__ import annotations
11
14
 
@@ -19,6 +22,7 @@ from localmodels.context_policy import (
19
22
  WindowDecision,
20
23
  )
21
24
  from localmodels.estimator import HardwareBudget
25
+ from localmodels.records import Plan
22
26
 
23
27
  GIB = 1 << 30
24
28
  # Spare device budget kept before enabling an optional Metal drafter (matches Metal ubatch).
@@ -38,6 +42,9 @@ class DraftSpec:
38
42
  kv_bytes_per_token: int # full-attention KV bytes/token at q8_0/q8_0
39
43
  kv_swa_bytes: int = 0 # fixed sliding-window KV bytes
40
44
  backends: tuple[str, ...] = ("metal",)
45
+ # Oldest llama.cpp build that accepts ``spec_type`` ("" = any); deploy omits the drafter on an
46
+ # older or different-fork engine (b12588-mix has no draft-dspark).
47
+ min_engine: str = ""
41
48
 
42
49
 
43
50
  def device_bytes(spec: DraftSpec, window: int, kv_types: tuple[str, str]) -> int:
@@ -63,6 +70,9 @@ def llama_args(path: str, spec_type: str, n_max: int) -> list[str]:
63
70
  ]
64
71
 
65
72
 
73
+ _LAUNCH_KEYS = ("draft_type", "draft_n_max", "draft_bytes")
74
+
75
+
66
76
  def launch_keys(decision: WindowDecision) -> dict[str, object]:
67
77
  """Plan ``launch`` keys emitted only when an optional drafter is active."""
68
78
  if decision.draft_n_max <= 0 or not decision.draft_type:
@@ -80,6 +90,38 @@ def active(launch: Mapping[str, object]) -> bool:
80
90
  return isinstance(raw, int) and not isinstance(raw, bool) and raw > 0
81
91
 
82
92
 
93
+ def drafter_dest(plan: Plan) -> str | None:
94
+ """The file an active external drafter runs from (its ``--model-draft``), else None. A plan
95
+ still starts without it: ``without_drafter`` drops the drafter and its flags."""
96
+ argv = plan["service"]["argv"]
97
+ if not active(plan["launch"]) or "--model-draft" not in argv[:-1]:
98
+ return None
99
+ return argv[argv.index("--model-draft") + 1]
100
+
101
+
102
+ def without_drafter(plan: Plan) -> Plan:
103
+ """``plan`` with its external drafter left out: no drafter file, flags, or ``draft_*`` launch
104
+ keys. The model runs unchanged, only without speculation; the memory figures stay as priced
105
+ (with the drafter), an overestimate."""
106
+ dest = drafter_dest(plan)
107
+ if dest is None:
108
+ return plan
109
+ argv = plan["service"]["argv"]
110
+ at = argv.index("--model-draft")
111
+ kept = argv[:at] + argv[at + 2 :]
112
+ for flag in ("--spec-type", "--spec-draft-n-max"):
113
+ if flag in kept[:-1]:
114
+ i = kept.index(flag)
115
+ kept = kept[:i] + kept[i + 2 :]
116
+ launch = {k: v for k, v in plan["launch"].items() if k not in _LAUNCH_KEYS}
117
+ return {
118
+ **plan,
119
+ "files": [f for f in plan["files"] if f["dest"] != dest],
120
+ "service": {**plan["service"], "argv": kept},
121
+ "launch": launch,
122
+ }
123
+
124
+
83
125
  def priced(
84
126
  spec: DraftSpec | None,
85
127
  planned: LaunchPlan,
@@ -1,4 +1,6 @@
1
1
  """Per-engine plan adapters. ``suite_plan.build_plan`` assembles every catalog component's
2
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#子包."""
3
+ Strata and PolyStrata (``strata_poly``) or every other server (``auxiliary``). ``llama_cpp`` holds
4
+ the single-model llama.cpp plan's parts behind ``deploy.build_plan``, with one backend per device
5
+ (CUDA, Metal, CPU). The hooks are in ``base.EngineAdapter`` and ``llama_cpp.LlamaBackend``; see
6
+ docs/local-models/architecture.md#子包."""
@@ -3,6 +3,7 @@ llama.cpp CUDA (or Metal) engine of a GPU component."""
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
+ from localmodels.engine_adapters import llama_cpp
6
7
  from localmodels.engine_adapters.base import EngineAdapter
7
8
  from localmodels.records import ReleaseEngine
8
9
 
@@ -20,7 +21,9 @@ class AuxAdapter(EngineAdapter):
20
21
 
21
22
  def device_args(self, *, apple: bool, on_gpu: bool) -> list[str]:
22
23
  if apple and self.runtime in LLAMA_RUNTIMES:
23
- return ["--device", "MTL0" if on_gpu else "none"]
24
+ return list(
25
+ llama_cpp.backend_for("metal").device_args if on_gpu else llama_cpp.NO_DEVICE
26
+ )
24
27
  return []
25
28
 
26
29
  def library_path(self, engine: ReleaseEngine, *, on_gpu: bool) -> str | None:
@@ -0,0 +1,539 @@
1
+ """llama.cpp single-model plans (``deploy.build_plan``): the engine build, the server's files,
2
+ argv, environment and plan keys. Where they differ by device the plan asks the placement's
3
+ backend (``backend_for``): an NVIDIA card (CUDA), Apple Metal or the CPU."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+
9
+ from localmodels import catalog as cat
10
+ from localmodels import draft_spec, metal, plan_envelope, vision
11
+ from localmodels.context_policy import (
12
+ DEFAULT_UBATCH,
13
+ AgentPosture,
14
+ LaunchPlan,
15
+ WindowDecision,
16
+ agent_launch_args,
17
+ agent_unified_bytes,
18
+ cache_floor_bytes,
19
+ launch_args,
20
+ )
21
+ from localmodels.engines import (
22
+ EngineUnavailableError,
23
+ commit_matches,
24
+ engine_lock_commit,
25
+ engine_lock_path,
26
+ host_engine,
27
+ release_engine,
28
+ select_engine_build,
29
+ )
30
+ from localmodels.estimator import as_loaded, eager
31
+ from localmodels.plan_envelope import PlanError, catalog_pins, hub_url
32
+ from localmodels.planning.budget import Backend, Placement
33
+ from localmodels.probe import GPU, HostFacts, OptionalEngine
34
+ from localmodels.records import ModelSpec, PinnedFile, ReleaseEngine, ReusableFile, SelectedBuild
35
+
36
+ # Apple Metal's llama.cpp: one pinned build for standard GGUFs and looped Inkling 2 Mini alike.
37
+ METAL_DEFAULT_ENGINE = "b12757-mix-ef2df21"
38
+ # llama.cpp's device flags: a Metal placement takes the GPU, ``NO_DEVICE`` hides every device.
39
+ # CPU_ARGS also keep layers, KV and ops off it (an off-card auxiliary component hides it only).
40
+ METAL_DEVICE = ("--device", "MTL0")
41
+ NO_DEVICE = ("--device", "none")
42
+ CPU_ARGS = (
43
+ *NO_DEVICE,
44
+ "--gpu-layers",
45
+ "0",
46
+ "--no-kv-offload",
47
+ "--no-op-offload",
48
+ "--fit",
49
+ "off",
50
+ )
51
+ # Older builds (< b12588) need CUDA graphs disabled on Linux SM 12.0; b12588+ and PrismML
52
+ # prism-b12178+ builds run cleanly with graphs enabled.
53
+ CUDA_GRAPHS_BUILD = 12588
54
+ CUDA_GRAPHS_PRISM_BUILD = 12178
55
+
56
+ Gpus = dict[int, GPU]
57
+
58
+
59
+ class LlamaBackend:
60
+ """Where a llama.cpp plan differs by device. The defaults are an NVIDIA card's."""
61
+
62
+ device_args: tuple[str, ...] = ()
63
+
64
+ def lock_tag(self, tag: str | None) -> str | None:
65
+ """The engine lock a plan pins, given the entry's own (None: the default build)."""
66
+ return tag
67
+
68
+ def check_reused(
69
+ self,
70
+ facts: HostFacts,
71
+ known: OptionalEngine | None,
72
+ argv: list[str],
73
+ required: str,
74
+ lock_commit: str | None,
75
+ ) -> None:
76
+ """Refuse an ``--engine-path`` engine this device cannot confirm."""
77
+
78
+ def check_engine(self, entry: cat.CatalogEntry, engine: ReleaseEngine) -> None:
79
+ """Refuse the planned engine for what the entry loads on this device."""
80
+
81
+ def visible_devices(self, placement: Placement, gpus: Gpus) -> dict[str, str]:
82
+ """The cards the service may see: the placement's, unless it is unified memory."""
83
+ if placement.gpu_indices and not placement.budget.uma:
84
+ return {
85
+ "CUDA_VISIBLE_DEVICES": ",".join(gpus[i]["uuid"] for i in placement.gpu_indices)
86
+ }
87
+ return {}
88
+
89
+ def engine_env(
90
+ self, facts: HostFacts, placement: Placement, gpus: Gpus, engine: ReleaseEngine
91
+ ) -> dict[str, str]:
92
+ """Environment the engine build needs on this device."""
93
+ return {}
94
+
95
+ def placement_gpus(self, facts: HostFacts) -> list[GPU]:
96
+ """Devices the plan lists beside the placement's cards."""
97
+ return []
98
+
99
+ def agent_launch_keys(
100
+ self,
101
+ entry: cat.CatalogEntry,
102
+ variant: cat.QuantVariant,
103
+ decision: WindowDecision,
104
+ agent: AgentPosture,
105
+ ) -> dict[str, object]:
106
+ """Plan ``launch`` keys the agent posture adds on this device."""
107
+ return {}
108
+
109
+
110
+ class CudaBackend(LlamaBackend):
111
+ def engine_env(
112
+ self, facts: HostFacts, placement: Placement, gpus: Gpus, engine: ReleaseEngine
113
+ ) -> dict[str, str]:
114
+ build_num = cat.build_number(engine.get("build"))
115
+ prism_num = cat.prism_build_number(engine.get("build"))
116
+ if (
117
+ facts["platform"] == "linux"
118
+ and (build_num is None or build_num < CUDA_GRAPHS_BUILD)
119
+ and (prism_num is None or prism_num < CUDA_GRAPHS_PRISM_BUILD)
120
+ and any(
121
+ gpus[i]["vendor"] == "nvidia" and gpus[i].get("compute_capability") == "12.0"
122
+ for i in placement.gpu_indices
123
+ )
124
+ ):
125
+ return {"GGML_CUDA_DISABLE_GRAPHS": "1"}
126
+ return {}
127
+
128
+
129
+ class MetalBackend(LlamaBackend):
130
+ device_args = METAL_DEVICE
131
+
132
+ def lock_tag(self, tag: str | None) -> str | None:
133
+ """Release builds older than the Metal default (and no pin) take the Metal default;
134
+ a fork's own lock (not ``b*``) is kept."""
135
+ floor = cat.build_number(METAL_DEFAULT_ENGINE) or 0
136
+ if tag is None or (tag.startswith("b") and (cat.build_number(tag) or 0) < floor):
137
+ return METAL_DEFAULT_ENGINE
138
+ return tag
139
+
140
+ def placement_gpus(self, facts: HostFacts) -> list[GPU]:
141
+ return [g for g in [metal.device(facts)] if g is not None]
142
+
143
+ def agent_launch_keys(
144
+ self,
145
+ entry: cat.CatalogEntry,
146
+ variant: cat.QuantVariant,
147
+ decision: WindowDecision,
148
+ agent: AgentPosture,
149
+ ) -> dict[str, object]:
150
+ """The prompt cache's floor shares unified memory with the model."""
151
+ profile = eager(entry.profile(variant))
152
+ return {
153
+ "unified_bytes": agent_unified_bytes(profile, decision, agent),
154
+ "cache_floor_bytes": cache_floor_bytes(agent, profile),
155
+ }
156
+
157
+
158
+ class CpuBackend(LlamaBackend):
159
+ device_args = CPU_ARGS
160
+
161
+ def check_reused(
162
+ self,
163
+ facts: HostFacts,
164
+ known: OptionalEngine | None,
165
+ argv: list[str],
166
+ required: str,
167
+ lock_commit: str | None,
168
+ ) -> None:
169
+ host_engine(
170
+ {**facts, "engines": [known] if known else []},
171
+ argv,
172
+ required or None,
173
+ False,
174
+ EngineUnavailableError(
175
+ "CPU deployment must confirm every reused-engine launch option; "
176
+ "probe again or use the pinned CPU engine"
177
+ ),
178
+ [],
179
+ commit=lock_commit,
180
+ )
181
+
182
+ def check_engine(self, entry: cat.CatalogEntry, engine: ReleaseEngine) -> None:
183
+ if engine["source"] == "existing" and (entry.mmproj is not None or entry.mtp_capable):
184
+ raise PlanError("CPU: reused engine vision/draft placement unknown; use pinned engine")
185
+
186
+ def visible_devices(self, placement: Placement, gpus: Gpus) -> dict[str, str]:
187
+ return {"CUDA_VISIBLE_DEVICES": ""}
188
+
189
+
190
+ BACKENDS: dict[Backend, LlamaBackend] = {
191
+ "cuda": CudaBackend(),
192
+ "metal": MetalBackend(),
193
+ "cpu": CpuBackend(),
194
+ }
195
+
196
+
197
+ def backend_for(name: Backend) -> LlamaBackend:
198
+ """The hooks of a placement's backend (``Placement.backend``: cuda, metal or cpu)."""
199
+ return BACKENDS[name]
200
+
201
+
202
+ @dataclass(frozen=True)
203
+ class Companions:
204
+ """What a plan loads beside the weights: the picture reader's projector, the agent
205
+ posture's external drafter, or the generic ladder's MTP head."""
206
+
207
+ reader: str
208
+ mmproj: cat.AssetFile | None
209
+ draft: cat.AssetFile | None
210
+ mtp_head: cat.AssetFile | None
211
+
212
+ @property
213
+ def files(self) -> list[cat.AssetFile]:
214
+ return [a for a in (self.mmproj, self.draft, self.mtp_head) if a is not None]
215
+
216
+
217
+ def companions(entry: cat.CatalogEntry, decision: WindowDecision, *, agent: bool) -> Companions:
218
+ """The agent posture reads pictures where the decision put the reader and loads the drafter
219
+ the decision admitted; the generic ladder reads them on the GPU and loads the MTP head."""
220
+ if agent:
221
+ reader = decision.vision_reader
222
+ draft = entry.draft if decision.draft_n_max > 0 else None
223
+ mtp_head = None
224
+ else:
225
+ reader = "gpu" if entry.mmproj else "off"
226
+ draft, mtp_head = None, entry.mtp_head
227
+ return Companions(reader, entry.mmproj if reader != "off" else None, draft, mtp_head)
228
+
229
+
230
+ def assets(
231
+ entry: cat.CatalogEntry, variant: cat.QuantVariant, extra: Companions
232
+ ) -> list[tuple[str, cat.AssetFile]]:
233
+ """The weights and companions to pin, each with the repository it comes from."""
234
+ return [(entry.repo, f) for f in variant.files] + [
235
+ (a.repo or entry.repo, a) for a in extra.files
236
+ ]
237
+
238
+
239
+ def asset_dest(base_dir: str, local_name: str) -> str:
240
+ """Where a plan keeps a companion file (projector, drafter, MTP head) under ``base_dir``."""
241
+ return f"{base_dir.rstrip('/')}/models/assets/{local_name}"
242
+
243
+
244
+ def plan_files(
245
+ pinned: list[PinnedFile], variant: cat.QuantVariant, base: str, download_endpoint: str
246
+ ) -> list[ReusableFile]:
247
+ """The pinned files with their URL and destination: weights (and custom GGUFs) under
248
+ ``models/``, companions under ``models/assets/``."""
249
+ model_names = {f.path for f in variant.files}
250
+
251
+ def dest(f: PinnedFile) -> str:
252
+ if f["path"] in model_names or f["local_name"].startswith("custom/"):
253
+ return f"{base}/models/{f['local_name']}"
254
+ return asset_dest(base, f["local_name"])
255
+
256
+ return [
257
+ {
258
+ "repo": f["repo"],
259
+ "path": f["path"],
260
+ "revision": f["revision"],
261
+ "size_bytes": f["size_bytes"],
262
+ "sha256": f["sha256"],
263
+ "local_name": f["local_name"],
264
+ "dest": dest(f),
265
+ "url": hub_url(download_endpoint, f["repo"], f["revision"], f["path"]),
266
+ }
267
+ for f in pinned
268
+ ]
269
+
270
+
271
+ def drafter_in_place(entry: cat.CatalogEntry, base_dir: str) -> bool:
272
+ """Whether ``entry``'s optional external drafter is under ``base_dir`` with the catalog's
273
+ pinned bytes (its SHA256 receipt). A library load plans the drafter only then: it is an
274
+ accelerator, so a model downloaded before its drafter shipped (Inkling 2 Mini before dev64),
275
+ or one whose drafter fails verification, loads without speculation instead of failing."""
276
+ asset = entry.draft
277
+ if asset is None or asset.sha256 is None:
278
+ return False
279
+ pinned = catalog_pins([(asset.repo or entry.repo, asset)], "")[0]
280
+ planned: ReusableFile = {
281
+ "repo": pinned["repo"],
282
+ "path": pinned["path"],
283
+ "revision": pinned["revision"],
284
+ "size_bytes": pinned["size_bytes"],
285
+ "sha256": pinned["sha256"],
286
+ "local_name": pinned["local_name"],
287
+ "url": "",
288
+ "dest": asset_dest(base_dir, pinned["local_name"]),
289
+ }
290
+ return plan_envelope.verified_in_place(planned)
291
+
292
+
293
+ def server_args(
294
+ entry: cat.CatalogEntry,
295
+ variant: cat.QuantVariant,
296
+ placement: Placement,
297
+ launch: LaunchPlan,
298
+ agent: AgentPosture | None,
299
+ ) -> list[str]:
300
+ """Window, slots, KV and batch flags: the agent posture's, else the generic ladder's."""
301
+ decision = launch.decision
302
+ assert isinstance(decision, WindowDecision)
303
+ if agent is not None:
304
+ return agent_launch_args(decision, agent)
305
+ return launch_args(
306
+ as_loaded(entry.profile(variant), placement.budget),
307
+ decision,
308
+ mtp_capable=entry.mtp_capable,
309
+ mtp_draft_depth=entry.mtp_draft_depth,
310
+ uma=placement.budget.uma,
311
+ mtp_prefill=launch.mtp_prefill,
312
+ ubatch=entry.ubatch,
313
+ )
314
+
315
+
316
+ def trailing_args(
317
+ entry: cat.CatalogEntry,
318
+ variant: cat.QuantVariant,
319
+ files: list[ReusableFile],
320
+ extra: Companions,
321
+ decision: WindowDecision,
322
+ backend: LlamaBackend,
323
+ *,
324
+ agent: bool,
325
+ ) -> list[str]:
326
+ """The argv after the server's own flags: lazy loading (generic ladder only), the
327
+ companions, the catalog's sampling and the device."""
328
+ argv = ["--lazy-mode", "on"] if variant.lazy_bytes and not agent else []
329
+ by_name = {f["path"]: f for f in files}
330
+ if extra.mmproj is not None:
331
+ argv += vision.llama_args(by_name[extra.mmproj.path]["dest"], extra.reader)
332
+ if extra.draft is not None:
333
+ argv += draft_spec.llama_args(
334
+ by_name[extra.draft.path]["dest"], decision.draft_type, decision.draft_n_max
335
+ )
336
+ if extra.mtp_head is not None:
337
+ argv += ["--model-draft", by_name[extra.mtp_head.path]["dest"]]
338
+ for key, value in entry.sampling.items():
339
+ argv += [f"--{key}", value]
340
+ return argv + list(backend.device_args)
341
+
342
+
343
+ def drafter_engine_ok(
344
+ spec: draft_spec.DraftSpec, build: str | None, commit: str | None = None
345
+ ) -> bool:
346
+ """Whether llama.cpp ``build`` accepts the drafter's ``--spec-type``: at least its
347
+ ``min_engine`` release, from the same fork (``b12757-mix-…`` needs a ``mix`` build), or a
348
+ reused engine that is ``min_engine`` itself: probe reads only ``b12757`` and a commit from
349
+ ``--version``, and that commit is the lock's pinned one."""
350
+ if not spec.min_engine:
351
+ return True
352
+ have, need = cat.build_number(build), cat.build_number(spec.min_engine)
353
+ if have is None or need is None or have < need:
354
+ return False
355
+ if commit_matches(engine_lock_commit(spec.min_engine), commit):
356
+ return True
357
+ fork = spec.min_engine.split("-")[1:2]
358
+ return not fork or str(build).split("-")[1:2] == fork
359
+
360
+
361
+ def drafter_refused(
362
+ entry: cat.CatalogEntry, extra: Companions, engine: ReleaseEngine, facts: HostFacts
363
+ ) -> bool:
364
+ """Whether the planned engine cannot run the drafter the plan priced (it was priced
365
+ before the engine was known)."""
366
+ if extra.draft is None or entry.draft_spec is None:
367
+ return False
368
+ commit = next(
369
+ (e.get("commit") for e in facts["engines"] if e["path"] == engine["binary"]), None
370
+ )
371
+ return not drafter_engine_ok(entry.draft_spec, engine.get("build"), commit)
372
+
373
+
374
+ def drafter_warning(entry: cat.CatalogEntry, engine: ReleaseEngine) -> str:
375
+ assert entry.draft_spec is not None
376
+ return (
377
+ f"speculation: the {entry.draft_spec.spec_type} drafter needs llama.cpp "
378
+ f"{entry.draft_spec.min_engine} or newer; engine {engine.get('build') or 'unknown'} "
379
+ "runs without it"
380
+ )
381
+
382
+
383
+ def _reused_engine(
384
+ facts: HostFacts,
385
+ entry: cat.CatalogEntry,
386
+ backend: LlamaBackend,
387
+ path: str,
388
+ pin: tuple[str, str | None],
389
+ warnings: list[str],
390
+ argv: list[str],
391
+ ) -> ReleaseEngine:
392
+ """``--engine-path``: the probed build, or the entry's pin when the commit is the lock's."""
393
+ required, lock_commit = pin
394
+ known = next((e for e in facts["engines"] if e["path"] == path), None)
395
+ tag = known["build"] if known else None
396
+ commit_ok = bool(known and commit_matches(lock_commit, known.get("commit")))
397
+ if not commit_ok and cat.engine_too_old(entry, tag):
398
+ raise PlanError(f"{entry.display_name} needs llama.cpp {required} or newer")
399
+ if commit_ok and (
400
+ not tag
401
+ or (cat.prism_build_number(required) is not None and cat.prism_build_number(tag) is None)
402
+ ):
403
+ tag = required
404
+ if not tag:
405
+ warnings.append("reused engine has no comparable release; model support unconfirmed")
406
+ backend.check_reused(facts, known, argv, required, lock_commit)
407
+ return {"source": "existing", "binary": path, "build": tag}
408
+
409
+
410
+ def _pinned_build(
411
+ facts: HostFacts, entry: cat.CatalogEntry, name: str, backend: LlamaBackend
412
+ ) -> SelectedBuild:
413
+ """The entry's locked build, else the default build when it is new enough, else the
414
+ ``min_engine`` lock; the backend may pin its own lock instead."""
415
+ lock_tag = entry.engine or None
416
+ default: SelectedBuild | None = None
417
+ if lock_tag is None:
418
+ default = select_engine_build(facts, name)
419
+ lock_tag = entry.min_engine if cat.engine_too_old(entry, default["tag"]) else None
420
+ lock_tag = backend.lock_tag(lock_tag)
421
+ if lock_tag is None:
422
+ assert default is not None
423
+ return default
424
+ lock = engine_lock_path(lock_tag)
425
+ if not lock.is_file():
426
+ raise PlanError(
427
+ f"{entry.display_name} needs llama.cpp {lock_tag}; no pinned engine lock is available"
428
+ )
429
+ return select_engine_build(facts, name, lock)
430
+
431
+
432
+ def engine_plan(
433
+ facts: HostFacts,
434
+ entry: cat.CatalogEntry,
435
+ backend: Backend,
436
+ warnings: list[str],
437
+ argv: list[str],
438
+ *,
439
+ base_dir: str,
440
+ engine_path: str | None = None,
441
+ ) -> ReleaseEngine:
442
+ """The llama.cpp engine for ``entry`` on ``backend``: the ``engine_path`` engine when one
443
+ is named, else the pinned release, else a capable engine already on the host."""
444
+ hooks = backend_for(backend)
445
+ required = entry.min_engine or entry.engine
446
+ lock_commit = engine_lock_commit(entry.engine or entry.min_engine) if required else None
447
+ if engine_path:
448
+ pin = (required, lock_commit)
449
+ engine = _reused_engine(facts, entry, hooks, engine_path, pin, warnings, argv)
450
+ else:
451
+ try:
452
+ engine = release_engine(_pinned_build(facts, entry, backend, hooks), base_dir)
453
+ except EngineUnavailableError as exc:
454
+ engine = host_engine(
455
+ facts, argv, required or None, False, exc, warnings, commit=lock_commit
456
+ )
457
+ hooks.check_engine(entry, engine)
458
+ return engine
459
+
460
+
461
+ def service_env(
462
+ facts: HostFacts,
463
+ placement: Placement,
464
+ engine: ReleaseEngine,
465
+ backend: LlamaBackend,
466
+ *,
467
+ reused: bool,
468
+ ) -> dict[str, str]:
469
+ """The service's environment: visible cards, the engine's libraries and the device's
470
+ workarounds; a Mac runs with Metal's service environment instead."""
471
+ gpus = {g["index"]: g for g in facts.get("gpus") or []}
472
+ env = backend.visible_devices(placement, gpus)
473
+ # Windows loads a program's DLLs from its own directory; LD_LIBRARY_PATH means nothing there.
474
+ if facts["platform"] != "win32" and (engine["source"] == "release" or not reused):
475
+ env["LD_LIBRARY_PATH"] = engine.get("dir") or engine["binary"].rsplit("/", 1)[0]
476
+ env |= backend.engine_env(facts, placement, gpus, engine)
477
+ return dict(metal.SERVICE_ENV) if facts["platform"] == "darwin" else env
478
+
479
+
480
+ def model_doc(entry: cat.CatalogEntry, variant: cat.QuantVariant) -> ModelSpec:
481
+ return {
482
+ "id": entry.id,
483
+ "display_name": entry.display_name,
484
+ "repo": entry.repo,
485
+ "quant": variant.quant,
486
+ "model_id": variant.model_id,
487
+ "validated": variant.validated,
488
+ }
489
+
490
+
491
+ def placement_doc(
492
+ facts: HostFacts, placement: Placement, backend: LlamaBackend
493
+ ) -> dict[str, object]:
494
+ gpus = {g["index"]: g for g in facts.get("gpus") or []}
495
+ return {
496
+ "id": placement.id,
497
+ "label": placement.label,
498
+ "pooled": placement.pooled,
499
+ "gpus": [
500
+ {"index": g["index"], "uuid": g["uuid"], "name": g["name"]}
501
+ for g in [gpus[i] for i in placement.gpu_indices if i in gpus]
502
+ + backend.placement_gpus(facts)
503
+ ],
504
+ }
505
+
506
+
507
+ def launch_doc(
508
+ entry: cat.CatalogEntry,
509
+ variant: cat.QuantVariant,
510
+ launch: LaunchPlan,
511
+ extra: Companions,
512
+ backend: LlamaBackend,
513
+ agent: AgentPosture | None,
514
+ ) -> dict[str, object]:
515
+ """The plan's ``launch``. Agent-posture keys appear only in that posture, and vision only
516
+ when on: an older plan rebuilds without them, digest unchanged."""
517
+ decision = launch.decision
518
+ assert isinstance(decision, WindowDecision)
519
+ doc: dict[str, object] = {
520
+ "window": decision.window,
521
+ "spilled": decision.spilled,
522
+ "spill_bytes": decision.spill_bytes,
523
+ "reasons": decision.reasons,
524
+ "mtp_prefill": launch.mtp_prefill,
525
+ }
526
+ if agent is None:
527
+ return doc
528
+ doc |= {
529
+ "slots": decision.slots,
530
+ "kv_types": list(decision.kv_types),
531
+ "mtp_draft_depth": decision.mtp_draft_depth,
532
+ "posture": "agent",
533
+ "vram_bytes": decision.vram_bytes,
534
+ **({"ubatch": decision.ubatch} if decision.ubatch != DEFAULT_UBATCH else {}),
535
+ }
536
+ if extra.mmproj is not None:
537
+ doc |= vision.launch_keys(extra.mmproj, extra.reader)
538
+ doc |= draft_spec.launch_keys(decision)
539
+ return doc | backend.agent_launch_keys(entry, variant, decision, agent)