@simplexai/localmodels-linux-arm64 0.1.0-dev.103 → 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 (139) hide show
  1. package/LICENSE +201 -0
  2. package/{modules/simplex_localmodels-0.1.0.dev103.dist-info/licenses/NOTICE → NOTICE} +42 -13
  3. package/README.md +10 -0
  4. package/bootstrap.identity +1 -1
  5. package/bootstrap.sha256 +126 -127
  6. package/modules/localmodels/__init__.py +1 -1
  7. package/modules/localmodels/catalog.json +130 -127
  8. package/modules/localmodels/catalog.py +7 -3
  9. package/modules/localmodels/catalog_recipes.py +3 -3
  10. package/modules/localmodels/cli_parser.py +3 -3
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/console.py +1 -1
  13. package/modules/localmodels/context_policy.py +6 -5
  14. package/modules/localmodels/debug_cli.py +0 -12
  15. package/modules/localmodels/debug_mode.py +0 -6
  16. package/modules/localmodels/decode_calibration.json +3 -4
  17. package/modules/localmodels/decode_calibration.py +5 -2
  18. package/modules/localmodels/deployment_lifecycle.py +1 -1
  19. package/modules/localmodels/download-mirrors.json +1 -1
  20. package/modules/localmodels/engine_adapters/base.py +11 -1
  21. package/modules/localmodels/engine_adapters/strata_poly.py +65 -3
  22. package/modules/localmodels/engine_adapters/suite_plan.py +57 -20
  23. package/modules/localmodels/engines-b11583.json +6 -26
  24. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +3 -15
  25. package/modules/localmodels/engines-b12757-mix-ef2df21.json +3 -15
  26. package/modules/localmodels/engines-prism-b12178-03ec600.json +3 -15
  27. package/modules/localmodels/engines-speechcpp-v0.11.3.json +4 -20
  28. package/modules/localmodels/engines-strata-0.1.47.json +1 -5
  29. package/modules/localmodels/engines-strata-0.1.49.2.json +1 -5
  30. package/modules/localmodels/engines-strata-0.1.59.1.json +1 -5
  31. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +6 -30
  32. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +129 -0
  33. package/modules/localmodels/engines-whisper-b5454.json +6 -30
  34. package/modules/localmodels/engines.json +13 -61
  35. package/modules/localmodels/estimator.py +10 -5
  36. package/modules/localmodels/gpu_specs.py +1 -1
  37. package/modules/localmodels/hosts.py +12 -16
  38. package/modules/localmodels/kokoro-tts-0.6.1.txt +1 -1
  39. package/modules/localmodels/library_elastic.py +135 -6
  40. package/modules/localmodels/library_kept.py +9 -1
  41. package/modules/localmodels/library_model.py +28 -1
  42. package/modules/localmodels/library_poly.py +109 -11
  43. package/modules/localmodels/library_pricing.py +12 -3
  44. package/modules/localmodels/library_serve.py +134 -67
  45. package/modules/localmodels/library_smoke.py +63 -5
  46. package/modules/localmodels/library_state.py +3 -2
  47. package/modules/localmodels/library_status.py +8 -1
  48. package/modules/localmodels/llm_rank.py +13 -8
  49. package/modules/localmodels/metal.py +1 -2
  50. package/modules/localmodels/plan_envelope.py +29 -11
  51. package/modules/localmodels/planning/budget.py +14 -12
  52. package/modules/localmodels/planning/memory_pools.py +7 -1
  53. package/modules/localmodels/privacy_acceptance.py +6 -5
  54. package/modules/localmodels/py.typed +0 -0
  55. package/modules/localmodels/quant_formats.py +1 -1
  56. package/modules/localmodels/recommend_cli.py +1 -1
  57. package/modules/localmodels/remote_ops_launchd.py +8 -1
  58. package/modules/localmodels/runtime_process.py +1 -1
  59. package/modules/localmodels/service_deployment.py +2 -4
  60. package/modules/localmodels/service_probe.py +59 -13
  61. package/modules/localmodels/setup_inspection.py +72 -70
  62. package/modules/localmodels/setup_text.py +7 -56
  63. package/modules/localmodels/sidecar_downloads.py +34 -0
  64. package/modules/localmodels/sidecar_http.py +61 -5
  65. package/modules/localmodels/sidecar_state.py +52 -2
  66. package/modules/localmodels/speech_admission.py +20 -4
  67. package/modules/localmodels/speech_catalog.py +23 -0
  68. package/modules/localmodels/speech_cli.py +10 -2
  69. package/modules/localmodels/speech_jobs.py +42 -17
  70. package/modules/localmodels/speech_server.py +182 -81
  71. package/modules/localmodels/speech_state.py +4 -1
  72. package/modules/localmodels/speech_workers.py +11 -0
  73. package/modules/localmodels/stack.py +1 -1
  74. package/modules/localmodels/stack_args.py +6 -6
  75. package/modules/localmodels/stack_auto.py +1 -1
  76. package/modules/localmodels/stack_aux_gpu.py +1 -1
  77. package/modules/localmodels/stack_cleanup.py +21 -18
  78. package/modules/localmodels/stack_cli.py +6 -2
  79. package/modules/localmodels/stack_compose.py +11 -4
  80. package/modules/localmodels/stack_debug.py +1 -2
  81. package/modules/localmodels/stack_decision.py +4 -4
  82. package/modules/localmodels/stack_doctor.py +2 -2
  83. package/modules/localmodels/stack_events.py +1 -1
  84. package/modules/localmodels/stack_gpu_memory.py +1 -1
  85. package/modules/localmodels/stack_hardware.py +3 -3
  86. package/modules/localmodels/stack_mcp.py +1 -2
  87. package/modules/localmodels/stack_picks.py +1 -1
  88. package/modules/localmodels/stack_plan.py +9 -9
  89. package/modules/localmodels/stack_ports.py +31 -4
  90. package/modules/localmodels/stack_rollback.py +1 -1
  91. package/modules/localmodels/stack_run.py +1 -1
  92. package/modules/localmodels/stack_suite.py +61 -12
  93. package/modules/localmodels/stack_view_agent.py +1 -1
  94. package/modules/localmodels/stack_view_serve.py +0 -2
  95. package/modules/localmodels/stack_view_words.py +2 -2
  96. package/modules/localmodels/stack_warm.py +2 -2
  97. package/modules/localmodels/stack_whatif.py +524 -41
  98. package/modules/localmodels/stack_whatif_html.py +903 -0
  99. package/modules/localmodels/startlux-decide-83fe6c7d.txt +2 -2
  100. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.7.txt → strata-poly-serve-0.2.20-poly.9.txt} +1 -1
  101. package/modules/localmodels/strata_poly_server.py +114 -3
  102. package/modules/localmodels/suite.py +137 -5
  103. package/modules/localmodels/tts_admission.py +2 -17
  104. package/modules/localmodels/tts_catalog.py +29 -1
  105. package/modules/localmodels/tts_cli.py +23 -4
  106. package/modules/localmodels/tts_http.py +10 -4
  107. package/modules/localmodels/tts_jobs.py +49 -19
  108. package/modules/localmodels/tts_server.py +1 -1
  109. package/modules/localmodels/tts_sidecar.py +66 -28
  110. package/modules/localmodels/tts_state.py +7 -2
  111. package/modules/localmodels/vision.py +5 -3
  112. package/modules/localmodels/web/view/ASSET-SOURCES.md +4 -7
  113. package/modules/localmodels/web/view/view.css +0 -1
  114. package/modules/localmodels/web/view/view.js +2 -5
  115. package/modules/localmodels/web/whatif/app.js +730 -0
  116. package/modules/localmodels/web/whatif/page.html +1172 -0
  117. package/modules/localmodels/web/whatif/sim.js +303 -0
  118. package/modules/localmodels/windows_job.py +179 -11
  119. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/METADATA +14 -0
  120. package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/RECORD +118 -114
  121. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/LICENSE +201 -0
  122. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/NOTICE +126 -0
  123. package/package.json +11 -2
  124. package/tool.json +1 -1
  125. package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +0 -94
  126. package/modules/localmodels/fixtures/stack-research-demo-plan.json +0 -1059
  127. package/modules/localmodels/stack_research.py +0 -716
  128. package/modules/localmodels/stack_research_demo.py +0 -125
  129. package/modules/localmodels/stack_research_plan.py +0 -146
  130. package/modules/localmodels/web/index.html +0 -2605
  131. package/modules/localmodels/web/sizecalc/app.js +0 -1306
  132. package/modules/localmodels/web/sizecalc/calc.js +0 -269
  133. package/modules/localmodels/web/sizecalc/page.html +0 -520
  134. package/modules/localmodels/web/view/logo-claude.svg +0 -3
  135. package/modules/localmodels/web/view/logo-codex.png +0 -0
  136. package/modules/simplex_localmodels-0.1.0.dev103.dist-info/METADATA +0 -9
  137. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/WHEEL +0 -0
  138. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/entry_points.txt +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,303 @@
