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

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 (153) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +126 -0
  3. package/README.md +10 -0
  4. package/bootstrap.identity +1 -1
  5. package/bootstrap.sha256 +139 -121
  6. package/modules/localmodels/__init__.py +1 -1
  7. package/modules/localmodels/__main__.py +3 -1
  8. package/modules/localmodels/catalog.json +435 -127
  9. package/modules/localmodels/catalog.py +7 -3
  10. package/modules/localmodels/catalog_recipes.py +3 -3
  11. package/modules/localmodels/cli_parser.py +7 -3
  12. package/modules/localmodels/component.py +1 -1
  13. package/modules/localmodels/console.py +1 -1
  14. package/modules/localmodels/context_policy.py +6 -5
  15. package/modules/localmodels/debug_cli.py +0 -12
  16. package/modules/localmodels/debug_mode.py +0 -6
  17. package/modules/localmodels/debug_stub_server.py +280 -7
  18. package/modules/localmodels/decode_calibration.json +3 -4
  19. package/modules/localmodels/decode_calibration.py +5 -2
  20. package/modules/localmodels/deployment_lifecycle.py +1 -1
  21. package/modules/localmodels/download-mirrors.json +77 -1
  22. package/modules/localmodels/engine_adapters/base.py +11 -1
  23. package/modules/localmodels/engine_adapters/strata_poly.py +65 -3
  24. package/modules/localmodels/engine_adapters/suite_plan.py +57 -20
  25. package/modules/localmodels/engines-b11583.json +6 -26
  26. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +3 -15
  27. package/modules/localmodels/engines-b12757-mix-ef2df21.json +3 -15
  28. package/modules/localmodels/engines-prism-b12178-03ec600.json +3 -15
  29. package/modules/localmodels/engines-speechcpp-v0.11.3.json +68 -0
  30. package/modules/localmodels/engines-strata-0.1.47.json +1 -5
  31. package/modules/localmodels/engines-strata-0.1.49.2.json +1 -5
  32. package/modules/localmodels/engines-strata-0.1.59.1.json +1 -5
  33. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +6 -30
  34. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +129 -0
  35. package/modules/localmodels/engines-whisper-b5454.json +6 -30
  36. package/modules/localmodels/engines.json +13 -61
  37. package/modules/localmodels/estimator.py +10 -5
  38. package/modules/localmodels/gpu_specs.py +1 -1
  39. package/modules/localmodels/hosts.py +12 -16
  40. package/modules/localmodels/kokoro-tts-0.6.1.txt +1 -1
  41. package/modules/localmodels/library_elastic.py +135 -6
  42. package/modules/localmodels/library_kept.py +9 -1
  43. package/modules/localmodels/library_model.py +28 -1
  44. package/modules/localmodels/library_poly.py +109 -11
  45. package/modules/localmodels/library_pricing.py +12 -3
  46. package/modules/localmodels/library_serve.py +162 -75
  47. package/modules/localmodels/library_smoke.py +63 -5
  48. package/modules/localmodels/library_state.py +3 -2
  49. package/modules/localmodels/library_status.py +8 -1
  50. package/modules/localmodels/llm_rank.py +13 -8
  51. package/modules/localmodels/metal.py +1 -2
  52. package/modules/localmodels/plan_envelope.py +29 -11
  53. package/modules/localmodels/planning/budget.py +14 -12
  54. package/modules/localmodels/planning/memory_pools.py +7 -1
  55. package/modules/localmodels/privacy_acceptance.py +6 -5
  56. package/modules/localmodels/py.typed +0 -0
  57. package/modules/localmodels/quant_formats.py +1 -1
  58. package/modules/localmodels/recommend_cli.py +1 -1
  59. package/modules/localmodels/remote_ops_common.py +12 -2
  60. package/modules/localmodels/remote_ops_launchd.py +8 -1
  61. package/modules/localmodels/runtime_process.py +1 -1
  62. package/modules/localmodels/service_deployment.py +2 -4
  63. package/modules/localmodels/service_probe.py +59 -13
  64. package/modules/localmodels/setup_inspection.py +72 -70
  65. package/modules/localmodels/setup_text.py +7 -56
  66. package/modules/localmodels/sidecar_downloads.py +460 -0
  67. package/modules/localmodels/sidecar_http.py +452 -0
  68. package/modules/localmodels/sidecar_state.py +516 -0
  69. package/modules/localmodels/speech_admission.py +33 -4
  70. package/modules/localmodels/speech_catalog.py +23 -0
  71. package/modules/localmodels/speech_cli.py +10 -2
  72. package/modules/localmodels/speech_jobs.py +120 -384
  73. package/modules/localmodels/speech_server.py +187 -77
  74. package/modules/localmodels/speech_state.py +90 -454
  75. package/modules/localmodels/speech_workers.py +51 -162
  76. package/modules/localmodels/stack.py +18 -0
  77. package/modules/localmodels/stack_args.py +6 -6
  78. package/modules/localmodels/stack_auto.py +1 -1
  79. package/modules/localmodels/stack_aux_gpu.py +1 -1
  80. package/modules/localmodels/stack_cleanup.py +21 -18
  81. package/modules/localmodels/stack_cli.py +6 -2
  82. package/modules/localmodels/stack_compose.py +11 -4
  83. package/modules/localmodels/stack_debug.py +1 -2
  84. package/modules/localmodels/stack_decision.py +4 -4
  85. package/modules/localmodels/stack_doctor.py +2 -2
  86. package/modules/localmodels/stack_down.py +19 -14
  87. package/modules/localmodels/stack_events.py +1 -1
  88. package/modules/localmodels/stack_gpu_memory.py +1 -1
  89. package/modules/localmodels/stack_hardware.py +3 -3
  90. package/modules/localmodels/stack_mcp.py +1 -2
  91. package/modules/localmodels/stack_picks.py +1 -1
  92. package/modules/localmodels/stack_plan.py +9 -9
  93. package/modules/localmodels/stack_ports.py +32 -4
  94. package/modules/localmodels/stack_rollback.py +1 -1
  95. package/modules/localmodels/stack_run.py +1 -1
  96. package/modules/localmodels/stack_suite.py +61 -12
  97. package/modules/localmodels/stack_up.py +51 -1
  98. package/modules/localmodels/stack_view_agent.py +1 -1
  99. package/modules/localmodels/stack_view_serve.py +0 -2
  100. package/modules/localmodels/stack_view_words.py +2 -2
  101. package/modules/localmodels/stack_warm.py +2 -2
  102. package/modules/localmodels/stack_whatif.py +524 -41
  103. package/modules/localmodels/stack_whatif_html.py +903 -0
  104. package/modules/localmodels/startlux-decide-83fe6c7d.txt +2 -2
  105. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.7.txt → strata-poly-serve-0.2.20-poly.9.txt} +1 -1
  106. package/modules/localmodels/strata_poly_server.py +251 -3
  107. package/modules/localmodels/suite.py +137 -5
  108. package/modules/localmodels/tts-moss.txt +321 -0
  109. package/modules/localmodels/tts_admission.py +381 -0
  110. package/modules/localmodels/tts_backend_speechcpp.py +487 -0
  111. package/modules/localmodels/tts_catalog.py +279 -0
  112. package/modules/localmodels/tts_cli.py +352 -0
  113. package/modules/localmodels/tts_http.py +623 -0
  114. package/modules/localmodels/tts_jobs.py +526 -0
  115. package/modules/localmodels/tts_model.py +591 -0
  116. package/modules/localmodels/tts_moss_presets.json +1 -0
  117. package/modules/localmodels/tts_serve.py +451 -0
  118. package/modules/localmodels/tts_server.py +1 -1
  119. package/modules/localmodels/tts_sidecar.py +788 -0
  120. package/modules/localmodels/tts_state.py +400 -0
  121. package/modules/localmodels/tts_worker_kokoro.py +463 -0
  122. package/modules/localmodels/tts_worker_moss.py +748 -0
  123. package/modules/localmodels/tts_workers.py +696 -0
  124. package/modules/localmodels/vision.py +5 -3
  125. package/modules/localmodels/web/view/ASSET-SOURCES.md +4 -7
  126. package/modules/localmodels/web/view/view.css +0 -1
  127. package/modules/localmodels/web/view/view.js +2 -5
  128. package/modules/localmodels/web/whatif/app.js +730 -0
  129. package/modules/localmodels/web/whatif/page.html +1172 -0
  130. package/modules/localmodels/web/whatif/sim.js +303 -0
  131. package/modules/localmodels/windows_job.py +179 -11
  132. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/METADATA +14 -0
  133. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/RECORD +132 -109
  134. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/LICENSE +201 -0
  135. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/NOTICE +126 -0
  136. package/package.json +11 -2
  137. package/tool.json +1 -1
  138. package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +0 -94
  139. package/modules/localmodels/fixtures/stack-research-demo-plan.json +0 -1059
  140. package/modules/localmodels/stack_research.py +0 -716
  141. package/modules/localmodels/stack_research_demo.py +0 -125
  142. package/modules/localmodels/stack_research_plan.py +0 -146
  143. package/modules/localmodels/web/index.html +0 -2605
  144. package/modules/localmodels/web/sizecalc/app.js +0 -1306
  145. package/modules/localmodels/web/sizecalc/calc.js +0 -269
  146. package/modules/localmodels/web/sizecalc/page.html +0 -520
  147. package/modules/localmodels/web/view/logo-claude.svg +0 -3
  148. package/modules/localmodels/web/view/logo-codex.png +0 -0
  149. package/modules/simplex_localmodels-0.1.0.dev102.dist-info/METADATA +0 -9
  150. package/modules/simplex_localmodels-0.1.0.dev102.dist-info/licenses/NOTICE +0 -68
  151. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/WHEEL +0 -0
  152. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/entry_points.txt +0 -0
  153. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -1,6 +1,6 @@
