@simplexai/localmodels-win32-x64 0.1.0-dev.63 → 0.1.0-dev.65

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 (142) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +140 -130
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/app.py +15 -2
  6. package/modules/localmodels/approval.py +5 -3
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +36 -0
  9. package/modules/localmodels/catalog.py +28 -5
  10. package/modules/localmodels/catalog_recipes.py +40 -1
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +7 -2
  13. package/modules/localmodels/custom_probe.py +5 -5
  14. package/modules/localmodels/debug_mode.py +85 -103
  15. package/modules/localmodels/deploy.py +129 -18
  16. package/modules/localmodels/deployment_lifecycle.py +167 -0
  17. package/modules/localmodels/download-mirrors.json +126 -6
  18. package/modules/localmodels/draft_spec.py +164 -0
  19. package/modules/localmodels/engine_adapters/__init__.py +4 -0
  20. package/modules/localmodels/engine_adapters/auxiliary.py +27 -0
  21. package/modules/localmodels/engine_adapters/base.py +40 -0
  22. package/modules/localmodels/engine_adapters/strata_poly.py +57 -0
  23. package/modules/localmodels/engine_adapters/suite_plan.py +394 -0
  24. package/modules/localmodels/engines-prism-b12178-03ec600.json +7 -7
  25. package/modules/localmodels/gateway.py +124 -13
  26. package/modules/localmodels/gateway_accept.py +1 -6
  27. package/modules/localmodels/gateway_cli.py +13 -24
  28. package/modules/localmodels/gateway_ops.py +185 -0
  29. package/modules/localmodels/gateway_server.py +3 -2
  30. package/modules/localmodels/harness.py +13 -16
  31. package/modules/localmodels/harness_core.py +4 -9
  32. package/modules/localmodels/harness_gateway.py +4 -3
  33. package/modules/localmodels/hosts.py +22 -34
  34. package/modules/localmodels/install.py +15 -0
  35. package/modules/localmodels/library_convert.py +5 -11
  36. package/modules/localmodels/library_custom.py +6 -6
  37. package/modules/localmodels/library_elastic.py +24 -127
  38. package/modules/localmodels/library_jobs.py +14 -5
  39. package/modules/localmodels/library_order.py +4 -3
  40. package/modules/localmodels/library_poly.py +5 -4
  41. package/modules/localmodels/library_pricing.py +80 -255
  42. package/modules/localmodels/library_serve.py +13 -14
  43. package/modules/localmodels/library_smoke.py +8 -1
  44. package/modules/localmodels/library_status.py +16 -16
  45. package/modules/localmodels/llm_rank.py +1 -1
  46. package/modules/localmodels/magpie_legacy.py +160 -0
  47. package/modules/localmodels/magpie_setup.py +6 -1
  48. package/modules/localmodels/memcalc_cli.py +2 -2
  49. package/modules/localmodels/pi_profile.py +3 -7
  50. package/modules/localmodels/plan_envelope.py +1 -1
  51. package/modules/localmodels/planning/__init__.py +3 -0
  52. package/modules/localmodels/{budget.py → planning/budget.py} +48 -30
  53. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  54. package/modules/localmodels/{memcalc_load.py → planning/memcalc_load.py} +1 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/{sizecalc.py → planning/sizecalc.py} +1 -1
  57. package/modules/localmodels/recommend.py +1 -1
  58. package/modules/localmodels/recommend_cli.py +3 -4
  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 +3 -2
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +1 -1
  64. package/modules/localmodels/setup_inspection_harness.py +1 -1
  65. package/modules/localmodels/setup_upgrade.py +3 -12
  66. package/modules/localmodels/sizecalc_cli.py +10 -2
  67. package/modules/localmodels/speech_admission.py +1 -1
  68. package/modules/localmodels/speech_jobs.py +2 -1
  69. package/modules/localmodels/speech_model.py +2 -0
  70. package/modules/localmodels/speech_server.py +130 -9
  71. package/modules/localmodels/speech_state.py +11 -0
  72. package/modules/localmodels/speech_worker_sensevoice.py +38 -0
  73. package/modules/localmodels/speech_workers.py +5 -1
  74. package/modules/localmodels/stack.py +4 -9
  75. package/modules/localmodels/stack_arena.py +2 -2
  76. package/modules/localmodels/stack_auto.py +5 -5
  77. package/modules/localmodels/stack_aux_gpu.py +5 -3
  78. package/modules/localmodels/stack_binding.py +24 -143
  79. package/modules/localmodels/stack_capacity.py +1 -1
  80. package/modules/localmodels/stack_card.py +3 -3
  81. package/modules/localmodels/stack_cleanup.py +6 -5
  82. package/modules/localmodels/stack_client_settings.py +9 -2
  83. package/modules/localmodels/stack_compose.py +43 -6
  84. package/modules/localmodels/stack_console.py +2 -2
  85. package/modules/localmodels/stack_debug.py +1 -1
  86. package/modules/localmodels/stack_decision.py +1 -1
  87. package/modules/localmodels/stack_doctor.py +10 -7
  88. package/modules/localmodels/stack_down.py +3 -3
  89. package/modules/localmodels/stack_gpu_memory.py +1 -1
  90. package/modules/localmodels/stack_hardware.py +3 -3
  91. package/modules/localmodels/stack_hardware_text.py +1 -1
  92. package/modules/localmodels/stack_ledger.py +2 -1
  93. package/modules/localmodels/stack_lifecycle.py +7 -7
  94. package/modules/localmodels/stack_mcp.py +1 -1
  95. package/modules/localmodels/stack_memory.py +4 -4
  96. package/modules/localmodels/stack_mlx.py +1 -1
  97. package/modules/localmodels/stack_plan.py +18 -13
  98. package/modules/localmodels/stack_ports.py +2 -2
  99. package/modules/localmodels/stack_preflight.py +4 -3
  100. package/modules/localmodels/stack_remove.py +13 -6
  101. package/modules/localmodels/stack_review.py +3 -5
  102. package/modules/localmodels/stack_rollback.py +1 -1
  103. package/modules/localmodels/stack_route.py +5 -4
  104. package/modules/localmodels/stack_run.py +16 -0
  105. package/modules/localmodels/stack_suite.py +14 -6
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +10 -14
  108. package/modules/localmodels/stack_up.py +25 -39
  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_llm.py +12 -7
  114. package/modules/localmodels/stack_view_text.py +2 -6
  115. package/modules/localmodels/stack_view_tick.py +2 -2
  116. package/modules/localmodels/stack_view_words.py +5 -2
  117. package/modules/localmodels/stack_warm.py +7 -4
  118. package/modules/localmodels/stack_whatif.py +1 -1
  119. package/modules/localmodels/suite.py +6 -334
  120. package/modules/localmodels/tui_views.py +28 -7
  121. package/modules/localmodels/web/index.html +595 -226
  122. package/modules/localmodels/web/sizecalc/app.js +34 -40
  123. package/modules/localmodels/web/sizecalc/calc.js +3 -3
  124. package/modules/localmodels/web/sizecalc/page.html +4 -3
  125. package/modules/localmodels/web/view/fleet.html +18 -3
  126. package/modules/localmodels/web/view/fleet.js +135 -14
  127. package/modules/localmodels/web/view/i18n.js +4 -0
  128. package/modules/localmodels/web/view/index.html +16 -0
  129. package/modules/localmodels/web/view/nav.js +49 -0
  130. package/modules/localmodels/web/view/theme.js +1 -1
  131. package/modules/localmodels/web/view/view.css +51 -15
  132. package/modules/localmodels/web/view/view.js +22 -4
  133. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/METADATA +1 -1
  134. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/RECORD +137 -127
  135. package/package.json +1 -1
  136. package/tool.json +1 -1
  137. package/modules/localmodels/library_vram.py +0 -123
  138. /package/modules/localmodels/{memcalc.py → planning/memcalc.py} +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/WHEEL +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/entry_points.txt +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/NOTICE +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -15,7 +15,7 @@ from collections.abc import Callable