1
+ /* Pure lookup & resolution engine for `localmodels stack what-if --html`.
2
+ * Zero hardcoded model IDs or hardware thresholds: every decision comes directly
3
+ * from `WHATIF_DATA` generated by Python `stack_whatif_html.page_data()`.
4
+ */
5
+ (function (root) {
6
+ "use strict";
7
+
8
+ const GIB = 1073741824;
9
+
10
+ function formatWindow(tokens) {
11
+ if (!tokens || tokens <= 0) return "—";
12
+ if (tokens % 1024 === 0) return String(tokens / 1024) + "K";
13
+ return String(Math.round(tokens / 1000)) + "K";
14
+ }
15
+
16
+ function formatGiB(bytes, digits) {
17
+ if (bytes === null || bytes === undefined) return "—";
18
+ const d = digits === undefined ? 1 : digits;
19
+ return (bytes / GIB).toFixed(d) + " GiB";
20
+ }
21
+
22
+ function formatNum(n) {
23
+ return Number(n).toFixed(2).replace(/\.?0+$/, "");
24
+ }
25
+
26
+ function lookupBand(bands, value) {
27
+ if (!bands || !bands.length) return null;
28
+ const target = Number(value) + 1e-6;
29
+ let chosen = 0;
30
+ for (let i = bands.length - 1; i >= 0; i--) {
31
+ if (bands[i][0] <= target) {
32
+ chosen = i;
33
+ break;
34
+ }
35
+ }
36
+ return { edge: bands[chosen][0], value: bands[chosen][1], index: chosen };
37
+ }
38
+
39
+ function strataPossible(policy, platform, cuda, vramUsed, prefer) {
40
+ if (prefer !== "smartest" || cuda !== "13.0") return false;
41
+ if (platform === "linux" && vramUsed >= policy.idle_used_gib) return false;
42
+ if (platform === "win32" && vramUsed > policy.wddm_baseline_cap_gib) return false;
43
+ return true;
44
+ }
45
+
46
+ function cloneResult(raw, stripPassedOver) {
47
+ const out = Object.assign({}, raw);
48
+ let reasons = Array.isArray(raw.reasons) ? raw.reasons.slice() : [];
49
+ if (stripPassedOver) {
50
+ reasons = reasons.filter(function (line) {
51
+ return !String(line).startsWith("LLM: auto passed over");
52
+ });
53
+ }
54
+ out.reasons = reasons;
55
+ return out;
56
+ }
57
+
58
+ function resolveNvidia(data, state) {
59
+ const policy = data.policy;
60
+ const platform = state.platform === "linux" ? "linux" : "win32";
61
+ const vram = Number(state.vram);
62
+ const ram = Number(state.ram);
63
+ const ramAvail = Math.max(0, Math.min(Number(state.ram_avail), ram));
64
+ const vramUsed = Math.max(0, Math.min(Number(state.vram_used || 0), vram - 1));
65
+ const cuda = String(state.cuda || "13.0");
66
+ const prefer = String(state.prefer || "smartest");
67
+ const decision = String(state.decision || "none");
68
+
69
+ let effPrefer = prefer;
70
+ let effCuda = cuda;
71
+ let stripPassedOver = false;
72
+ if (prefer === "concurrent" && decision === "auto") {
73
+ effPrefer = "smartest";
74
+ effCuda = cuda === "13.0" ? "12.8" : cuda;
75
+ stripPassedOver = true;
76
+ } else if (prefer !== "smartest" && cuda === "13.0") {
77
+ effCuda = "12.8";
78
+ } else if (!strataPossible(policy, platform, cuda, vramUsed, prefer) && cuda === "13.0") {
79
+ effCuda = "12.8";
80
+ }
81
+
82
+ const effStrata = strataPossible(policy, platform, effCuda, vramUsed, effPrefer);
83
+ const buckets = (data.nvidia_ram_buckets || {})[String(vram)] || {};
84
+ const ramKey = effStrata ? String(buckets[String(ram)] || ram) : "*";
85
+ const key = [platform, vram, ramKey, effCuda, vramUsed, effPrefer, decision].join("|");
86
+ const curve = data.nvidia[key] || [];
87
+ const hit = lookupBand(curve, ramAvail);
88
+ const result = hit ? cloneResult(data.results[hit.value], stripPassedOver) : null;
89
+
90
+ const libStrata = strataPossible(policy, platform, cuda, vramUsed, "smartest");
91
+ const libCuda = !libStrata && cuda === "13.0" ? "12.8" : cuda;
92
+ const libRamKey = libStrata ? String(buckets[String(ram)] || ram) : "*";
93
+ const libKey = [platform, vram, libRamKey, libCuda, vramUsed].join("|");
94
+ const libCurve = (data.library && data.library.nvidia && data.library.nvidia[libKey]) || [];
95
+ const libHit = lookupBand(libCurve, ramAvail);
96
+
97
+ return {
98
+ mode: "nvidia",
99
+ result: result,
100
+ library: libHit ? libHit.value : null,
101
+ curve: curve,
102
+ curveKey: key,
103
+ effectiveAvail: ramAvail,
104
+ rawAvail: ramAvail,
105
+ ramTotal: ram,
106
+ vramTotal: vram,
107
+ vramUsed: vramUsed,
108
+ vramFree: Math.max(0, vram - vramUsed),
109
+ strataAllowed: strataPossible(policy, platform, cuda, vramUsed, prefer),
110
+ stripPassedOver: stripPassedOver,
111
+ };
112
+ }
113
+
114
+ function resolveMac(data, state) {
115
+ const policy = data.policy;
116
+ const total = Number(state.mac_total);
117
+ const tier = data.mac.tiers[String(total)] || {
118
+ working_set_gib: total * 0.75,
119
+ reserve_gib: 3,
120
+ ceiling_gib: total - 3,
121
+ };
122
+ const rawAvail = Math.max(0, Math.min(Number(state.mac_avail), total));
123
+ const pressure = Number(state.pressure || 1);
124
+ const prefer = String(state.prefer || "smartest");
125
+ const decision = String(state.decision || "none");
126
+
127
+ if (pressure === 4) {
128
+ return {
129
+ mode: "mac",
130
+ result: cloneResult(data.results[data.mac.critical_result], false),
131
+ library: null,
132
+ curve: [],
133
+ effectiveAvail: 0,
134
+ rawAvail: rawAvail,
135
+ pressureKept: rawAvail,
136
+ tier: tier,
137
+ total: total,
138
+ pressure: pressure,
139
+ };
140
+ }
141
+
142
+ const kept = pressure === 2 ? rawAvail * policy.warn_keep_fraction : 0;
143
+ const effAvail = Math.max(0, rawAvail - kept);
144
+ const effPrefer = prefer === "concurrent" ? "smartest" : prefer;
145
+ const key = [total, effPrefer, decision].join("|");
146
+ const curve = data.mac.curves[key] || [];
147
+ const hit = lookupBand(curve, effAvail);
148
+ const result = hit ? cloneResult(data.results[hit.value], false) : null;
149
+ if (result && pressure === 2) {
150
+ const pct = Math.round(policy.warn_keep_fraction * 100);
151
+ result.reasons.unshift(
152
+ "macOS memory pressure is at warning; " +
153
+ kept.toFixed(1) +
154
+ " GB (" +
155
+ pct +
156
+ "% of the memory available) is kept back so loading the stack does not push it to critical"
157
+ );
158
+ }
159
+
160
+ const libCurve = (data.library && data.library.mac && data.library.mac[String(total)]) || [];
161
+ const libHit = lookupBand(libCurve, effAvail);
162
+
163
+ return {
164
+ mode: "mac",
165
+ result: result,
166
+ library: libHit ? libHit.value : null,
167
+ curve: curve,
168
+ curveKey: key,
169
+ effectiveAvail: effAvail,
170
+ rawAvail: rawAvail,
171
+ pressureKept: kept,
172
+ tier: tier,
173
+ total: total,
174
+ pressure: pressure,
175
+ };
176
+ }
177
+
178
+ function resolveOtherUnified(data, state) {
179
+ const vendor = String(state.other_vendor || "cuda-uma");
180
+ const total = Number(state.other_total || 64);
181
+ const prefer = String(state.prefer || "smartest");
182
+ const key = [vendor, total, prefer].join("|");
183
+ const entry = data.other_unified[key];
184
+ return {
185
+ mode: "other_unified",
186
+ result: entry ? cloneResult(data.results[entry.result], false) : null,
187
+ library: entry ? entry.library : null,
188
+ curve: [],
189
+ vendor: vendor,
190
+ total: total,
191
+ };
192
+ }
193
+
194
+ function buildCommand(state) {
195
+ const parts = ["python3 -m localmodels stack plan --llm auto"];
196
+ if (state.prefer && state.prefer !== "smartest") {
197
+ parts.push("--prefer " + state.prefer);
198
+ }
199
+ if (state.decision && state.decision !== "none") {
200
+ parts.push("--decision " + state.decision);
201
+ }
202
+ if (state.mode === "mac") {
203
+ parts.push("--unified-memory " + state.mac_total + "GiB");
204
+ }
205
+ return parts.join(" ");
206
+ }
207
+
208
+ function buildWhatifCommand(state) {
209
+ const parts = ["python3 -m localmodels stack what-if"];
210
+ if (state.mode === "mac") {
211
+ parts.push("--unified-memory " + state.mac_total + "GiB");
212
+ parts.push("--ram-available " + formatNum(state.mac_avail) + "GiB");
213
+ if (Number(state.pressure) !== 1) {
214
+ parts.push("--pressure " + state.pressure);
215
+ }
216
+ } else if (state.mode === "nvidia") {
217
+ parts.push("--platform " + (state.platform === "linux" ? "linux" : "windows"));
218
+ parts.push("--vram " + state.vram + "GiB");
219
+ parts.push("--ram " + state.ram + "GiB");
220
+ parts.push("--ram-available " + formatNum(state.ram_avail) + "GiB");
221
+ if (state.cuda && state.cuda !== "13.0") {
222
+ parts.push("--cuda " + state.cuda);
223
+ }
224
+ if (Number(state.vram_used) > 0) {
225
+ parts.push("--vram-used " + state.vram_used + "GiB");
226
+ }
227
+ } else {
228
+ return "python3 -m localmodels library status";
229
+ }
230
+ if (state.prefer && state.prefer !== "smartest") {
231
+ parts.push("--prefer " + state.prefer);
232
+ }
233
+ if (state.decision && state.decision !== "none") {
234
+ parts.push("--decision " + state.decision);
235
+ }
236
+ return parts.join(" ");
237
+ }
238
+
239
+ function resolve(data, state) {
240
+ let out;
241
+ if (state.mode === "mac") {
242
+ out = resolveMac(data, state);
243
+ } else if (state.mode === "other_unified") {
244
+ out = resolveOtherUnified(data, state);
245
+ } else {
246
+ out = resolveNvidia(data, state);
247
+ }
248
+ out.command = buildCommand(state);
249
+ out.whatifCommand = buildWhatifCommand(state);
250
+ return out;
251
+ }
252
+
253
+ function extractRulerBands(data, curve, maxGib) {
254
+ if (!curve || !curve.length) return [];
255
+ const clipped = [];
256
+ for (let i = 0; i < curve.length; i++) {
257
+ const low = Number(curve[i][0]);
258
+ if (low > maxGib + 1e-6) break;
259
+ const nextLow = i + 1 < curve.length ? Math.min(maxGib, Number(curve[i + 1][0])) : maxGib;
260
+ const res = data.results[curve[i][1]];
261
+ if (clipped.length) {
262
+ const prev = clipped[clipped.length - 1];
263
+ const same =
264
+ prev.result.ok === res.ok &&
265
+ prev.result.id === res.id &&
266
+ prev.result.quant === res.quant &&
267
+ prev.result.engine === res.engine &&
268
+ prev.result.window === res.window &&
269
+ prev.result.slots === res.slots &&
270
+ prev.result.decision_id === res.decision_id &&
271
+ JSON.stringify(prev.result.kv_types) === JSON.stringify(res.kv_types);
272
+ if (same) {
273
+ prev.max = nextLow;
274
+ continue;
275
+ }
276
+ }
277
+ clipped.push({ min: low, max: nextLow, result: res });
278
+ }
279
+ return clipped.reverse();
280
+ }
281
+
282
+ const api = {
283
+ GIB: GIB,
284
+ formatWindow: formatWindow,
285
+ formatGiB: formatGiB,
286
+ formatNum: formatNum,
287
+ lookupBand: lookupBand,
288
+ strataPossible: strataPossible,
289
+ resolveNvidia: resolveNvidia,
290
+ resolveMac: resolveMac,
291
+ resolveOtherUnified: resolveOtherUnified,
292
+ resolve: resolve,
293
+ buildCommand: buildCommand,
294
+ buildWhatifCommand: buildWhatifCommand,
295
+ extractRulerBands: extractRulerBands,
296
+ };
297
+
298
+ if (typeof module !== "undefined" && module.exports) {
299
+ module.exports = api;
300
+ } else {
301
+ root.WHATIF_SIM = api;
302
+ }
303
+ })(typeof globalThis !== "undefined" ? globalThis : window);
@@ -1,28 +1,144 @@
1
- """Windows: end a helper process together with the process that started it."""
1
+ """Windows: Job Object lifetime, CPU affinity, and shared core-reservation policy.
2
+
3
+ Pure CPU-split helpers (``reserved_speech_cores``, ``poly_cpu_threads``,
4
+ ``split_affinity_masks``, ``parse_affinity_override``) run on every platform so planning and
5
+ tests share one rule with the Windows runtime.
6
+ """
2
7
 
3
8
  from __future__ import annotations
4
9
 
5
10
  import ctypes
11
+ import os
6
12
  import sys
13
+ from collections.abc import Mapping
7
14
  from typing import Any
8
15
 
16
+ _AFFINITY = 0x0010 # JOB_OBJECT_LIMIT_AFFINITY
9
17
  _KILL_ON_JOB_CLOSE = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
10
18
  # JOB_OBJECT_LIMIT_BREAKAWAY_OK: a service the helper starts with CREATE_BREAKAWAY_FROM_JOB
11
19
  # (process_identity.spawn_detached) leaves the job and outlives the CLI; without it the model
12
- # server stayed in the job and died with the load command (homewin, dev38 verification).
20
+ # server stayed in the job and died with the load command (Windows job verification).
13
21
  _BREAKAWAY_OK = 0x0800
14
22
  _EXTENDED_LIMITS = 9 # JobObjectExtendedLimitInformation
15
23
  _JOBS: list[Any] = [] # this process's job handles: closed by Windows when it ends, however
16
24
 
25
+ SPEECH_AFFINITY_ENV = "LOCALMODELS_SPEECH_CPU_AFFINITY"
26
+ POLY_AFFINITY_ENV = "LOCALMODELS_POLY_CPU_AFFINITY"
27
+ _DISABLE_VALUES = frozenset(("0", "off", "false", "none"))
17
28
 
18
- def end_with_this_process(handle: int) -> bool:
19
- """Windows: put the process ``handle`` names in a job that this process alone holds open,
20
- with kill-on-close: when this process ends, however (TerminateProcess included), Windows
21
- ends that process and its children. A helper otherwise outlives a killed CLI and keeps the
22
- file it writes open, so cleaning up after the CLI fails with WinError 32. False when the
23
- job cannot be made or assigned (the helper then ends as before)."""
29
+
30
+ def reserved_speech_cores(logical_cores: int) -> int:
31
+ """Logical cores kept back from PolyStrata for speech and desktop responsiveness."""
32
+ if logical_cores >= 12:
33
+ return 4
34
+ if logical_cores >= 6:
35
+ return 2
36
+ return 0
37
+
38
+
39
+ def poly_cpu_threads(logical_cores: int) -> int:
40
+ """Default ``--threads`` for PolyStrata CPU expert compute, leaving headroom for speech."""
41
+ cores = max(1, logical_cores)
42
+ reserve = reserved_speech_cores(cores)
43
+ if reserve > 0:
44
+ return max(1, cores - reserve)
45
+ return max(1, cores - 1)
46
+
47
+
48
+ def split_affinity_masks(
49
+ available_mask: int,
50
+ *,
51
+ min_speech_cores: int = 1,
52
+ ) -> tuple[int, int] | None:
53
+ """Split ``available_mask`` into disjoint ``(poly_mask, speech_mask)`` bitmasks.
54
+
55
+ Reserves the highest-index logical CPUs for speech (keeping CPU 0 and Intel P-cores with
56
+ PolyStrata while guaranteeing a PolyStrata-free slice for speech). Returns ``None`` when
57
+ too few CPUs are available to reserve at least ``min_speech_cores``.
58
+ """
59
+ if available_mask <= 0:
60
+ return None
61
+ cpus = [bit for bit in range(available_mask.bit_length()) if available_mask & (1 << bit)]
62
+ reserve = reserved_speech_cores(len(cpus))
63
+ if reserve <= 0 or reserve < min_speech_cores or len(cpus) <= reserve:
64
+ return None
65
+ speech_mask = sum(1 << bit for bit in cpus[-reserve:])
66
+ poly_mask = available_mask & ~speech_mask
67
+ if poly_mask <= 0 or speech_mask <= 0:
68
+ return None
69
+ return poly_mask, speech_mask
70
+
71
+
72
+ def parse_affinity_override(raw: str | None, available_mask: int) -> int | None:
73
+ """Parse an explicit CPU affinity env override (``off`` -> 0, int/hex -> clamped mask).
74
+
75
+ Returns ``None`` when unset/blank so the caller applies its default policy.
76
+ """
77
+ if raw is None:
78
+ return None
79
+ cleaned = raw.strip().lower()
80
+ if not cleaned:
81
+ return None
82
+ if cleaned in _DISABLE_VALUES:
83
+ return 0
84
+ try:
85
+ parsed = int(cleaned, 0)
86
+ except ValueError:
87
+ return 0
88
+ if parsed <= 0 or available_mask <= 0:
89
+ return 0
90
+ return parsed & available_mask
91
+
92
+
93
+ def process_affinity_mask(handle: int | None = None) -> int | None:
94
+ """Windows: active processor-group affinity mask for ``handle`` (default: current process)."""
24
95
  if sys.platform != "win32":
25
- return False
96
+ return None
97
+ from ctypes import wintypes
98
+
99
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
100
+ h = wintypes.HANDLE
101
+ kernel.GetCurrentProcess.argtypes, kernel.GetCurrentProcess.restype = (), h
102
+ kernel.GetProcessAffinityMask.argtypes = (
103
+ h,
104
+ ctypes.POINTER(ctypes.c_size_t),
105
+ ctypes.POINTER(ctypes.c_size_t),
106
+ )
107
+ kernel.GetProcessAffinityMask.restype = wintypes.BOOL
108
+ target = kernel.GetCurrentProcess() if handle is None else handle
109
+ proc_mask = ctypes.c_size_t(0)
110
+ sys_mask = ctypes.c_size_t(0)
111
+ if not kernel.GetProcessAffinityMask(target, ctypes.byref(proc_mask), ctypes.byref(sys_mask)):
112
+ return None
113
+ mask = int(proc_mask.value)
114
+ return mask if mask > 0 else None
115
+
116
+
117
+ def speech_affinity_mask(
118
+ *,
119
+ env: Mapping[str, str] | None = None,
120
+ available_mask: int | None = None,
121
+ ) -> int | None:
122
+ """Exclusive 4-core CPU affinity mask for a Windows CPU speech worker, or ``None``.
123
+
124
+ Only pins speech when at least 4 cores are reserved (12+ logical CPUs) so speech's 4
125
+ threads are never cramped onto 2 cores. On 6-11 logical CPUs, PolyStrata is still excluded
126
+ from the top 2 cores while speech runs unpinned at ``ABOVE_NORMAL_PRIORITY_CLASS``.
127
+ """
128
+ mask = process_affinity_mask() if available_mask is None else available_mask
129
+ if mask is None or mask <= 0:
130
+ return None
131
+ source = os.environ if env is None else env
132
+ override = parse_affinity_override(source.get(SPEECH_AFFINITY_ENV), mask)
133
+ if override is not None:
134
+ return override if override > 0 else None
135
+ split = split_affinity_masks(mask, min_speech_cores=4)
136
+ return split[1] if split is not None else None
137
+
138
+
139
+ def _windows_job_structures() -> tuple[Any, Any]:
140
+ if sys.platform != "win32":
141
+ raise RuntimeError("Windows Job Object structures require win32")
26
142
  from ctypes import wintypes
27
143
 
28
144
  c = ctypes.c_uint64
@@ -42,6 +158,14 @@ def end_with_this_process(handle: int) -> bool:
42
158
  ("peak_job", ctypes.c_size_t),
43
159
  ] # fmt: skip
44
160
 
161
+ return Basic, Extended
162
+
163
+
164
+ def _configure_kernel32() -> Any:
165
+ if sys.platform != "win32":
166
+ raise RuntimeError("kernel32 Job Object API requires win32")
167
+ from ctypes import wintypes
168
+
45
169
  kernel = ctypes.WinDLL("kernel32", use_last_error=True)
46
170
  h = wintypes.HANDLE
47
171
  kernel.CreateJobObjectW.argtypes, kernel.CreateJobObjectW.restype = (
@@ -54,12 +178,27 @@ def end_with_this_process(handle: int) -> bool:
54
178
  (h, h),
55
179
  wintypes.BOOL,
56
180
  )
181
+ kernel.SetProcessAffinityMask.argtypes, kernel.SetProcessAffinityMask.restype = (
182
+ (h, ctypes.c_size_t),
183
+ wintypes.BOOL,
184
+ )
57
185
  kernel.CloseHandle.argtypes, kernel.CloseHandle.restype = (h,), wintypes.BOOL
186
+ return kernel
187
+
188
+
189
+ def _assign_job(handle: int, flags: int, affinity_mask: int | None = None) -> bool:
190
+ if sys.platform != "win32":
191
+ return False
192
+ _, extended_cls = _windows_job_structures()
193
+ kernel = _configure_kernel32()
58
194
  job = kernel.CreateJobObjectW(None, None)
59
195
  if not job:
60
196
  return False
61
- info = Extended()
62
- info.basic.flags = _KILL_ON_JOB_CLOSE | _BREAKAWAY_OK
197
+ info = extended_cls()
198
+ info.basic.flags = flags
199
+ if affinity_mask is not None and affinity_mask > 0:
200
+ info.basic.flags |= _AFFINITY
201
+ info.basic.affinity = affinity_mask
63
202
  if kernel.SetInformationJobObject(
64
203
  job, _EXTENDED_LIMITS, ctypes.byref(info), ctypes.sizeof(info)
65
204
  ) and kernel.AssignProcessToJobObject(job, handle):
@@ -67,3 +206,32 @@ def end_with_this_process(handle: int) -> bool:
67
206
  return True
68
207
  kernel.CloseHandle(job)
69
208
  return False
209
+
210
+
211
+ def end_with_this_process(handle: int, *, affinity_mask: int | None = None) -> bool:
212
+ """Windows: put the process ``handle`` names in a job that this process alone holds open,
213
+ with kill-on-close: when this process ends, however (TerminateProcess included), Windows
214
+ ends that process and its children. A helper otherwise outlives a killed CLI and keeps the
215
+ file it writes open, so cleaning up after the CLI fails with WinError 32.
216
+
217
+ When ``affinity_mask`` is positive, also sets ``JOB_OBJECT_LIMIT_AFFINITY`` on the job,
218
+ falling back to kill-on-close alone if the host job hierarchy rejects the affinity limit.
219
+ False when the job cannot be made or assigned (the helper then ends as before)."""
220
+ if sys.platform != "win32":
221
+ return False
222
+ base_flags = _KILL_ON_JOB_CLOSE | _BREAKAWAY_OK
223
+ if affinity_mask is not None and affinity_mask > 0:
224
+ if _assign_job(handle, base_flags, affinity_mask):
225
+ return True
226
+ return _assign_job(handle, base_flags)
227
+
228
+
229
+ def restrict_process_tree_affinity(handle: int, affinity_mask: int) -> bool:
230
+ """Windows: bound ``handle`` and every child it spawns to ``affinity_mask`` via a Job Object
231
+ without kill-on-close, falling back to ``SetProcessAffinityMask`` when nested jobs fail."""
232
+ if sys.platform != "win32" or affinity_mask <= 0:
233
+ return False
234
+ if _assign_job(handle, 0, affinity_mask):
235
+ return True
236
+ kernel = _configure_kernel32()
237
+ return bool(kernel.SetProcessAffinityMask(handle, affinity_mask))
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: simplex-localmodels
3
+ Version: 0.1.0.dev104
4
+ Summary: Detect hardware, recommend and install a verified local model stack
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ License-File: localmodels/HERMES-LICENSE
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.10