1
1
  # startlux-decide 1.1.0 (StartLuxLabs/StartLux-Decision@83fe6c7d61a687a6e17f118b4f7d8f429f5d3a01, code
2
2
  # Apache-2.0) for the llama.cpp backend of a StartLux Instant decision front, with the aiohttp and
3
- # transformers versions measured with it on lab-12021 (2026-10-20 and 2026-10-22). Installed by
3
+ # transformers versions verified on reference Linux CUDA hardware. Installed by
4
4
  # localmodels/frontend.py with pip --require-hashes --no-deps. Regenerate the pinned dependencies with
5
5
  # uv pip compile --universal --python-version 3.10 --generate-hashes --no-header --no-annotate
6
6
  # from "aiohttp==3.14.5" and "transformers==5.20.2". The source archive is 110 MB (it carries the
@@ -8,7 +8,7 @@
8
8
  # jinja2 and MarkupSafe were appended on 2026-10-29, compiled the same way from "jinja2" alone:
9
9
  # transformers' apply_chat_template needs jinja2, which neither startlux-decide nor transformers
10
10
  # requires, so without it the front exits on its first request
11
- # (evidence/2026-10-29-stack-macos-metal-tiers).
11
+ # (verified on macOS Metal).
12
12
  startlux-decide @ https://github.com/StartLuxLabs/StartLux-Decision/archive/83fe6c7d61a687a6e17f118b4f7d8f429f5d3a01.tar.gz \
13
13
  --hash=sha256:b1c15f6b2f104f02955008f38a74ebf72b282da8a165ae97dac4b8ce4570ce90
14
14
  aiohappyeyeballs==2.7.1 \
@@ -1,4 +1,4 @@
1
- # PolyStrata 0.2.20-poly.7's Python server (terminal/serve/server.py, MIT) for strata-poly LLM
1
+ # PolyStrata 0.2.20-poly.9's Python server (terminal/serve/server.py, MIT) for strata-poly LLM
2
2
  # recipes: jinja2 3.1.6 (BSD-3-Clause) with markupsafe 3.0.3 (BSD-3-Clause) renders the chat
3
3
  # template, regex 2026.9.10 (Apache-2.0 and CNRI-Python) drives its tokenizer, psutil 7.2.2
4
4
  # (BSD-3-Clause) reads memory for its status page, and pillow (MIT-CMU; 13.0.0 on Python 3.11+,
@@ -12,7 +12,10 @@ the server:
12
12
  2. The serve profile ``stack plan`` wrote names paths under ``~`` when the stack uses its
13
13
  default directory, and PolyStrata takes them literally, so a copy with every such path
14
14
  expanded (``strata-profile.resolved.json``) is what the server reads.
15
- 3. ``serve/server.py --engine strata --config <resolved profile>`` runs inside this process
15
+ 3. Under Windows that copy's ``--vram-reserve-mib`` is read off the card as it is now
16
+ (``for_windows``): the engine sizes its VRAM from CUDA's free memory, which under WDDM does
17
+ not count other programs.
18
+ 4. ``serve/server.py --engine strata --config <resolved profile>`` runs inside this process
16
19
  (``runpy``), so the unit's signals and exit status are the server's while the command line
17
20
  stays the one the deployment records: service discovery tells this tool's own engine from
18
21
  someone else's by matching a GPU process's ancestors against that recorded command.
@@ -21,6 +24,7 @@ the server:
21
24
  from __future__ import annotations
22
25
 
23
26
  import argparse
27
+ import ctypes
24
28
  import json
25
29
  import os
26
30
  import runpy
@@ -28,6 +32,116 @@ import shutil
28
32
  import subprocess
29
33
  import sys
30
34
  from pathlib import Path
35
+ from typing import Any, cast
36
+
37
+ _JOB_LIMIT_AFFINITY = 0x0010 # JOB_OBJECT_LIMIT_AFFINITY
38
+ _BASIC_LIMITS = 2 # JobObjectBasicLimitInformation
39
+ _AFFINITY_ENV = "LOCALMODELS_POLY_CPU_AFFINITY"
40
+ _DISABLE_VALUES = frozenset(("0", "off", "false", "none"))
41
+ _AFFINITY_JOBS: list[Any] = [] # kept open for the server's lifetime; no kill-on-close
42
+
43
+
44
+ def _reserved_speech_cores(logical_cores: int) -> int:
45
+ """Keep the same core-reservation rule as ``localmodels.windows_job`` (standalone copy)."""
46
+ if logical_cores >= 12:
47
+ return 4
48
+ if logical_cores >= 6:
49
+ return 2
50
+ return 0
51
+
52
+
53
+ def poly_affinity_mask(available_mask: int, override: str | None = None) -> int | None:
54
+ """Return the Windows CPU affinity mask for PolyStrata (excluding reserved speech cores).
55
+
56
+ Reserves the highest-index logical CPUs (keeping CPU 0 and Intel P-cores with PolyStrata
57
+ while guaranteeing a PolyStrata-free slice for CPU speech workers). Returns ``None`` when
58
+ disabled via ``LOCALMODELS_POLY_CPU_AFFINITY=off`` or when fewer than 6 CPUs are available.
59
+ """
60
+ if available_mask <= 0:
61
+ return None
62
+ if override is not None:
63
+ cleaned = override.strip().lower()
64
+ if cleaned:
65
+ if cleaned in _DISABLE_VALUES:
66
+ return None
67
+ try:
68
+ parsed = int(cleaned, 0)
69
+ except ValueError:
70
+ return None
71
+ clamped = parsed & available_mask
72
+ return clamped if clamped > 0 else None
73
+ cpus = [bit for bit in range(available_mask.bit_length()) if available_mask & (1 << bit)]
74
+ reserve = _reserved_speech_cores(len(cpus))
75
+ if reserve <= 0 or len(cpus) <= reserve:
76
+ return None
77
+ speech_mask = sum(1 << bit for bit in cpus[-reserve:])
78
+ poly_mask = available_mask & ~speech_mask
79
+ return poly_mask if poly_mask > 0 else None
80
+
81
+
82
+ def apply_windows_cpu_affinity() -> int | None:
83
+ """Windows: restrict this launcher and its child ``strata-poly.exe`` to ``poly_affinity_mask``.
84
+
85
+ Prefers a Windows Job Object with ``JOB_OBJECT_LIMIT_AFFINITY`` (without kill-on-close) so
86
+ the kernel enforces the mask across the whole process tree, falling back to
87
+ ``SetProcessAffinityMask`` when nested job assignment is rejected. Returns the applied mask
88
+ or ``None`` off Windows / when skipped.
89
+ """
90
+ if sys.platform != "win32":
91
+ return None
92
+ from ctypes import wintypes
93
+
94
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
95
+ handle_t, ptr_size_t = wintypes.HANDLE, ctypes.POINTER(ctypes.c_size_t)
96
+ specs: tuple[tuple[str, tuple[Any, ...], Any], ...] = (
97
+ ("GetCurrentProcess", (), handle_t),
98
+ ("GetProcessAffinityMask", (handle_t, ptr_size_t, ptr_size_t), wintypes.BOOL),
99
+ ("SetProcessAffinityMask", (handle_t, ctypes.c_size_t), wintypes.BOOL),
100
+ ("CreateJobObjectW", (ctypes.c_void_p, wintypes.LPCWSTR), handle_t),
101
+ (
102
+ "SetInformationJobObject",
103
+ (handle_t, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD),
104
+ wintypes.BOOL,
105
+ ),
106
+ ("AssignProcessToJobObject", (handle_t, handle_t), wintypes.BOOL),
107
+ ("CloseHandle", (handle_t,), wintypes.BOOL),
108
+ )
109
+ for name, argtypes, restype in specs:
110
+ fn = getattr(kernel, name)
111
+ fn.argtypes, fn.restype = argtypes, restype
112
+
113
+ current = kernel.GetCurrentProcess()
114
+ proc_mask, sys_mask = ctypes.c_size_t(0), ctypes.c_size_t(0)
115
+ if not kernel.GetProcessAffinityMask(current, ctypes.byref(proc_mask), ctypes.byref(sys_mask)):
116
+ return None
117
+ target_mask = poly_affinity_mask(int(proc_mask.value), os.environ.get(_AFFINITY_ENV))
118
+ if target_mask is None:
119
+ return None
120
+
121
+ class _JobBasicLimits(ctypes.Structure):
122
+ _fields_ = [
123
+ ("per_process_user_time", ctypes.c_int64),
124
+ ("per_job_user_time", ctypes.c_int64),
125
+ ("limit_flags", wintypes.DWORD),
126
+ ("min_working_set", ctypes.c_size_t),
127
+ ("max_working_set", ctypes.c_size_t),
128
+ ("active_process_limit", wintypes.DWORD),
129
+ ("affinity", ctypes.c_size_t),
130
+ ("priority_class", wintypes.DWORD),
131
+ ("scheduling_class", wintypes.DWORD),
132
+ ]
133
+
134
+ job = kernel.CreateJobObjectW(None, None)
135
+ if job:
136
+ limits = _JobBasicLimits(limit_flags=_JOB_LIMIT_AFFINITY, affinity=target_mask)
137
+ if kernel.SetInformationJobObject(
138
+ job, _BASIC_LIMITS, ctypes.byref(limits), ctypes.sizeof(limits)
139
+ ) and kernel.AssignProcessToJobObject(job, current):
140
+ _AFFINITY_JOBS.append(job)
141
+ return target_mask
142
+ kernel.CloseHandle(job)
143
+
144
+ return target_mask if kernel.SetProcessAffinityMask(current, target_mask) else None
31
145
 
32
146
 
33
147
  def source_root(engine_dir: Path) -> Path:
@@ -97,12 +211,145 @@ def planning_home(profile: dict[str, object], deploy_dir: Path) -> str:
97
211
  return os.path.expanduser("~")
98
212
 
99
213
 
214
+ RESERVE_FLAG = "--vram-reserve-mib"
215
+ BEFORE_CACHE_KEY = "vram_before_cache_mib"
216
+ WINDOWS = os.name == "nt"
217
+
218
+ # Run in a child Python so no CUDA context outlives it in the server's process; argv: the planned
219
+ # reserve and the VRAM the engine takes before its cache, in MiB. On the engine's card (CUDA
220
+ # device 0 under the unit's CUDA_VISIBLE_DEVICES) it reads NVML's free memory, which counts every
221
+ # process, then allocates as the engine does and prints the free memory CUDA reports to a process
222
+ # holding the second figure, or, when that is 0, holding all the engine may take (the card's free
223
+ # less the planned reserve).
224
+ CARD_PROBE = r"""
225
+ import ctypes, json, os, sys, time
226
+ planned, before = int(sys.argv[1]), int(sys.argv[2])
227
+ nvml = None
228
+ for name in ("nvml.dll", os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"),
229
+ "NVIDIA Corporation", "NVSMI", "nvml.dll")):
230
+ try:
231
+ nvml = ctypes.WinDLL(name)
232
+ break
233
+ except OSError:
234
+ pass
235
+ cuda = ctypes.WinDLL("nvcuda.dll")
236
+ dev, ctx, uuid = ctypes.c_int(), ctypes.c_void_p(), (ctypes.c_ubyte * 16)()
237
+ assert cuda.cuInit(0) == 0 and cuda.cuDeviceGet(ctypes.byref(dev), 0) == 0
238
+ assert cuda.cuDeviceGetUuid_v2(uuid, dev) == 0
239
+ b = bytes(uuid)
240
+ name = "GPU-%s-%s-%s-%s-%s" % (b[:4].hex(), b[4:6].hex(), b[6:8].hex(), b[8:10].hex(), b[10:].hex())
241
+ class Mem(ctypes.Structure):
242
+ _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]
243
+ mem, card = Mem(), ctypes.c_void_p()
244
+ assert nvml.nvmlInit_v2() == 0
245
+ assert nvml.nvmlDeviceGetHandleByUUID(name.encode(), ctypes.byref(card)) == 0
246
+ assert nvml.nvmlDeviceGetMemoryInfo(card, ctypes.byref(mem)) == 0
247
+ nvml.nvmlShutdown()
248
+ target = (mem.free >> 20) - planned
249
+ assert cuda.cuDevicePrimaryCtxRetain(ctypes.byref(ctx), dev) == 0
250
+ out, chunks = {"card_free_mib": mem.free >> 20}, []
251
+ def hold(mib):
252
+ held = 256 * len(chunks)
253
+ while held + 256 <= mib:
254
+ ptr = ctypes.c_uint64()
255
+ if cuda.cuMemAlloc_v2(ctypes.byref(ptr), ctypes.c_size_t(256 << 20)) != 0:
256
+ break
257
+ chunks.append(ptr)
258
+ assert cuda.cuMemsetD8_v2(ptr, ctypes.c_ubyte(0), ctypes.c_size_t(256 << 20)) == 0
259
+ held += 256
260
+ assert cuda.cuCtxSynchronize() == 0
261
+ time.sleep(1.0)
262
+ free, total = ctypes.c_size_t(), ctypes.c_size_t()
263
+ assert cuda.cuMemGetInfo_v2(ctypes.byref(free), ctypes.byref(total)) == 0
264
+ return held, free.value >> 20
265
+ try:
266
+ assert cuda.cuCtxSetCurrent(ctx) == 0
267
+ if 0 < before < target:
268
+ out["before_held_mib"], out["before_cuda_free_mib"] = hold(before)
269
+ else:
270
+ out["held_mib"], out["cuda_free_mib"] = hold(target)
271
+ finally:
272
+ for ptr in chunks:
273
+ cuda.cuMemFree_v2(ptr)
274
+ cuda.cuDevicePrimaryCtxRelease(dev)
275
+ print(json.dumps(out))
276
+ """
277
+
278
+
279
+ def windows_reserve_mib(planned: int, before: int) -> int:
280
+ """``--vram-reserve-mib`` for strata-poly under Windows, so that the engine takes what the
281
+ card has free less ``planned``, ``before`` being the VRAM it takes ahead of its cache.
282
+
283
+ The engine fills its cache (or its ``--vram-pool``) to what CUDA reports free less the
284
+ reserve. Under WDDM that figure is the process's budget less its own use, not the card's
285
+ free memory: on a reference RTX 4060 Ti 16 GB (Windows WDDM) a process holding nothing was told
286
+ 15,223 MiB both idle and with another program holding 8,000 MiB (NVML: 14,804 and 6,685).
287
+ With such a program there the budget also shrinks once the process holds about 2.5 GiB, by
288
+ about a MiB for each MiB more, until Windows moves one of them to system memory (decoding
289
+ then fell to about 5 tokens/s). So the reserve is read off that budget: what CUDA reports to
290
+ a process holding ``before`` (what the engine sees when it fills its cache), less the cache
291
+ it may have. Without ``before`` it is what CUDA reports to a process holding all the engine
292
+ may take, which leaves the engine ``before`` over. On a card nothing else uses, the reserve
293
+ stays ``planned`` (reference 16 GB WDDM: 643 MiB computed, 1,280 kept). ``planned`` also when the card
294
+ cannot be read: the plan's reserve stands."""
295
+ try:
296
+ done = subprocess.run(
297
+ [sys.executable, "-I", "-c", CARD_PROBE, str(planned), str(before)],
298
+ capture_output=True,
299
+ text=True,
300
+ timeout=120,
301
+ check=False,
302
+ )
303
+ views = json.loads(done.stdout.strip().splitlines()[-1])
304
+ target = int(views["card_free_mib"]) - planned
305
+ if "before_cuda_free_mib" in views:
306
+ fill = int(views["before_cuda_free_mib"]) - (target - int(views["before_held_mib"]))
307
+ else:
308
+ fill = int(views["cuda_free_mib"])
309
+ reserve = max(planned, fill)
310
+ except (OSError, subprocess.SubprocessError, ValueError, LookupError, TypeError):
311
+ print(
312
+ "strata_poly_server: could not read the card's free VRAM; keeping the planned "
313
+ f"{RESERVE_FLAG} {planned}",
314
+ file=sys.stderr,
315
+ )
316
+ return planned
317
+ held = views.get("before_held_mib", views.get("held_mib"))
318
+ cuda_free = views.get("before_cuda_free_mib", views.get("cuda_free_mib"))
319
+ print(
320
+ f"strata_poly_server: the card has {views['card_free_mib']} MiB free; CUDA reports "
321
+ f"{cuda_free} MiB free holding {held}; {RESERVE_FLAG} {planned} -> {reserve}",
322
+ file=sys.stderr,
323
+ )
324
+ return reserve
325
+
326
+
327
+ def for_windows(profile: dict[str, object]) -> dict[str, object]:
328
+ """``profile`` with the reserve ``windows_reserve_mib`` gives (when it has a numeric one)."""
329
+ args = profile.get("args")
330
+ if not isinstance(args, list) or RESERVE_FLAG not in args[:-1]:
331
+ return profile
332
+ at = args.index(RESERVE_FLAG) + 1
333
+ try:
334
+ planned = int(str(args[at]))
335
+ except ValueError:
336
+ return profile
337
+ before = profile.get(BEFORE_CACHE_KEY)
338
+ reserve = windows_reserve_mib(planned, before if isinstance(before, int) else 0)
339
+ return {**profile, "args": [*args[:at], str(reserve), *args[at + 1 :]]}
340
+
341
+
100
342
  def resolve(config: Path) -> Path:
101
- """Write the profile with its home-relative paths expanded beside it; returns that file."""
343
+ """Write the profile with its home-relative paths expanded beside it, and under Windows its
344
+ reserve raised by what other programs hold on the card; returns that file."""
102
345
  resolved = config.with_name(config.stem + ".resolved.json")
103
346
  profile = json.loads(config.read_text(encoding="utf-8"))
104
347
  home = planning_home(profile, config.parent.resolve())
105
- resolved.write_text(json.dumps(_expanded(profile, home), indent=1) + "\n", encoding="utf-8")
348
+ profile = cast("dict[str, object]", _expanded(profile, home))
349
+ if WINDOWS:
350
+ profile = for_windows(profile)
351
+ profile.pop(BEFORE_CACHE_KEY, None) # this launcher's, not PolyStrata's
352
+ resolved.write_text(json.dumps(profile, indent=1) + "\n", encoding="utf-8")
106
353
  return resolved
107
354
 
108
355
 
@@ -134,6 +381,7 @@ def main(argv: list[str] | None = None) -> None:
134
381
  if root not in sys.path:
135
382
  sys.path.insert(0, root)
136
383
  seed_expert_profile(args.engine_dir, args.config)
384
+ apply_windows_cpu_affinity()
137
385
  sys.argv = server_argv(args.engine_dir, resolve(args.config), args.host, args.port)
138
386
  runpy.run_path(sys.argv[0], run_name="__main__")
139
387
 
@@ -16,6 +16,7 @@ from __future__ import annotations
16
16
  import copy
17
17
  import json
18
18
  import subprocess
19
+ from collections.abc import Sequence
19
20
  from dataclasses import dataclass, field
20
21
  from pathlib import Path
21
22
  from typing import TypedDict
@@ -32,7 +33,7 @@ from localmodels.engines import (
32
33
  from localmodels.plan_envelope import MODELSCOPE_URL, PlanError
33
34
  from localmodels.probe import GPU, HostFacts
34
35
  from localmodels.records import Plan, ReleaseEngine
35
- from localmodels.vision import StrataVision, strata_gpu_mib
36
+ from localmodels.vision import StrataVision, strata_gpu_mib, strata_ram_mib
36
37
 
37
38
  GIB = 1 << 30
38
39
  # Engines that keep a MoE model's experts in host RAM beside a GPU cache: Strata, and PolyStrata's
@@ -82,8 +83,10 @@ class ExpertCacheSizing(TypedDict):
82
83
 
83
84
  class CardArgs(TypedDict, total=False):
84
85
  at_least_bytes: int
86
+ at_least_free_bytes: int # optional live free VRAM less reserve floor (shared-GPU safety)
85
87
  platforms: list[str] # only on these (facts["platform"]); every platform when absent
86
88
  args: list[str]
89
+ context: int # optional larger context window (--max-context and launch.window) on this card
87
90
 
88
91
 
89
92
  class SuiteRecipe(cat.ComponentRecipe, total=False):
@@ -103,8 +106,8 @@ class SuiteRecipe(cat.ComponentRecipe, total=False):
103
106
  # strata-poly recipes: what the engine keeps free of the card (--vram-reserve-mib) for the
104
107
  # display and its own overshoot of that reserve.
105
108
  vram_reserve_mib: int
106
- # strata-poly recipes: engine flags given only to a card with room to spare (``at_least_bytes``
107
- # of the card less the reserve) or only on some platforms, appended to the profile's args.
109
+ # strata-poly recipes: engine flags or wider context given only to a card with room to spare
110
+ # (``at_least_bytes`` of the card less the reserve) or only on some platforms.
108
111
  card_args: list[CardArgs]
109
112
  limits: dict[str, str]
110
113
  env: dict[str, str]
@@ -119,9 +122,9 @@ class SuiteRecipe(cat.ComponentRecipe, total=False):
119
122
  min_ram_total_bytes: int # below this the recipe is not recommended
120
123
  conversation_cache: ConversationCache # Strata recipes: parking when stack plan grants it
121
124
  expert_cache_sizing: ExpertCacheSizing # Strata recipes: a fixed slot count instead of auto
122
- vision: StrataVision # Strata recipes whose model reads pictures (roadmap decision 31)
125
+ vision: StrataVision # Strata recipes whose model reads pictures
123
126
  # Strata recipes since 2026-11-03: the installed SimplexAI score that lets ``--llm auto``
124
- # weigh the recipe against the llama.cpp pick (roadmap decisions 26 and 33; stack_suite).
127
+ # weigh the recipe against the llama.cpp pick (stack_suite).
125
128
  quality: cat.QualityData
126
129
  # PolyStrata recipes that should be preferred over a same-score llama.cpp pick (decision 66).
127
130
  prefer_over_llama: bool
@@ -135,6 +138,13 @@ class SuiteRecipe(cat.ComponentRecipe, total=False):
135
138
  parameters: str
136
139
  active_parameters: str
137
140
  moe: bool
141
+ decode_fraction: float
142
+ # Optional KV geometry and Metal overhead for compositional Apple Silicon unified-memory pricing.
143
+ full_layers: int
144
+ swa_layers: int
145
+ swa_window: int
146
+ per_layer_f16: int
147
+ metal_overhead_bytes: int
138
148
 
139
149
 
140
150
  @dataclass(frozen=True)
@@ -257,3 +267,125 @@ def size_bytes(text: str) -> int:
257
267
 
258
268
  def catalog_file(name: str) -> Path:
259
269
  return cat.CATALOG_PATH.parent / name
270
+
271
+
272
+ # PolyStrata KV row bytes relative to FP16 (2048 B/row for Inkling 2 Mini; engine/src/poly/inkling2.cpp).
273
+ POLY_KV_ROW_RATIO: dict[str, float] = {
274
+ "fp16": 1.0,
275
+ "f16": 1.0,
276
+ "fp8": 1056 / 2048,
277
+ "q8_0": 1088 / 2048,
278
+ "q4_0": 576 / 2048,
279
+ }
280
+ _POLY_SINGLE_SLOT_KV = frozenset({"q8_0", "q4_0"})
281
+ # Metal runtime/compute buffers (~1.5 GiB) + Python serve wrapper (~0.3 GiB), overridable per recipe.
282
+ # Calibrated on 24 GB Apple M6 (inkling-2-mini-q3-poly, --metal-memory legacy, 3072/3072 experts):
283
+ # 15.29 GiB post-load and 15.99 GiB after a 9.3K prompt vs 16.38 GiB planned (Metal strata-vision
284
+ # 311 MiB vs 791 MiB CUDA estimate offsets Metal compute overhead).
285
+ DEFAULT_METAL_OVERHEAD_BYTES = 1843 << 20
286
+
287
+
288
+ def poly_kv_format(args: Sequence[object]) -> str:
289
+ """Effective ``--kv`` format from a PolyStrata args list (defaults to ``fp16``)."""
290
+ items = [str(item) for item in args]
291
+ fmt = "fp16"
292
+ for idx, token in enumerate(items):
293
+ if token == "--kv" and idx + 1 < len(items):
294
+ fmt = items[idx + 1].strip().lower()
295
+ return fmt
296
+
297
+
298
+ def plan_kv_format(plan: Plan, recipe: SuiteRecipe) -> str:
299
+ """Effective ``--kv`` format from a rendered plan's ``strata-profile.json``, else the recipe."""
300
+ config_files = plan["service"].get("config_files") or {}
301
+ for path, raw in config_files.items():
302
+ if path.endswith("strata-profile.json"):
303
+ try:
304
+ cfg = json.loads(raw)
305
+ except (TypeError, ValueError):
306
+ break
307
+ args = cfg.get("args") if isinstance(cfg, dict) else None
308
+ if isinstance(args, list):
309
+ return poly_kv_format(args)
310
+ profile = recipe.get("profile")
311
+ raw_args = profile.get("args") if isinstance(profile, dict) else None
312
+ return poly_kv_format(raw_args) if isinstance(raw_args, list) else "fp16"
313
+
314
+
315
+ def poly_kv_geometry(
316
+ recipe: SuiteRecipe, *, allow_catalog_fallback: bool = True
317
+ ) -> tuple[int, int, int, int] | None:
318
+ """``(full_layers, swa_layers, swa_window, per_layer_f16)`` for compositional Metal KV sizing."""
319
+ full = int(recipe.get("full_layers") or 0)
320
+ swa = int(recipe.get("swa_layers") or 0)
321
+ swa_win = int(recipe.get("swa_window") or 0)
322
+ per_layer = int(recipe.get("per_layer_f16") or 0)
323
+ if (full > 0 or swa > 0) and per_layer > 0:
324
+ return full, swa, swa_win, per_layer
325
+ if not allow_catalog_fallback:
326
+ return None
327
+ repo = recipe.get("repo") or ""
328
+ if not repo:
329
+ return None
330
+ twin = next(
331
+ (
332
+ e
333
+ for e in cat.load_catalog_file()
334
+ if e.repo == repo and (e.full_layers > 0 or e.swa_layers > 0) and e.per_layer_f16 > 0
335
+ ),
336
+ None,
337
+ )
338
+ if twin is None:
339
+ return None
340
+ return twin.full_layers, twin.swa_layers, twin.swa_window, twin.per_layer_f16
341
+
342
+
343
+ def poly_unified_footprint(
344
+ recipe: SuiteRecipe,
345
+ *,
346
+ window: int | None = None,
347
+ slots: int | None = None,
348
+ kv_fmt: str | None = None,
349
+ vision_reader: str = "off",
350
+ allow_catalog_fallback: bool = True,
351
+ fallback_beside_bytes: int = 12 * GIB,
352
+ ) -> tuple[int, int]:
353
+ """Return ``(unified_bytes, wired_bytes)`` for a ``strata-poly`` recipe on Apple Silicon Metal.
354
+
355
+ When KV geometry is available, prices compositionally:
356
+ ``weights + kv(window, slots, kv_fmt) + resident_vision + metal_overhead_bytes``.
357
+ ``wired_bytes`` covers GPU-resident weights, KV cache and Metal vision encoder;
358
+ ``unified_bytes`` adds Metal runtime/compute and Python server overhead (default 1.80 GiB,
359
+ overridable via ``recipe["metal_overhead_bytes"]``).
360
+ """
361
+ weights = sum(int(f["size_bytes"]) for f in recipe["files"] if not f.get("vision"))
362
+ geom = poly_kv_geometry(recipe, allow_catalog_fallback=allow_catalog_fallback)
363
+ if geom is None:
364
+ total = weights + fallback_beside_bytes
365
+ return total, total
366
+ full_layers, swa_layers, swa_window, per_layer_f16 = geom
367
+ profile = recipe.get("profile")
368
+ profile_args = profile.get("args") if isinstance(profile, dict) else None
369
+ raw_args: Sequence[object] = profile_args if isinstance(profile_args, list) else ()
370
+ eff_window = (
371
+ window if window is not None and window > 0 else int(recipe.get("context") or 65536)
372
+ )
373
+ eff_kv = (kv_fmt or poly_kv_format(raw_args)).strip().lower()
374
+ default_slots = int(str(profile.get("parallel") or 2)) if isinstance(profile, dict) else 2
375
+ eff_slots = max(1, slots if slots is not None and slots > 0 else default_slots)
376
+ if eff_kv in _POLY_SINGLE_SLOT_KV:
377
+ eff_slots = 1
378
+ ratio = POLY_KV_ROW_RATIO.get(eff_kv, 1.0)
379
+ full_tokens = eff_window * eff_slots
380
+ swa_tokens = min(eff_window, swa_window) * eff_slots if swa_layers and swa_window else 0
381
+ kv_bytes = int((full_layers * full_tokens + swa_layers * swa_tokens) * per_layer_f16 * ratio)
382
+ spec = recipe.get("vision") or {}
383
+ if vision_reader == "gpu" and spec:
384
+ vision_bytes = strata_gpu_mib(spec, "gpu") << 20
385
+ elif vision_reader == "cpu" and spec:
386
+ vision_bytes = strata_ram_mib(spec, "cpu") << 20
387
+ else:
388
+ vision_bytes = 0
389
+ overhead = int(recipe.get("metal_overhead_bytes") or DEFAULT_METAL_OVERHEAD_BYTES)
390
+ wired = weights + kv_bytes + vision_bytes
391
+ return wired + overhead, wired