15
15
  from dataclasses import dataclass
16
16
  from pathlib import Path
17
17
 
18
- from localmodels import deploy_steps, gateway, harness, harness_core, hosts
18
+ from localmodels import deploy_steps, gateway, harness, hosts, magpie_legacy
19
19
  from localmodels import stack_lifecycle as lifecycle
20
20
  from localmodels.gateway import AuxEndpoint, Check
21
21
  from localmodels.records import Plan
@@ -74,27 +74,6 @@ def _readiness(component: str, part: Plan) -> Check:
74
74
  return {"check": name, "ok": ok, "detail": (text.splitlines() or [""])[0][:160]}
75
75
 
76
76
 
77
- def _gateway_up(plan: harness.HarnessPlan) -> bool:
78
- if harness.gateway_kind(plan["gateway"]) == "bifrost":
79
- from localmodels import gateway_bifrost
80
-
81
- try:
82
- record = gateway_bifrost.require_target(plan)
83
- except harness.HarnessError:
84
- return False
85
- return bool(
86
- record
87
- and gateway_bifrost.owned_listener(record)
88
- and gateway_bifrost.healthy(plan["gateway"]["addr"])
89
- )
90
- try:
91
- env = harness.checked_gateway_environment(plan)
92
- except harness.HarnessError:
93
- return False
94
- magpie = harness.tool_path(plan, "magpie")
95
- return harness_core.run_tool([magpie, "healthcheck"], timeout=20, env=env).returncode == 0
96
-
97
-
98
77
  def _accept(
99
78
  plan: harness.HarnessPlan, decision_key: str | None, aux: list[AuxEndpoint]
100
79
  ) -> list[Check]:
@@ -106,7 +85,7 @@ class Effects:
106
85
  """The requests verify sends; a test passes its own."""
107
86
 
108
87
  readiness: Callable[[str, Plan], Check] = _readiness
109
- gateway_up: Callable[[harness.HarnessPlan], bool] = _gateway_up
88
+ gateway_up: Callable[[harness.HarnessPlan], bool] = gateway.answers
110
89
  accept: Callable[[harness.HarnessPlan, str | None, list[AuxEndpoint]], list[Check]] = _accept
