@simplexai/localmodels-win32-x64 0.1.0-dev.57 → 0.1.0-dev.59

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 (68) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +66 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +1 -1
  5. package/modules/localmodels/bifrost_admin.py +53 -8
  6. package/modules/localmodels/bifrost_config.py +103 -4
  7. package/modules/localmodels/bifrost_log.py +166 -0
  8. package/modules/localmodels/budget.py +161 -1
  9. package/modules/localmodels/catalog.json +55 -32
  10. package/modules/localmodels/catalog.py +5 -2
  11. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
  12. package/modules/localmodels/frontend.py +26 -21
  13. package/modules/localmodels/gateway_bifrost.py +30 -6
  14. package/modules/localmodels/gpu_specs.py +38 -13
  15. package/modules/localmodels/hosts.py +99 -12
  16. package/modules/localmodels/library_cli.py +8 -1
  17. package/modules/localmodels/library_convert.py +34 -0
  18. package/modules/localmodels/library_elastic.py +747 -0
  19. package/modules/localmodels/library_gateway.py +101 -10
  20. package/modules/localmodels/library_jobs.py +16 -7
  21. package/modules/localmodels/library_model.py +101 -4
  22. package/modules/localmodels/library_pricing.py +41 -39
  23. package/modules/localmodels/library_serve.py +322 -58
  24. package/modules/localmodels/library_state.py +35 -1
  25. package/modules/localmodels/library_status.py +113 -6
  26. package/modules/localmodels/llm_rank.py +16 -5
  27. package/modules/localmodels/metal.py +141 -0
  28. package/modules/localmodels/metal_probe.py +167 -0
  29. package/modules/localmodels/plan_envelope.py +4 -1
  30. package/modules/localmodels/probe.py +2 -2
  31. package/modules/localmodels/process_identity_linux.py +39 -0
  32. package/modules/localmodels/recommend.py +6 -1
  33. package/modules/localmodels/remote_ops.py +4 -3
  34. package/modules/localmodels/remote_ops_download.py +37 -24
  35. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  36. package/modules/localmodels/remote_ops_service.py +93 -36
  37. package/modules/localmodels/runtime_auth.py +4 -1
  38. package/modules/localmodels/service_wiring.py +238 -12
  39. package/modules/localmodels/setup_inspection.py +47 -70
  40. package/modules/localmodels/setup_inspection_harness.py +159 -15
  41. package/modules/localmodels/setup_text.py +14 -0
  42. package/modules/localmodels/setup_upgrade.py +1 -1
  43. package/modules/localmodels/source_byok.py +6 -2
  44. package/modules/localmodels/source_byok_probe.py +6 -1
  45. package/modules/localmodels/stack.py +9 -1
  46. package/modules/localmodels/stack_binding.py +3 -35
  47. package/modules/localmodels/stack_cleanup.py +4 -0
  48. package/modules/localmodels/stack_compose.py +24 -3
  49. package/modules/localmodels/stack_hardware.py +3 -1
  50. package/modules/localmodels/stack_lifecycle.py +24 -1
  51. package/modules/localmodels/stack_picks.py +16 -2
  52. package/modules/localmodels/stack_plan.py +6 -2
  53. package/modules/localmodels/stack_ports.py +2 -0
  54. package/modules/localmodels/stack_remove.py +10 -1
  55. package/modules/localmodels/stack_up.py +33 -7
  56. package/modules/localmodels/stack_update.py +3 -1
  57. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
  58. package/modules/localmodels/suite.py +43 -27
  59. package/modules/localmodels/transport.py +13 -2
  60. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
  61. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +63 -61
  62. package/package.json +1 -1
  63. package/tool.json +1 -1
  64. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  65. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
  68. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,747 @@
1
+ """Dual-tier memory admission and elastic posture ladder for ``localmodels library load``.
2
+
3
+ Separates the hard wired-memory ceiling (only gate that hard-refuses with ``LOAD_NO_ROOM``) from
4
+ the soft admission budget (drives elastic posture selection and pressure warnings). When live
5
+ memory is tight, steps down parallel slots first (2 -> 1), then context window (64K -> 32K -> 16K
6
+ floor) while keeping KV quantization and Flash Attention intact. On Apple Silicon unified memory,
7
+ if even the floor posture exceeds the soft budget while fitting within Metal wired headroom and
8
+ non-critical VM pressure, admission succeeds at the floor posture with a pressure warning.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ import math
15
+ from dataclasses import dataclass, replace
16
+ from typing import cast
17
+
18
+ from localmodels import (
19
+ budget,
20
+ context_policy,
21
+ deploy,
22
+ estimator,
23
+ hosts,
24
+ library_kept,
25
+ library_poly,
26
+ library_pricing,
27
+ metal,
28
+ plan_envelope,
29
+ vision,
30
+ )
31
+ from localmodels import catalog as cat
32
+ from localmodels.context_policy import AgentPosture
33
+ from localmodels.estimator import (
34
+ AGENT_VRAM_RESERVE_BYTES,
35
+ METAL_VRAM_RESERVE_BYTES,
36
+ PhysicsRefusal,
37
+ )
38
+ from localmodels.library_model import (
39
+ KV_CACHE_QUANTS,
40
+ KvCacheQuant,
41
+ MemoryPressureWarning,
42
+ MemoryPressureWarningLevel,
43
+ PostureSummary,
44
+ )
45
+ from localmodels.library_pricing import LiveMemoryUnavailable, Model, memory_bytes
46
+ from localmodels.probe import HostFacts
47
+ from localmodels.records import Plan
48
+
49
+ ELASTIC_CONTEXT_STEPS: tuple[int, ...] = (65536, 32768, 16384)
50
+ ELASTIC_FLOOR_WINDOW: int = 16384
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class PostureRung:
55
+ """One rung on the elastic agent posture ladder, ordered best -> most compact."""
56
+
57
+ posture: AgentPosture
58
+ degraded: bool
59
+ reason: str | None # None | "reduced_slots" | "reduced_context"
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class PostureSpec:
64
+ """Observable summary of a requested or effective agent posture."""
65
+
66
+ context_tokens: int
67
+ slots: int
68
+ kv_types: tuple[str, str]
69
+
70
+ def to_summary(self) -> PostureSummary:
71
+ summary: PostureSummary = {"context_tokens": self.context_tokens, "slots": self.slots}
72
+ k, v = self.kv_types
73
+ if k == v and k in KV_CACHE_QUANTS:
74
+ summary["kv_cache_quant"] = cast(KvCacheQuant, k)
75
+ return summary
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class ElasticPlan:
80
+ """Result of dual-tier admission + elastic posture pricing."""
81
+
82
+ plan: Plan
83
+ rung_index: int
84
+ ladder: tuple[PostureRung, ...]
85
+ requested_posture: PostureSpec
86
+ effective_posture: PostureSpec
87
+ degraded: bool
88
+ degradation_reason: str | None
89
+ memory_pressure_warning: MemoryPressureWarning | None
90
+ forced: bool
91
+ admission: budget.AdmissionBudget
92
+
93
+
94
+ class ElasticRoomError(deploy.AgentMemoryError):
95
+ """Hard-ceiling refusal carrying actionable dual-tier headroom diagnostics."""
96
+
97
+ def __init__(
98
+ self,
99
+ message: str,
100
+ *,
101
+ pool: str,
102
+ need_bytes: int,
103
+ free_bytes: int,
104
+ memory: str,
105
+ wired_headroom_bytes: int | None = None,
106
+ soft_available_bytes: int | None = None,
107
+ pressure_level: int | None = None,
108
+ can_force: bool = False,
109
+ ) -> None:
110
+ super().__init__(message, PhysicsRefusal(need_bytes, free_bytes, message), memory)
111
+ self.pool = pool
112
+ self.min_need_bytes = need_bytes
113
+ self.wired_headroom_bytes = wired_headroom_bytes
114
+ self.soft_available_bytes = soft_available_bytes
115
+ self.shortfall_bytes = max(0, need_bytes - free_bytes)
116
+ self.pressure_level = pressure_level
117
+ self.can_force = can_force
118
+
119
+
120
+ def elastic_posture_ladder(
121
+ base: AgentPosture,
122
+ *,
123
+ backend: str,
124
+ native_ctx: int = 0,
125
+ max_agent_window: int = 0,
126
+ ) -> tuple[PostureRung, ...]:
127
+ """Ordered agent posture ladder starting at the requested posture and stepping down cleanly:
128
+ 0. Requested posture (full slots, full context floor/target, q8_0 -> compact KV, FA on)
129
+ 1. Step down parallel slots (2 -> 1) at the standard context floor (64K)
130
+ 2. Step down context window to 32K (1 slot)
131
+ 3. Step down context window to 16K floor (1 slot)
132
+ """
133
+ requested = context_policy.posture_for(base, backend)
134
+ if max_agent_window > 0:
135
+ requested = replace(
136
+ requested,
137
+ target=min(requested.target, max_agent_window),
138
+ preferred=min(requested.preferred, max_agent_window),
139
+ )
140
+ rungs: list[PostureRung] = [PostureRung(requested, degraded=False, reason=None)]
141
+ max_ctx = native_ctx if native_ctx > 0 else requested.target
142
+ if requested.slots > 1 and min(requested.floor, max_ctx) >= requested.floor:
143
+ rungs.append(
144
+ PostureRung(
145
+ replace(
146
+ requested,
147
+ slots=1,
148
+ floor=requested.floor,
149
+ preferred=min(requested.preferred, requested.floor),
150
+ target=min(requested.target, requested.floor),
151
+ prompt_cache_mib=min(
152
+ requested.prompt_cache_mib, requested.prompt_cache_min_mib
153
+ ),
154
+ ),
155
+ degraded=True,
156
+ reason="reduced_slots",
157
+ )
158
+ )
159
+ cache_caps = {32768: 1024, 16384: 512}
160
+ for window in ELASTIC_CONTEXT_STEPS:
161
+ if window >= requested.floor:
162
+ continue
163
+ if native_ctx > 0 and window > native_ctx:
164
+ continue
165
+ rungs.append(
166
+ PostureRung(
167
+ replace(
168
+ requested,
169
+ slots=1,
170
+ floor=window,
171
+ preferred=window,
172
+ target=window,
173
+ prompt_cache_mib=min(
174
+ requested.prompt_cache_mib,
175
+ cache_caps.get(window, requested.prompt_cache_min_mib),
176
+ ),
177
+ ),
178
+ degraded=True,
179
+ reason="reduced_context",
180
+ )
181
+ )
182
+ return tuple(rungs)
183
+
184
+
185
+ def _project_cuda_uma(
186
+ facts: HostFacts, unified: int, target: int, *, bypass_working_set: bool
187
+ ) -> HostFacts:
188
+ seen = copy.deepcopy(facts)
189
+ need = target + AGENT_VRAM_RESERVE_BYTES
190
+ raw = int(math.ceil(need / (1 - budget._UMA_HEADROOM_FRACTION)))
191
+ while int(raw * (1 - budget._UMA_HEADROOM_FRACTION)) < need:
192
+ raw += 1
193
+ raw = raw if bypass_working_set else min(unified, raw)
194
+ if bypass_working_set and isinstance(cuda_pool := seen.get("cuda_pool"), dict):
195
+ cuda_pool["total_bytes"], cuda_pool["integrated"] = max(unified, raw), True
196
+ for gpu in seen.get("gpus") or []:
197
+ if gpu.get("vendor") == "nvidia" and gpu.get("mig_mode") != "enabled":
198
+ gpu["free_bytes"], gpu["used_bytes"] = 0, gpu["total_bytes"]
199
+ break
200
+ ram = seen["ram"]
201
+ if bypass_working_set:
202
+ ram["total_bytes"] = max(int(ram["total_bytes"]), raw)
203
+ if (cgroup := seen.get("cgroup_memory")) is not None:
204
+ if (limit := cgroup.get("limit_bytes")) is not None and limit < raw:
205
+ cgroup["limit_bytes"] = raw
206
+ cgroup["usage_bytes"] = 0
207
+ ram["available_bytes"] = min(int(ram["total_bytes"]), raw)
208
+ return seen
209
+
210
+
211
+ def facts_for_budget(
212
+ facts: HostFacts,
213
+ pool: str,
214
+ target_bytes: int,
215
+ *,
216
+ wired_cap_bytes: int | None = None,
217
+ bypass_working_set: bool = False,
218
+ ) -> HostFacts:
219
+ """Project ``facts`` so ``deploy.build_plan`` prices ``pool`` against ``target_bytes``
220
+ (unified/total) and optional ``wired_cap_bytes`` (Metal GPU wired headroom)."""
221
+ target = max(0, target_bytes)
222
+ if pool == "unified" and metal.supported(facts):
223
+ seen = copy.deepcopy(facts)
224
+ ram = seen["ram"]
225
+ needed_avail = target + metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
226
+ ram["available_bytes"] = (
227
+ needed_avail if bypass_working_set else min(int(ram["total_bytes"]), needed_avail)
228
+ )
229
+ ram["pressure_level"] = metal.PRESSURE_NORMAL
230
+ ram.pop("pressure_kept_bytes", None)
231
+ if isinstance(metal_doc := seen.get("metal"), dict):
232
+ ceiling = (
233
+ max(0, wired_cap_bytes) + METAL_VRAM_RESERVE_BYTES
234
+ if wired_cap_bytes is not None
235
+ else max(metal.wired_ceiling_bytes(facts), target + METAL_VRAM_RESERVE_BYTES)
236
+ if bypass_working_set
237
+ else metal.wired_ceiling_bytes(facts)
238
+ )
239
+ metal_doc["recommended_max_working_set_bytes"] = ceiling
240
+ return seen
241
+ if pool == "unified" and (unified := budget.unified_pool_bytes(facts)) is not None:
242
+ return _project_cuda_uma(facts, unified, target, bypass_working_set=bypass_working_set)
243
+ if (idx := library_pricing.gpu_index(pool)) is not None:
244
+ seen = copy.deepcopy(facts)
245
+ for gpu in seen.get("gpus") or []:
246
+ if gpu["index"] == idx:
247
+ free = target + AGENT_VRAM_RESERVE_BYTES
248
+ gpu["free_bytes"] = free if bypass_working_set else min(gpu["total_bytes"], free)
249
+ gpu["used_bytes"] = max(0, gpu["total_bytes"] - gpu["free_bytes"])
250
+ break
251
+ return seen
252
+ return facts
253
+
254
+
255
+ def _plan_posture(plan: Plan) -> PostureSpec:
256
+ launch = plan["launch"]
257
+ window = int(str(launch.get("window") or 0))
258
+ slots = int(str(launch.get("slots") or 1))
259
+ raw_kv = launch.get("kv_types")
260
+ kv_list = (
261
+ list(raw_kv) if isinstance(raw_kv, list | tuple) and len(raw_kv) == 2 else ["q8_0", "q8_0"]
262
+ )
263
+ return PostureSpec(
264
+ context_tokens=window, slots=slots, kv_types=(str(kv_list[0]), str(kv_list[1]))
265
+ )
266
+
267
+
268
+ def _vram_bytes(plan: Plan) -> int:
269
+ return int(str(plan["launch"].get("vram_bytes") or 0))
270
+
271
+
272
+ def _floor_need_bytes(
273
+ facts: HostFacts, model: Model, pool: str, floor_posture: AgentPosture
274
+ ) -> tuple[int, int]:
275
+ """(total_need_bytes, wired_need_bytes) at ``floor_posture`` (compact KV)."""
276
+ active = model.entry.agent_posture(floor_posture)
277
+ profile = estimator.eager(model.entry.profile(model.variant))
278
+ window = min(active.floor, profile.n_ctx_train) if profile.n_ctx_train > 0 else active.floor
279
+ kv = active.kv_types[-1]
280
+ mtp = bool(model.entry.mtp_capable and model.entry.agent_mtp and active.mtp_draft_depth > 0)
281
+ core = estimator.agent_footprint_bytes(
282
+ profile, window, slots=active.slots, kv_types=kv, ubatch=active.ubatch, mtp=mtp
283
+ )
284
+ if pool == "unified" and metal.supported(facts):
285
+ compact_posture = replace(active, kv_types=(kv,))
286
+ vis = (
287
+ vision.llama_device_bytes(model.entry.mmproj, "gpu")
288
+ if model.entry.mmproj is not None
289
+ and vision.llama_reader_enabled(model.entry.mmproj, compact_posture.vision)
290
+ else 0
291
+ )
292
+ host_side = context_policy.cache_floor_bytes(
293
+ compact_posture, profile
294
+ ) + context_policy.metal_host_bytes(profile, compact_posture)
295
+ wired_need = core + vis
296
+ return wired_need + host_side, wired_need
297
+ if pool == "unified":
298
+ vis = (
299
+ vision.llama_device_bytes(model.entry.mmproj, "gpu")
300
+ if model.entry.mmproj is not None
301
+ and vision.llama_reader_enabled(model.entry.mmproj, active.vision)
302
+ else 0
303
+ )
304
+ return core + vis, core + vis
305
+ if library_pricing.gpu_index(pool) is not None and model.entry.mmproj is not None:
306
+ total = library_pricing.pool_total(facts, pool)
307
+ mode = vision.reader(active.vision, total, unified=False)
308
+ vis = vision.llama_device_bytes(model.entry.mmproj, mode)
309
+ return core + vis, core + vis
310
+ return core, core
311
+
312
+
313
+ def minimum_memory_bytes(facts: HostFacts, model: Model, pool: str) -> int | None:
314
+ """Estimated footprint at the lowest elastic posture rung (floor ctx x 1 slot, compact KV)."""
315
+ if (
316
+ not pool
317
+ or pool == "system"
318
+ or model.entry.runtime != "llama.cpp"
319
+ or library_kept.retired(model.entry)
320
+ ):
321
+ return None
322
+ if pool not in library_pricing.pools(facts):
323
+ return None
324
+ backend = "metal" if pool == "unified" and metal.supported(facts) else "cuda"
325
+ ladder = elastic_posture_ladder(
326
+ library_pricing.posture(),
327
+ backend=backend,
328
+ native_ctx=model.entry.n_ctx_train,
329
+ max_agent_window=model.entry.max_agent_window,
330
+ )
331
+ floor_rung = ladder[-1]
332
+ compact_floor = replace(
333
+ floor_rung.posture, kv_types=(floor_rung.posture.kv_types[-1],), kv_pinned=True
334
+ )
335
+ min_need, _ = _floor_need_bytes(facts, model, pool, compact_floor)
336
+ return min_need
337
+
338
+
339
+ def validate_plan_bounds(
340
+ facts: HostFacts,
341
+ model: Model,
342
+ pool: str,
343
+ plan: Plan,
344
+ catalog: tuple[cat.CatalogEntry, ...],
345
+ *,
346
+ check_pool_total: bool = True,
347
+ check_host_ram: bool = True,
348
+ ) -> None:
349
+ """Reject a plan exceeding ``pool``'s total capacity or host RAM on a discrete GPU."""
350
+ if check_pool_total:
351
+ total = library_pricing.pool_total(facts, pool)
352
+ used = memory_bytes(plan)
353
+ if used > total:
354
+ refused = PhysicsRefusal(
355
+ needed_bytes=used,
356
+ available_bytes=total,
357
+ message=f"{model.id} needs {used} bytes, exceeding pool {pool} total {total} bytes",
358
+ )
359
+ raise deploy.AgentMemoryError(
360
+ refused.message,
361
+ refused,
362
+ "unified memory" if pool == "unified" else "GPU memory",
363
+ )
364
+ if check_host_ram and library_pricing.gpu_index(pool) is not None:
365
+ needed_ram = (
366
+ library_pricing.host_ram_bytes(plan, catalog) + budget.HARNESS_RAM + budget.RAM_FLOOR
367
+ )
368
+ _, avail_ram = budget.host_ram(facts)
369
+ if needed_ram > avail_ram:
370
+ refused = PhysicsRefusal(
371
+ needed_bytes=needed_ram,
372
+ available_bytes=avail_ram,
373
+ message=(
374
+ f"{model.id} needs {needed_ram} bytes of system memory, "
375
+ f"exceeding {avail_ram} bytes available"
376
+ ),
377
+ )
378
+ raise deploy.AgentMemoryError(refused.message, refused, "system memory")
379
+
380
+
381
+ @dataclass(frozen=True)
382
+ class _PriceCtx:
383
+ facts: HostFacts
384
+ model: Model
385
+ pool: str
386
+ placement: str
387
+ base_dir: str
388
+ catalog: tuple[cat.CatalogEntry, ...]
389
+ port: int
390
+
391
+
392
+ def _price_rung(
393
+ ctx: _PriceCtx,
394
+ rung_posture: AgentPosture,
395
+ *,
396
+ budget_bytes: int,
397
+ wired_cap_bytes: int | None = None,
398
+ check_pool_total: bool = True,
399
+ check_host_ram: bool = True,
400
+ bypass_working_set: bool = False,
401
+ ) -> Plan:
402
+ priced_facts = facts_for_budget(
403
+ ctx.facts,
404
+ ctx.pool,
405
+ budget_bytes,
406
+ wired_cap_bytes=wired_cap_bytes,
407
+ bypass_working_set=bypass_working_set,
408
+ )
409
+ plan = deploy.build_plan(
410
+ hosts.LOCAL_ID,
411
+ priced_facts,
412
+ deploy.PlanOptions(
413
+ model_id=ctx.model.entry.id,
414
+ placement_id=ctx.placement,
415
+ port=ctx.port,
416
+ base_dir=ctx.base_dir,
417
+ hf_download_endpoint=deploy.hf_endpoint(),
418
+ hf_api_endpoint=deploy.hf_endpoint(),
419
+ agent=rung_posture,
420
+ quant=ctx.model.variant.quant,
421
+ ),
422
+ entries=ctx.catalog,
423
+ resolver=deploy.catalog_pins,
424
+ )
425
+ validate_plan_bounds(
426
+ ctx.facts,
427
+ ctx.model,
428
+ ctx.pool,
429
+ plan,
430
+ ctx.catalog,
431
+ check_pool_total=check_pool_total,
432
+ check_host_ram=check_host_ram,
433
+ )
434
+ return plan
435
+
436
+
437
+ def _fits_hard_ceiling(plan: Plan, adm: budget.AdmissionBudget) -> bool:
438
+ if adm.backend == "metal":
439
+ return _vram_bytes(plan) <= adm.hard_ceiling_bytes and (
440
+ memory_bytes(plan) <= adm.physical_limit_bytes
441
+ )
442
+ return memory_bytes(plan) <= adm.hard_ceiling_bytes
443
+
444
+
445
+ def _try_tier1_ladder(
446
+ ctx: _PriceCtx,
447
+ ladder: tuple[PostureRung, ...],
448
+ requested_spec: PostureSpec,
449
+ adm: budget.AdmissionBudget,
450
+ min_rung_index: int,
451
+ ) -> tuple[ElasticPlan | None, deploy.AgentMemoryError | None]:
452
+ wired_cap = adm.wired_headroom_bytes if adm.backend == "metal" else None
453
+ tier1_budget = (
454
+ adm.soft_budget_bytes
455
+ if adm.backend == "metal"
456
+ else min(adm.soft_budget_bytes, adm.hard_ceiling_bytes)
457
+ )
458
+ ram_shortfall: deploy.AgentMemoryError | None = None
459
+ for idx in range(max(0, min(min_rung_index, len(ladder))), len(ladder)):
460
+ rung = ladder[idx]
461
+ try:
462
+ plan = _price_rung(
463
+ ctx, rung.posture, budget_bytes=tier1_budget, wired_cap_bytes=wired_cap
464
+ )
465
+ except deploy.AgentMemoryError as exc:
466
+ if exc.memory == "system memory":
467
+ ram_shortfall = exc
468
+ continue
469
+ if _fits_hard_ceiling(plan, adm):
470
+ eff = _plan_posture(plan)
471
+ return (
472
+ ElasticPlan(
473
+ plan=plan,
474
+ rung_index=idx,
475
+ ladder=ladder,
476
+ requested_posture=eff if not rung.degraded else requested_spec,
477
+ effective_posture=eff,
478
+ degraded=rung.degraded,
479
+ degradation_reason=rung.reason,
480
+ memory_pressure_warning=None,
481
+ forced=False,
482
+ admission=adm,
483
+ ),
484
+ None,
485
+ )
486
+ return None, ram_shortfall
487
+
488
+
489
+ def _force_within_hard_limits(
490
+ adm: budget.AdmissionBudget, min_need: int, min_wired_need: int
491
+ ) -> bool:
492
+ """Whether ``--force`` stays within non-overridable hardware ceilings (non-critical pressure,
493
+ physical memory limit, and on Apple Silicon the kernel/Metal wired ceiling)."""
494
+ if adm.critical_pressure or min_need > adm.physical_limit_bytes:
495
+ return False
496
+ return not (
497
+ adm.backend == "metal"
498
+ and adm.wired_ceiling_bytes is not None
499
+ and min_wired_need > adm.wired_ceiling_bytes
500
+ )
501
+
502
+
503
+ def _price_forced_floor(
504
+ ctx: _PriceCtx,
505
+ compact_floor: AgentPosture,
506
+ adm: budget.AdmissionBudget,
507
+ min_need: int,
508
+ min_wired_need: int,
509
+ *,
510
+ raise_system_ram: bool = False,
511
+ ) -> Plan | None:
512
+ """Price the compact floor under ``--force`` while enforcing hard physical ceilings."""
513
+ if not _force_within_hard_limits(adm, min_need, min_wired_need):
514
+ return None
515
+ wired_cap = adm.wired_ceiling_bytes if adm.backend == "metal" else None
516
+ try:
517
+ plan = _price_rung(
518
+ ctx,
519
+ compact_floor,
520
+ budget_bytes=adm.physical_limit_bytes,
521
+ wired_cap_bytes=wired_cap,
522
+ check_pool_total=False,
523
+ check_host_ram=True,
524
+ bypass_working_set=True,
525
+ )
526
+ except deploy.AgentMemoryError as exc:
527
+ if raise_system_ram and exc.memory == "system memory":
528
+ raise ElasticRoomError(
529
+ str(exc),
530
+ pool="system",
531
+ need_bytes=exc.needed_bytes,
532
+ free_bytes=exc.available_bytes,
533
+ memory="system memory",
534
+ soft_available_bytes=exc.available_bytes,
535
+ can_force=False,
536
+ ) from None
537
+ return None
538
+ wired_ok = (
539
+ adm.backend != "metal"
540
+ or adm.wired_ceiling_bytes is None
541
+ or _vram_bytes(plan) <= adm.wired_ceiling_bytes
542
+ )
543
+ return plan if wired_ok and memory_bytes(plan) <= adm.physical_limit_bytes else None
544
+
545
+
546
+ def _try_floor_admission(
547
+ ctx: _PriceCtx,
548
+ ladder: tuple[PostureRung, ...],
549
+ compact_floor: AgentPosture,
550
+ requested_spec: PostureSpec,
551
+ adm: budget.AdmissionBudget,
552
+ *,
553
+ min_need: int,
554
+ min_wired_need: int,
555
+ allow_overcommit: bool,
556
+ force: bool,
557
+ min_rung_index: int,
558
+ ) -> ElasticPlan | None:
559
+ floor_idx = len(ladder) - 1
560
+ if (
561
+ allow_overcommit
562
+ and adm.allows_soft_overcommit
563
+ and not adm.critical_pressure
564
+ and adm.pressure_level != metal.PRESSURE_WARN
565
+ and min_rung_index <= floor_idx
566
+ and min_wired_need <= adm.hard_ceiling_bytes
567
+ and min_need <= adm.physical_limit_bytes
568
+ ):
569
+ try:
570
+ plan = _price_rung(
571
+ ctx,
572
+ compact_floor,
573
+ budget_bytes=adm.physical_limit_bytes,
574
+ wired_cap_bytes=adm.hard_ceiling_bytes,
575
+ )
576
+ except deploy.AgentMemoryError:
577
+ plan = None
578
+ if plan is not None and _fits_hard_ceiling(plan, adm):
579
+ level: MemoryPressureWarningLevel = "soft"
580
+ warning: MemoryPressureWarning = {
581
+ "level": level,
582
+ "pool": ctx.pool,
583
+ "free_bytes": adm.soft_budget_bytes,
584
+ "budget_bytes": adm.hard_ceiling_bytes,
585
+ }
586
+ return ElasticPlan(
587
+ plan=plan,
588
+ rung_index=floor_idx,
589
+ ladder=ladder,
590
+ requested_posture=requested_spec,
591
+ effective_posture=_plan_posture(plan),
592
+ degraded=True,
593
+ degradation_reason="above_soft_budget",
594
+ memory_pressure_warning=warning,
595
+ forced=False,
596
+ admission=adm,
597
+ )
598
+ if force:
599
+ plan = _price_forced_floor(
600
+ ctx, compact_floor, adm, min_need, min_wired_need, raise_system_ram=True
601
+ )
602
+ if plan is not None:
603
+ forced_warning: MemoryPressureWarning = {
604
+ "level": "high",
605
+ "pool": ctx.pool,
606
+ "free_bytes": min(adm.soft_budget_bytes, adm.hard_ceiling_bytes),
607
+ "budget_bytes": adm.physical_limit_bytes,
608
+ }
609
+ return ElasticPlan(
610
+ plan=plan,
611
+ rung_index=floor_idx,
612
+ ladder=ladder,
613
+ requested_posture=requested_spec,
614
+ effective_posture=_plan_posture(plan),
615
+ degraded=True,
616
+ degradation_reason="forced_overcommit",
617
+ memory_pressure_warning=forced_warning,
618
+ forced=True,
619
+ admission=adm,
620
+ )
621
+ return None
622
+
623
+
624
+ def price_elastic(
625
+ facts: HostFacts,
626
+ model: Model,
627
+ pool: str,
628
+ base_dir: str,
629
+ catalog: tuple[cat.CatalogEntry, ...],
630
+ port: int = deploy.DEFAULT_PORT,
631
+ *,
632
+ allow_overcommit: bool = True,
633
+ force: bool = False,
634
+ min_rung_index: int = 0,
635
+ ) -> ElasticPlan:
636
+ """Dual-tier memory admission + elastic posture ladder for loading ``model`` on ``pool``."""
637
+ placement = library_pricing.pools(facts).get(pool)
638
+ if placement is None:
639
+ raise plan_envelope.PlanError(f"this computer has no pool {pool}")
640
+ if library_kept.retired(model.entry):
641
+ raise plan_envelope.PlanError(f"this version no longer ships {model.id}")
642
+ adm = budget.admission_budget(facts, pool)
643
+ if adm is None:
644
+ raise plan_envelope.PlanError(f"this computer has no pool {pool}")
645
+ if model.entry.runtime == "strata-poly":
646
+ poly_plan = library_poly.price(
647
+ facts,
648
+ model.entry.id,
649
+ pool,
650
+ base_dir,
651
+ port,
652
+ library_pricing.posture(),
653
+ require_live=True,
654
+ )
655
+ eff = _plan_posture(poly_plan)
656
+ return ElasticPlan(poly_plan, 0, (), eff, eff, False, None, None, False, adm)
657
+ ladder = elastic_posture_ladder(
658
+ library_pricing.posture(),
659
+ backend=adm.backend,
660
+ native_ctx=model.entry.n_ctx_train,
661
+ max_agent_window=model.entry.max_agent_window,
662
+ )
663
+ floor_rung = ladder[-1]
664
+ compact_floor = replace(
665
+ floor_rung.posture, kv_types=(floor_rung.posture.kv_types[-1],), kv_pinned=True
666
+ )
667
+ min_need, min_wired_need = _floor_need_bytes(facts, model, pool, compact_floor)
668
+ if pool == "unified" and metal.supported(facts) and (problem := metal.problem(facts)):
669
+ if metal.is_critical_pressure(facts):
670
+ raise ElasticRoomError(
671
+ problem,
672
+ pool="unified",
673
+ need_bytes=min_need,
674
+ free_bytes=0,
675
+ memory="unified memory",
676
+ wired_headroom_bytes=0,
677
+ soft_available_bytes=0,
678
+ pressure_level=adm.pressure_level,
679
+ can_force=False,
680
+ )
681
+ raise LiveMemoryUnavailable(problem)
682
+
683
+ req_p = model.entry.agent_posture(ladder[0].posture)
684
+ req_window = (
685
+ min(req_p.floor, model.entry.n_ctx_train) if model.entry.n_ctx_train > 0 else req_p.floor
686
+ )
687
+ requested_spec = PostureSpec(
688
+ context_tokens=req_window, slots=req_p.slots, kv_types=req_p.kv_types[0]
689
+ )
690
+
691
+ ctx = _PriceCtx(facts, model, pool, placement, base_dir, catalog, port)
692
+ admitted, ram_shortfall = _try_tier1_ladder(ctx, ladder, requested_spec, adm, min_rung_index)
693
+ if admitted is not None:
694
+ return admitted
695
+ if ram_shortfall is not None:
696
+ raise ElasticRoomError(
697
+ str(ram_shortfall),
698
+ pool="system",
699
+ need_bytes=ram_shortfall.needed_bytes,
700
+ free_bytes=ram_shortfall.available_bytes,
701
+ memory="system memory",
702
+ soft_available_bytes=ram_shortfall.available_bytes,
703
+ can_force=False,
704
+ )
705
+ floor_admitted = _try_floor_admission(
706
+ ctx,
707
+ ladder,
708
+ compact_floor,
709
+ requested_spec,
710
+ adm,
711
+ min_need=min_need,
712
+ min_wired_need=min_wired_need,
713
+ allow_overcommit=allow_overcommit,
714
+ force=force,
715
+ min_rung_index=min_rung_index,
716
+ )
717
+ if floor_admitted is not None:
718
+ return floor_admitted
719
+
720
+ memory_label = "unified memory" if pool == "unified" else "GPU memory"
721
+ can_force = (
722
+ not force
723
+ and _price_forced_floor(ctx, compact_floor, adm, min_need, min_wired_need) is not None
724
+ )
725
+ wired_blocked = adm.backend == "metal" and min_wired_need > adm.hard_ceiling_bytes
726
+ phys_blocked = min_need > adm.physical_limit_bytes
727
+ soft_blocked = adm.backend == "metal" and not wired_blocked and not phys_blocked
728
+ report_need = min_wired_need if wired_blocked else min_need
729
+ if wired_blocked or adm.backend != "metal":
730
+ report_free = adm.hard_ceiling_bytes
731
+ elif phys_blocked:
732
+ report_free = adm.physical_limit_bytes
733
+ else:
734
+ report_free = adm.soft_budget_bytes
735
+ ceiling_label = "soft budget" if soft_blocked else "hard ceiling"
736
+ raise ElasticRoomError(
737
+ f"{model.id} does not fit {pool} now (floor needs {report_need} bytes, {ceiling_label} "
738
+ f"{report_free} bytes)",
739
+ pool=pool,
740
+ need_bytes=report_need,
741
+ free_bytes=report_free,
742
+ memory=memory_label,
743
+ wired_headroom_bytes=adm.wired_headroom_bytes,
744
+ soft_available_bytes=adm.soft_budget_bytes,
745
+ pressure_level=adm.pressure_level,
746
+ can_force=can_force,
747
+ )