@simplexai/localmodels-linux-arm64 0.1.0-dev.57 → 0.1.0-dev.58

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