111
90
 
112
91
 
@@ -161,18 +140,13 @@ def verify(plan: StackPlan, owned: hosts.Owned, do: Effects = REAL) -> list[Chec
161
140
  }
162
141
  )
163
142
  return checks
164
- bifrost = harness.gateway_kind(gw["gateway"]) == "bifrost"
165
143
  if not do.gateway_up(gw):
166
- name = "Bifrost" if bifrost else "Magpie"
144
+ name = magpie_legacy.of(gw["gateway"]).label
167
145
  detail = f"{name} gateway {gw['gateway']['addr']} did not answer; no check through it"
168
146
  checks.append({"check": "gateway", "ok": False, "detail": detail})
169
147
  return checks
170
148
  served: list[AuxEndpoint] = []
171
- wired = set(owned["gateway"]["providers"])
172
- if bifrost:
173
- from localmodels import bifrost_checks
174
-
175
- wired = bifrost_checks.wired_providers(owned)
149
+ wired = gateway.wired_providers(gw, owned)
176
150
  for part in plan.get("aux", []):
177
151
  contract = part["endpoint"].get("contract", "")
178
152
  pid = gateway.AUX_PROVIDERS.get(contract)
@@ -23,8 +23,10 @@ from typing import Any, cast
23
23
 
24
24
  from localmodels import (
25
25
  app,
26
+ deployment_lifecycle,
26
27
  host_sensors,
27
28
  hosts,
29
+ magpie_legacy,
28
30
  metal,
29
31
  stack_lifecycle,
30
32
  stack_run,
@@ -199,7 +201,7 @@ def _state(liveness: tuple[str, str] | None) -> tuple[str, str]:
199
201
  if liveness is None:
200
202
  return "planned", say("state.undeployed")
201
203
  state, health = liveness
202
- if stack_lifecycle.healthy(state, health):
204
+ if deployment_lifecycle.healthy(state, health):
203
205
  return "serving", health
204
206
  return ("failed" if state == "failed" else "stopped"), health
205
207
 
@@ -578,10 +580,10 @@ def read_live(hw: Hardware | None = None) -> Reading:
578
580
  slots: dict[str, list[Slot]] = {}
579
581
  for task, part in parts_of(plan) if plan else []:
580
582
  entry = owned["deployments"].get(part["name"])
581
- if entry is None or entry["removed"]:
583
+ if not deployment_lifecycle.holds_service(entry):
582
584
  continue # planned, or removed by stack remove: nothing of ours to ask
583
585
  liveness[part["name"]] = stack_lifecycle.liveness(part)
584
- if stack_lifecycle.healthy(*liveness[part["name"]]):
586
+ if deployment_lifecycle.healthy(*liveness[part["name"]]):
585
587
  live[task] = part # measured below: what it holds beside what the plan priced
586
588
  if found := read_metrics(part):
587
589
  counters[part["name"]] = found
@@ -589,7 +591,7 @@ def read_live(hw: Hardware | None = None) -> Reading:
589
591
  slots[part["name"]] = ctx
590
592
  magpie = (
591
593
  plan["harness"]["gateway"]["addr"]
592
- if plan and plan["options"].get("gateway", "magpie") == "magpie"
594
+ if plan and magpie_legacy.of_options(plan["options"]).usage_events
593
595
  else None
594
596
  )
595
597
  events, wf = stack_view_events.read_with_waterfall(owned, magpie) if plan else ([], [])
@@ -6,7 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  from typing import TypedDict, cast
8
8
 
9
- from localmodels import stack_journal
9
+ from localmodels import magpie_legacy, stack_journal
10
10
  from localmodels.records import Plan
11
11
  from localmodels.stack_events import APPLY_ORDER as APPLY_ORDER
12
12
  from localmodels.stack_plan import StackPlan
@@ -47,7 +47,7 @@ def _apply_details(plan: StackPlan) -> dict[str, str]:
47
47
  for part in plan.get("aux", []):
48
48
  found[str(part["endpoint"].get("contract") or "aux")] = part["model"]["id"]
49
49
  gate = plan["harness"]["gateway"]
50
- kind = "Bifrost" if plan["options"].get("gateway") == "bifrost" else "Magpie"
50
+ kind = magpie_legacy.of_options(plan["options"]).label
51
51
  found["gateway"] = f"{kind} {gate['addr']}"
52
52
  found["tools"] = " · ".join(
53
53
  t["tool"] for t in plan["harness"]["tools"] if t["action"] not in ("skip", "reuse")
@@ -35,14 +35,19 @@ def llm_parts(part: Plan, window: int | None = None) -> dict[str, int]:
35
35
  if not isinstance(slots, int) or not isinstance(kv_types, list) or len(kv_types) != 2:
36
36
  return {}
37
37
  profile = eager(entry.profile(variant)) # the agent argv has no --lazy-mode
38
- return agent_footprint_parts(
39
- profile,
40
- window or planned,
41
- slots=slots,
42
- kv_types=(str(kv_types[0]), str(kv_types[1])),
43
- ubatch=_int(launch.get("ubatch")) or entry.agent_posture(AGENT).ubatch,
44
- mtp=_int(launch.get("mtp_draft_depth")) > 0,
38
+ parts = dict(
39
+ agent_footprint_parts(
40
+ profile,
41
+ window or planned,
42
+ slots=slots,
43
+ kv_types=(str(kv_types[0]), str(kv_types[1])),
44
+ ubatch=_int(launch.get("ubatch")) or entry.agent_posture(AGENT).ubatch,
45
+ mtp=_int(launch.get("mtp_draft_depth")) > 0,
46
+ )
45
47
  )
48
+ if draft_bytes := _int(launch.get("draft_bytes")):
49
+ parts["draft"] = draft_bytes
50
+ return parts
46
51
 
47
52
 
48
53
  def active_weight_bytes(part: Plan) -> int | None:
@@ -17,7 +17,7 @@ import time
17
17
  from collections.abc import Callable
18
18
  from typing import TextIO
19
19
 
20
- from localmodels import console
20
+ from localmodels import console, magpie_legacy
21
21
  from localmodels.stack_view import Component, Figure, Segment, StackView
22
22
  from localmodels.stack_view_events import Event
23
23
  from localmodels.stack_view_words import say
@@ -334,11 +334,7 @@ def _flow(
334
334
  ),
335
335
  ]
336
336
  who = " · ".join(c["name"] for c in view["clients"]) or say("t.clients")
337
- hub = (
338
- f"{'Bifrost' if gw and gw['kind'] == 'bifrost' else 'Magpie'} {gw['addr']}"
339
- if gw
340
- else say("t.gateway")
341
- )
337
+ hub = f"{magpie_legacy.of(gw).label} {gw['addr']}" if gw else say("t.gateway")
342
338
  lines = [
343
339
  f" {paint(say('t.flow'), bold=True)}",
344
340
  f" {who} ──▶ {paint(hub, bold=True)}"
@@ -20,7 +20,7 @@ import time
20
20
  from pathlib import Path
21
21
  from typing import Any, cast
22
22
 
23
- from localmodels import host_sensors, stack_view_gpu, telemetry_math
23
+ from localmodels import host_sensors, magpie_legacy, stack_view_gpu, telemetry_math
24
24
  from localmodels.stack_view_words import say
25
25
 
26
26
  CACHE_NAME = "stack-view-tick-cache.json"
@@ -480,7 +480,7 @@ def _cold_build(
480
480
  magpie_addr: str | None = None
481
481
  if plan is not None:
482
482
  active_bytes = stack_view_llm.active_weight_bytes(plan["llm"])
483
- if plan["options"].get("gateway", "magpie") == "magpie":
483
+ if magpie_legacy.of_options(plan["options"]).usage_events:
484
484
  magpie_addr = plan["harness"]["gateway"]["addr"]
485
485
  for task, part in stack_view.parts_of(plan):
486
486
  endpoints.append(
@@ -49,7 +49,7 @@ WORDS: dict[str, str] = {
49
49
  "part.kv": "KV cache",
50
50
  "part.state": "Recurrent state",
51
51
  "part.compute": "Compute buffer",
52
- "part.draft": "Draft (MTP)",
52
+ "part.draft": "Draft (speculation)",
53
53
  "part.process": "Process overhead",
54
54
  # the plan sandbox (stack_view_sandbox, GET /api/whatif)
55
55
  "sandbox.none": (
@@ -83,7 +83,10 @@ WORDS: dict[str, str] = {
83
83
  "A fixed state per session for the linear-attention layers; does not grow with context."
84
84
  ),
85
85
  "note.compute": "Scratch tensors of the forward pass; grow with the batch and the window.",
86
- "note.draft": "The MTP draft context: guess a few tokens ahead, then verify them at once.",
86
+ "note.draft": (
87
+ "Speculative decoding: an MTP head or a separate draft model guesses a few tokens ahead,"
88
+ " then the LLM verifies them at once."
89
+ ),
87
90
  "note.process": "The fixed cost of the CUDA context and the engine.",
88
91
  # the rest of a card or of the RAM
89
92
  "seg.foreign": "Other programs",
@@ -41,20 +41,21 @@ import urllib.error
41
41
  import urllib.request
42
42
  from collections.abc import Callable
43
43
  from pathlib import Path
44
- from typing import Literal, TypedDict
44
+ from typing import Literal, TypedDict, cast
45
45
 
46
46
  from localmodels import (
47
47
  cli_help,
48
+ debug_mode,
48
49
  metal,
49
50
  metal_probe,
50
51
  probe,
51
52
  process_identity,
52
53
  process_windows,
53
- stack_up,
54
+ stack_run,
54
55
  stack_verify,
55
56
  stack_warm_store,
56
57
  )
57
- from localmodels.budget import gib
58
+ from localmodels.planning.budget import gib
58
59
  from localmodels.records import Plan
59
60
  from localmodels.stack_plan import StackPlan, command
60
61
 
@@ -400,6 +401,8 @@ def prompt_speed(part: Plan, chat: Prefill = _chat) -> float | None:
400
401
  def warm_llm(part: Plan, chat: Chat = _chat) -> LlmWarm:
401
402
  """Two short requests at the stack's LLM. The first takes whatever is cold; the second is
402
403
  the speed a user gets."""
404
+ if (simulated := debug_mode.simulating()) is not None:
405
+ return cast(LlmWarm, debug_mode.simulated_warm(simulated))
403
406
  seen: LlmWarm = {
404
407
  "name": part["name"],
405
408
  "ok": False,
@@ -629,7 +632,7 @@ def add_parser(actions: argparse._SubParsersAction[argparse.ArgumentParser]) ->
629
632
 
630
633
 
631
634
  def cli(args: argparse.Namespace) -> int:
632
- plan = None if args.host_only else stack_up._accepted()
635
+ plan = None if args.host_only else stack_run.accepted()
633
636
  report = warm(allow_sudo=args.sudo, host_only=args.host_only, plan=plan)
634
637
  if args.json:
635
638
  json.dump(report, sys.stdout, ensure_ascii=False, indent=1)
@@ -29,8 +29,8 @@ from localmodels import (
29
29
  from localmodels import stack_hardware as hardware
30
30
  from localmodels.context_policy import posture_for, window_k
31
31
  from localmodels.contracts import decode
32
- from localmodels.memcalc import parse_size
33
32
  from localmodels.plan_envelope import PlanError
33
+ from localmodels.planning.memcalc import parse_size
34
34
  from localmodels.probe import GPU, HostFacts, Services
35
35
  from localmodels.stack_compose import agent_posture, choose_parts, ram_budget
36
36
  from localmodels.stack_memory import Machine
@@ -1,7 +1,7 @@
1
- """Plans for the stack components that are not catalog llama.cpp LLMs: Strata LLMs and the
1
+ """Recipes for the stack components that are not catalog llama.cpp LLMs: Strata LLMs and the
2
2
  embedding, reranker, STT and TTS servers on the CPU, plus the CUDA engine of a GPU
3
- decision model. Every part is a ``localmodels.deployment-plan/v1`` document that deploy.execute
4
- runs like any other; the recipes, artifacts and launch templates live in the catalog's
3
+ decision model. Every part is a ``localmodels.deployment-plan/v1`` document
4
+ (``engine_adapters.suite_plan.build_plan``) that deploy.execute runs like any other; the recipes, artifacts and launch templates live in the catalog's
5
5
  ``components`` list (``runtime`` strata | strata-poly | llama.cpp-cpu | whisper.cpp-cpu |
6
6
  kokoro-onnx-cpu). A recipe that names a ``venv`` runs in that hash-locked Python
7
7
  environment (frontend.install builds it) instead of a pinned engine build. A strata-poly recipe names both: PolyStrata's Python server (``{python}``, from
@@ -16,15 +16,11 @@ from __future__ import annotations
16
16
  import copy
17
17
  import json
18
18
  import subprocess
19
- import sys
20
- import urllib.parse
21
19
  from dataclasses import dataclass, field
22
20
  from pathlib import Path
23
- from typing import Any, TypedDict, cast
21
+ from typing import TypedDict
24
22
 
25
23
  from localmodels import catalog as cat
26
- from localmodels import hosts, reuse, vision
27
- from localmodels.component import front_venv, venv_python
28
24
  from localmodels.contracts import decode
29
25
  from localmodels.engines import (
30
26
  EngineUnavailableError,
@@ -33,17 +29,9 @@ from localmodels.engines import (
33
29
  release_engine,
34
30
  select_engine_build,
35
31
  )
36
- from localmodels.frontend import MIN_PYTHON
37
- from localmodels.plan_envelope import (
38
- MODELSCOPE_URL,
39
- PlanError,
40
- cpu_threads,
41
- deployment,
42
- plan_envelope,
43
- verified_in_place,
44
- )
32
+ from localmodels.plan_envelope import MODELSCOPE_URL, PlanError
45
33
  from localmodels.probe import GPU, HostFacts
46
- from localmodels.records import Plan, ReleaseEngine, ReusableFile
34
+ from localmodels.records import Plan, ReleaseEngine
47
35
  from localmodels.vision import StrataVision
48
36
 
49
37
  GIB = 1 << 30
@@ -211,322 +199,6 @@ def slice_memory() -> int:
211
199
  return 0
212
200
 
213
201
 
214
- def _engine(r: SuiteRecipe, facts: HostFacts, base_dir: str, backend: str) -> ReleaseEngine:
215
- build = select_engine_build(facts, backend, engine_lock_path(r["engine"]))
216
- return release_engine(build, base_dir)
217
-
218
-
219
- def _venv_engine(r: SuiteRecipe, base_dir: str) -> ReleaseEngine:
220
- """The Python of the recipe's hash-locked venv; the requirements file is its pin. stack is
221
- local-only, so the venv is made from the Python planning runs on."""
222
- if sys.version_info < MIN_PYTHON:
223
- need = ".".join(map(str, MIN_PYTHON))
224
- raise PlanError(
225
- f"its Python environment needs Python {need} or newer; this host has {sys.version.split()[0]}"
226
- )
227
- venv = front_venv(base_dir, r["venv"])
228
- return {"source": "venv", "binary": venv_python(venv), "build": r["venv"], "dir": venv}
229
-
230
-
231
- def _threads(r: SuiteRecipe, facts: HostFacts) -> int:
232
- return int(r["threads"]) if r.get("threads") else cpu_threads(facts)
233
-
234
-
235
- def _formatted(value: object, values: dict[str, str]) -> object:
236
- if isinstance(value, str):
237
- return value.format(**values)
238
- if isinstance(value, list):
239
- return [_formatted(v, values) for v in value]
240
- if isinstance(value, dict):
241
- return {k: _formatted(v, values) for k, v in value.items()}
242
- return value
243
-
244
-
245
- def _reuse(files: list[ReusableFile], specs: list[SuiteFile], roots: tuple[str, ...]) -> None:
246
- """Point each file at a same-size copy under a --reuse-from directory (at its catalog path)
247
- on the destination's filesystem; the download step hard-links it only after the SHA256
248
- matches. A copy elsewhere cannot be linked, so it is not counted as saved download."""
249
- for f, spec in zip(files, specs, strict=True):
250
- for root in roots:
251
- candidate = Path(root).expanduser() / spec["path"]
252
- if (
253
- candidate.is_file()
254
- and candidate.stat().st_size == f["size_bytes"]
255
- and candidate.stat().st_dev == reuse.device(str(Path(f["dest"]).expanduser()))
256
- ):
257
- f["reuse"] = str(candidate)
258
- break
259
-
260
-
261
- def _plan_files(
262
- r: SuiteRecipe, options: SuiteOptions, model_dir: str, reader: str
263
- ) -> list[ReusableFile]:
264
- template = SOURCES[r.get("source", "hf")]
265
- files: list[ReusableFile] = []
266
- specs = [
267
- f for f in cast("list[SuiteFile]", r["files"]) if reader != "off" or not f.get("vision")
268
- ]
269
- for f in specs: # catalog files may name their own source
270
- repo, revision = f.get("repo", r["repo"]), f.get("revision", r["revision"])
271
- url = "" if f.get("derived") else f.get("url") or template
272
- files.append(
273
- {
274
- "repo": repo,
275
- "path": f["path"],
276
- "revision": revision,
277
- "size_bytes": f["size_bytes"],
278
- "sha256": f["sha256"],
279
- "local_name": f.get("local_name", f["path"].rsplit("/", 1)[-1]),
280
- "dest": f"{model_dir}/{f.get('local_name', f['path'])}",
281
- "url": url.format(
282
- hf=options.hf_endpoint,
283
- repo=repo,
284
- revision=revision,
285
- path=urllib.parse.quote(f["path"]),
286
- catalog_dir=cat.CATALOG_PATH.parent,
287
- ),
288
- }
289
- )
290
- if f.get("derived"):
291
- files[-1]["generated"] = True
292
- _reuse(files, specs, options.reuse_from)
293
- missing = [
294
- s["path"]
295
- for f, s in zip(files, specs, strict=True)
296
- if s.get("derived") and not f.get("reuse") and not verified_in_place(f)
297
- ]
298
- if missing and not r.get("preparation"):
299
- raise PlanError(
300
- f"{r['id']} has no pinned preparation recipe for {len(missing)} generated files "
301
- f"(such as {missing[0]}); point --reuse-from at an existing Strata model directory"
302
- )
303
- return files
304
-
305
-
306
- def _profile_template(
307
- facts: HostFacts,
308
- r: SuiteRecipe,
309
- options: SuiteOptions,
310
- files: list[ReusableFile],
311
- values: dict[str, str],
312
- reader: str,
313
- ) -> dict[str, Any]:
314
- """Build the rendered Strata/PolyStrata ``strata-profile.json`` template."""
315
- profile_template = dict(r.get("profile") or {})
316
- if reader != "off":
317
- projector = next(f for f in files if f["local_name"] == r["vision"]["mmproj"])
318
- values["vision_mmproj"] = projector["dest"]
319
- cores = int(facts.get("cpu", {}).get("logical_cores") or 2)
320
- profile_template["vision"] = vision.strata_section(reader, cores, exe="{vision_exe}")
321
- if r["runtime"] == "strata":
322
- profile_template["args"] = [*cast("list[str]", profile_template["args"]), "--vision"]
323
- if options.gpu and r.get("card_args"):
324
- # Under --gpu-memory the reserve also holds what the share leaves out of the real card
325
- # (stack_gpu_memory.LEFT_OUT, stack_suite.poly_reserve_mib), so the room is counted on it.
326
- left_out = int(cast("dict[str, int]", options.gpu).get("share_left_out_bytes", 0))
327
- room = options.gpu["total_bytes"] + left_out - (options.vram_reserve_mib << 20)
328
- profile_template["args"] = [
329
- *cast("list[str]", profile_template["args"]),
330
- *(
331
- a
332
- for group in r["card_args"]
333
- if room >= group["at_least_bytes"]
334
- and facts["platform"] in group.get("platforms", [facts["platform"]])
335
- for a in group["args"]
336
- ),
337
- ]
338
- if options.reasoning_budget and r["runtime"] == "strata":
339
- # strata-<model>.json's default for requests that name none (Strata DETAILS, v0.2.4).
340
- profile_template["reasoning_budget_tokens"] = options.reasoning_budget
341
- if r["runtime"] == "strata-poly":
342
- # PolyStrata's server enables prompt-start warm-up only when opt-in warm_start is true,
343
- # and maps parallel: 2 to --batch 2 (WHI-1059 / WHI-1012).
344
- profile_template.setdefault("warm_start", True)
345
- profile_template.setdefault("parallel", 2)
346
- return profile_template
347
-
348
-
349
- def build_plan(host_id: str, facts: HostFacts, r: SuiteRecipe, options: SuiteOptions) -> Plan:
350
- """The deployment plan for one suite component from its catalog template."""
351
- base = options.base_dir.rstrip("/")
352
- on_gpu = r["runtime"] in STRATA_RUNTIMES or bool(r.get("vram_bytes"))
353
- if on_gpu and options.gpu is None:
354
- raise PlanError(f"{r['id']} needs an idle NVIDIA GPU")
355
- apple = facts["platform"] == "darwin" and facts["arch"] == "arm64"
356
- _check_runtime(facts, r)
357
- backend = ("metal" if apple else "cuda") if on_gpu else "cpu"
358
- engine = _engine(r, facts, base, backend) if r.get("engine") else _venv_engine(r, base)
359
- model_dir = f"{base}/models/{r['id']}"
360
- reader = options.vision_reader if r.get("vision") else "off"
361
- files = _plan_files(r, options, model_dir, reader)
362
- port = options.port or int(r.get("port") or 0)
363
- where = deployment(r["id"], port, base, taken=hosts.deployment_dirs(host_id))
364
- threads = _threads(r, facts)
365
- values = {
366
- "engine": engine["binary"],
367
- "engine_dir": engine["dir"],
368
- "vision_exe": f"{engine['dir']}/strata-vision.exe"
369
- if facts["platform"] == "win32"
370
- else f"{engine['dir']}/strata-vision",
371
- "model_dir": model_dir,
372
- "hf_endpoint": options.hf_endpoint,
373
- "model": files[0]["dest"] if files else model_dir,
374
- "weights_sha256": files[0]["sha256"] if files else "",
375
- "alias": r.get("alias", r["id"]),
376
- "port": str(where.port),
377
- "key_file": where.api_key_file,
378
- "deploy_dir": where.deploy_dir,
379
- "threads": str(threads),
380
- "gpu_uuid": options.gpu["uuid"] if options.gpu else "",
381
- "vram_reserve_mib": str(options.vram_reserve_mib),
382
- "expert_cache": options.expert_cache,
383
- "auth_proxy": f"{where.deploy_dir}/{AUTH_PROXY}",
384
- "tts_server": f"{where.deploy_dir}/{TTS_SERVER}",
385
- "poly_server": f"{where.deploy_dir}/{POLY_SERVER}",
386
- "python": venv_python(front_venv(base, r["venv"])) if r.get("venv") else "",
387
- }
388
- parking = r.get("conversation_cache")
389
- parking_mib = options.conversation_cache_mib if parking else 0
390
- reader_ram_mib = vision.strata_ram_mib(r.get("vision") or {}, reader)
391
- profile_template = _profile_template(facts, r, options, files, values, reader)
392
- if parking:
393
- values |= {
394
- "conversation_cache_mib": str(parking_mib),
395
- "conversation_cache_slots": str(parking["slots"]),
396
- "conversation_cache_min_free_mib": str(parking["min_free_mib"]),
397
- "conversation_cache_min_tokens": str(parking["min_tokens"]),
398
- }
399
- argv = [a.format(**values) for a in r["argv"]]
400
- argv[0] = (
401
- sys.executable
402
- if host_id == hosts.LOCAL_ID and r.get("auth_proxy") and argv[0] == "python3"
403
- else argv[0]
404
- )
405
- if apple and r["runtime"] in ("llama.cpp", "llama.cpp-cpu"):
406
- argv += ["--device", "MTL0" if on_gpu else "none"]
407
- env = {k: v.format(**values) for k, v in r.get("env", {}).items()}
408
- env.setdefault("CUDA_VISIBLE_DEVICES", values["gpu_uuid"])
409
- if r["runtime"] in ("llama.cpp-cpu", "whisper.cpp-cpu") or (
410
- on_gpu and r["runtime"] not in STRATA_RUNTIMES
411
- ):
412
- env.setdefault("LD_LIBRARY_PATH", engine["dir"])
413
- if apple:
414
- env.pop("CUDA_VISIBLE_DEVICES", None)
415
- env.pop("LD_LIBRARY_PATH", None)
416
- # Parked conversations live in the engine's own cgroup, so the budget raises its ceilings.
417
- added_mib = parking_mib + reader_ram_mib
418
- limits = {
419
- k: f"{(size_bytes(v) >> 20) + added_mib}M"
420
- if added_mib and k in ("MemoryHigh", "MemoryMax")
421
- else v
422
- for k, v in {**r.get("limits", {}), **NO_SWAP}.items()
423
- }
424
- label = f"GPU {options.gpu['index']}" if on_gpu and options.gpu else f"CPU {threads} threads"
425
- gpus = (
426
- [{"index": options.gpu["index"], "uuid": options.gpu["uuid"], "name": options.gpu["name"]}]
427
- if on_gpu and options.gpu
428
- else []
429
- )
430
- plan = plan_envelope(
431
- host_id,
432
- facts,
433
- where,
434
- model={
435
- "id": r["id"],
436
- "display_name": r.get("display_name") or f"{r.get('alias', r['id'])} ({r['runtime']})",
437
- "repo": r["repo"],
438
- "quant": r["version"],
439
- "model_id": r.get("alias", r["id"]),
440
- "validated": r.get("status") == "validated",
441
- },
442
- files=files,
443
- engine=engine,
444
- placement={
445
- "id": "gpu" if on_gpu else "cpu",
446
- "label": label,
447
- "pooled": False,
448
- "gpus": gpus,
449
- },
450
- launch={
451
- "window": r.get("context", 0),
452
- "spilled": False,
453
- "spill_bytes": 0,
454
- "reasons": [r.get("note", "")],
455
- "threads": threads,
456
- "memory_estimate_bytes": r["memory_estimate_bytes"] + (added_mib << 20),
457
- "vram_bytes": r.get("vram_bytes", 0)
458
- + (vision.strata_gpu_mib(r.get("vision") or {}, reader) << 20),
459
- **(
460
- {"preparation": _formatted(r["preparation"], values)}
461
- if r.get("preparation")
462
- else {}
463
- ),
464
- **({"conversation_cache_mib": parking_mib} if parking else {}),
465
- **_profile_launch(r["runtime"], profile_template),
466
- **({"vision": reader} if reader != "off" else {}),
467
- # The same keys as a decision front's: stack apply builds the venv before the unit.
468
- **(
469
- {
470
- "frontend_requirements": r["venv"],
471
- "frontend_base_dir": options.base_dir,
472
- "frontend_bytes": r.get("venv_bytes", 0),
473
- }
474
- if r.get("venv")
475
- else {}
476
- ),
477
- },
478
- service={
479
- "argv": argv,
480
- "env": env,
481
- "limits": limits,
482
- "slice": SLICE,
483
- "slice_limits": {**options.slice_limits, **NO_SWAP},
484
- },
485
- endpoint={"model": r.get("alias", r["id"]), "contract": r.get("contract", "chat")},
486
- warnings=[],
487
- )
488
- config: dict[str, str] = {}
489
- if profile_template:
490
- profile = _formatted(profile_template, values)
491
- config[f"{where.deploy_dir}/strata-profile.json"] = json.dumps(profile, indent=1) + "\n"
492
- if r.get("auth_proxy"):
493
- config[values["auth_proxy"]] = (PACKAGE_DIR / AUTH_PROXY).read_text(encoding="utf-8")
494
- if server := SERVERS.get(r["runtime"]):
495
- config[f"{where.deploy_dir}/{server}"] = (PACKAGE_DIR / server).read_text(encoding="utf-8")
496
- if config:
497
- plan["service"]["config_files"] = config
498
- if r.get("health_path"):
499
- plan["service"]["health_path"] = r["health_path"]
500
- _readiness(plan, r)
501
- return plan
502
-
503
-
504
- def _profile_launch(runtime: str, profile: dict[str, object]) -> dict[str, object]:
505
- if runtime not in STRATA_RUNTIMES:
506
- return {}
507
- launch: dict[str, object] = {"slots": int(str(profile.get("parallel") or 1))}
508
- args = cast("list[str]", profile.get("args") or [])
509
- if "--mtp" in args and "--spec" in args:
510
- launch["mtp_draft_depth"] = int(args[args.index("--spec") + 1])
511
- return launch
512
-
513
-
514
- def _readiness(plan: Plan, r: SuiteRecipe) -> None:
515
- """What the readiness check needs beyond the contract: its input, time and token limit."""
516
- if r.get("fixture"):
517
- plan["fixture"] = r["fixture"]
518
- if r.get("verify_timeout_s"):
519
- plan["verify_timeout_s"] = r["verify_timeout_s"]
520
- if r.get("input_tokens"):
521
- plan["input_tokens"] = r["input_tokens"]
522
-
523
-
524
- def _check_runtime(facts: HostFacts, recipe: SuiteRecipe) -> None:
525
- # PolyStrata's strata-poly has a Metal build; Strata's own engine is CUDA only.
526
- if facts["platform"] == "darwin" and recipe["runtime"] == "strata":
527
- raise PlanError("Strata recipes need CUDA and cannot run on Apple Silicon Metal")
528
-
529
-
530
202
  def cuda_decision_engine(
531
203
  facts: HostFacts, argv: list[str], base_dir: str, notes: list[str], *, metal: bool = False
532
204
  ) -> ReleaseEngine: