@simplexai/localmodels-darwin-x64 0.1.0-dev.111 → 0.1.0-dev.112

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 (33) hide show
  1. package/README.md +1 -1
  2. package/bootstrap.identity +1 -1
  3. package/bootstrap.sha256 +32 -32
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/catalog.json +64 -40
  6. package/modules/localmodels/catalog_recipes.py +10 -1
  7. package/modules/localmodels/deploy.py +9 -4
  8. package/modules/localmodels/engine_adapters/suite_plan.py +4 -0
  9. package/modules/localmodels/engines.json +96 -91
  10. package/modules/localmodels/engines.py +9 -2
  11. package/modules/localmodels/library_cli.py +2 -1
  12. package/modules/localmodels/library_jobs.py +47 -11
  13. package/modules/localmodels/library_model.py +3 -1
  14. package/modules/localmodels/library_poly.py +75 -36
  15. package/modules/localmodels/library_pricing.py +125 -20
  16. package/modules/localmodels/library_serve.py +68 -14
  17. package/modules/localmodels/library_state.py +3 -0
  18. package/modules/localmodels/library_status.py +11 -1
  19. package/modules/localmodels/region.py +5 -9
  20. package/modules/localmodels/remote_ops_download.py +14 -5
  21. package/modules/localmodels/stack_suite.py +14 -1
  22. package/modules/localmodels/suite.py +30 -5
  23. package/modules/localmodels/web/view/i18n.js +1 -1
  24. package/modules/localmodels/web/view/view.js +11 -3
  25. package/modules/{simplex_localmodels-0.1.0.dev111.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/METADATA +1 -1
  26. package/modules/{simplex_localmodels-0.1.0.dev111.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/RECORD +28 -28
  27. package/package.json +1 -1
  28. package/tool.json +1 -1
  29. /package/modules/{simplex_localmodels-0.1.0.dev111.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/WHEEL +0 -0
  30. /package/modules/{simplex_localmodels-0.1.0.dev111.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/entry_points.txt +0 -0
  31. /package/modules/{simplex_localmodels-0.1.0.dev111.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/licenses/LICENSE +0 -0
  32. /package/modules/{simplex_localmodels-0.1.0.dev111.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/licenses/NOTICE +0 -0
  33. /package/modules/{simplex_localmodels-0.1.0.dev111.dist-info → simplex_localmodels-0.1.0.dev112.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -87,14 +87,25 @@ def _validated_for(recipe: suite.SuiteRecipe, platform: str) -> bool:
87
87
  return key in scope or (key == "win32" and "linux" in scope)
88
88
 
89
89
 
90
+ def _metal_priced(recipe: suite.SuiteRecipe) -> bool:
91
+ """Whether the catalog prices this recipe for Apple Silicon Metal.
92
+
93
+ A recipe declares a ``darwin`` ``card_args`` tier when it was planned and measured on Metal:
94
+ that tier sets the unified-memory window (and the profile's parallel/batching where it
95
+ differs from the CUDA one), so a Metal plan and its unified footprint are the ones the
96
+ catalog documents. Recipes without one only carry CUDA geometry.
97
+ """
98
+ return any("darwin" in group.get("platforms", ()) for group in recipe.get("card_args") or ())
99
+
100
+
90
101
  def _candidate_for(recipe: suite.SuiteRecipe, platform: str) -> bool:
91
- # A candidate has no validated_on scope (it needs status validated), and Metal PolyStrata
92
- # recipes are priced from their own validated KV geometry and overhead: until evidence
93
- # promotes a candidate on Apple Silicon, list it on the CUDA platforms only.
102
+ # A candidate has no validated_on scope (that needs status validated); it is listed on the
103
+ # CUDA platforms, and on Apple Silicon only when the catalog prices it for Metal
104
+ # (``_metal_priced``), so no Mac is offered a plan priced from CUDA-only geometry.
94
105
  return (
95
106
  bool(recipe.get("library"))
96
107
  and recipe.get("status") == "candidate"
97
- and platform != "darwin"
108
+ and (platform != "darwin" or _metal_priced(recipe))
98
109
  and stack_suite.built_for(recipe, platform)
99
110
  )
100
111
 
@@ -261,43 +272,62 @@ def _ram_experts_bytes(recipe: suite.SuiteRecipe) -> int:
261
272
 
262
273
 
263
274
  def _calibrate_host_ram(plan: Plan, recipe: suite.SuiteRecipe, gpu: GPU) -> None:
264
- """Discount unused expert spill when ``gpu`` fits most/all weights in VRAM.
275
+ """Price the experts the card keeps out of VRAM against host RAM.
265
276
 
266
277
  Recipes targeting 8-16 GB cards (such as ``inkling-2-mini-q3-poly``) size
267
278
  ``memory_estimate_bytes`` for heavy 8 GB RAM expert offloading, either through an explicit
268
279
  ``--ram-experts-mib`` pool or through the ``host_ram_spill_bytes`` their 8 GB plan spills.
269
- On a 16 GB card where nearly all experts stay in VRAM (~1.52 GiB host RAM actual), charging
270
- the full 8 GB spill blocks ``library load`` at ~16.89 GB free RAM; Qwen4's ``--basinkv``
271
- profiles never pass ``--ram-experts-mib`` (it evicts the 11.52 GB PLE shard from page cache)
272
- but still spill their 14 GiB of 8 GB-tier experts.
273
-
274
- The PLE shard and BasinKV's pinned host KV are never discounted: they stay in host RAM on
275
- every card.
280
+ A bigger card discounts the pool it does not need: on a 16 GB card where nearly all experts
281
+ stay in VRAM (~1.52 GiB host RAM actual), charging the full 8 GB spill blocks ``library
282
+ load`` at ~16.89 GB free RAM. Qwen4's ``--basinkv`` profiles never pass ``--ram-experts-mib``
283
+ (it evicts the 11.52 GB PLE shard from page cache) but still spill their 14 GiB of 8 GB-tier
284
+ experts.
285
+
286
+ The same physics runs the other way on a card below the recipe's full-cache tier: every
287
+ expert the expert cache cannot hold lives in host RAM, so the plan is charged the cold
288
+ experts its declared spill does not already cover. That is what makes an 8 GB card report a
289
+ host-RAM shortfall for ``qwen4-35b-a3b-q4-poly`` (33.75 GiB of weights + PLE cannot fit in
290
+ 32 GB) instead of a bogus VRAM one, and what lets ``inkling-2-mini-q4-poly`` run at 64K on
291
+ the same host.
292
+
293
+ The PLE shard is never discounted: it stays in host RAM on every card, and BasinKV's pinned
294
+ host KV (726 MiB at 128K, ~1.45 GiB at 256K measured on an 8 GB budget) already rides inside
295
+ the recipe's estimate, so the discount only gives back the expert pool.
276
296
  """
277
297
  ram_experts = _ram_experts_bytes(recipe) or max(0, int(recipe.get("host_ram_spill_bytes") or 0))
278
298
  recipe_base = int(recipe.get("memory_estimate_bytes") or 0)
279
- if ram_experts <= 0 or recipe_base <= ram_experts:
299
+ if ram_experts <= 0 or recipe_base <= 0:
280
300
  return
281
301
  weight_bytes = suite.poly_weight_bytes(recipe)
282
302
  if weight_bytes <= 0:
283
303
  return
284
304
  gpu_weights = max(0, weight_bytes - int(recipe.get("embd_table_bytes") or 0))
285
305
  vram_for_weights = max(0, gpu["free_bytes"] - suite.VRAM_NON_EXPERT_BYTES)
286
- spilled = min(ram_experts, max(0, gpu_weights - vram_for_weights))
287
- saved = ram_experts - spilled
288
- if saved <= 0:
289
- return
306
+ cold = max(0, gpu_weights - vram_for_weights)
290
307
  plan_mem = int(str(plan["launch"]["memory_estimate_bytes"]))
291
- calibrated = max(0, plan_mem - saved)
292
- plan["launch"]["memory_estimate_bytes"] = calibrated
308
+ if cold <= ram_experts and recipe_base <= ram_experts:
309
+ return # the estimate does not cover its own declared pool: nothing to give back
310
+ if cold <= ram_experts:
311
+ # The estimate already holds the declared pool: give back the part the card does not use.
312
+ delta = cold - ram_experts
313
+ elif recipe_base > ram_experts:
314
+ # The estimate holds the declared pool, so charge only the experts beyond it.
315
+ delta = cold - ram_experts
316
+ else:
317
+ # The estimate never held the pool (the smallest tier's experts are page cache), so every
318
+ # cold expert is extra host RAM.
319
+ delta = cold
320
+ if delta == 0:
321
+ return
322
+ plan["launch"]["memory_estimate_bytes"] = max(0, plan_mem + delta)
293
323
  limits = plan["service"].get("limits")
294
324
  if isinstance(limits, dict) and "MemoryHigh" in limits:
295
325
  old_high = suite.size_bytes(limits["MemoryHigh"])
296
- new_high = max(calibrated, old_high - saved)
326
+ new_high = max(0, old_high + delta)
297
327
  limits["MemoryHigh"] = f"{(new_high + (1 << 20) - 1) >> 20}M"
298
328
  if "MemoryMax" in limits:
299
329
  old_max = suite.size_bytes(limits["MemoryMax"])
300
- new_max = max(new_high + (3 << 30), old_max - saved)
330
+ new_max = max(0, old_max + delta)
301
331
  limits["MemoryMax"] = f"{(new_max + (1 << 20) - 1) >> 20}M"
302
332
 
303
333
 
@@ -392,10 +422,22 @@ def price(
392
422
  posture: AgentPosture,
393
423
  *,
394
424
  require_live: bool = False,
425
+ allow_shortfall: bool = False,
395
426
  ) -> Plan:
396
- """Price one ``strata-poly`` library model on discrete NVIDIA or Apple Silicon unified pool."""
427
+ """Price one ``strata-poly`` library model on discrete NVIDIA or Apple Silicon unified pool.
428
+
429
+ ``allow_shortfall`` builds the plan a download needs on a computer whose memory or VRAM is
430
+ too small to load it now (``library download`` for a model the user will load after freeing
431
+ memory): platform, engine and geometry are still checked, capacity is not."""
397
432
  if pool == "unified" and metal.supported(facts):
398
- return _price_unified(facts, recipe_id, base_dir, port, posture, require_live=require_live)
433
+ return _price_unified(
434
+ facts,
435
+ recipe_id,
436
+ base_dir,
437
+ port,
438
+ posture,
439
+ require_live=require_live and not allow_shortfall,
440
+ )
399
441
  if facts["platform"] not in ("linux", "win32"):
400
442
  raise plan_envelope.PlanError(
401
443
  "PolyStrata recipes run on Apple Silicon Metal and Linux/Windows NVIDIA GPUs only"
@@ -405,16 +447,18 @@ def price(
405
447
  if not stack_suite.built_for(recipe, facts["platform"]):
406
448
  raise plan_envelope.PlanError(f"{recipe_id} has no engine build for {facts['platform']}")
407
449
  # Reject immutable hardware capacity shortfalls before checking the CUDA driver so an
408
- # outdated driver never promises that a 24 GB recipe will unlock on an 8 GB card.
409
- need_vram = int(recipe.get("vram_bytes") or 0)
410
- if need_vram > gpu["total_bytes"]:
450
+ # outdated driver never promises that a 24 GB recipe will unlock on an 8 GB card. The floor
451
+ # is the hybrid-offload one when the recipe declares it: its full expert cache (vram_bytes)
452
+ # is the high-speed tier, not the least it starts in.
453
+ need_vram = suite.poly_min_vram_bytes(recipe)
454
+ if not allow_shortfall and need_vram > gpu["total_bytes"]:
411
455
  msg = f"{recipe_id} needs {need_vram} bytes of VRAM, exceeding {gpu['total_bytes']} bytes"
412
456
  raise deploy.AgentMemoryError(
413
457
  msg, PhysicsRefusal(need_vram, gpu["total_bytes"], msg), "GPU memory"
414
458
  )
415
459
  min_total_ram = int(recipe.get("min_ram_total_bytes") or 0)
416
460
  total_ram = facts["ram"]["total_bytes"]
417
- if min_total_ram > total_ram:
461
+ if not allow_shortfall and min_total_ram > total_ram:
418
462
  msg = (
419
463
  f"{recipe_id} recommends at least {min_total_ram} bytes of system memory, "
420
464
  f"this host has {total_ram} bytes"
@@ -438,17 +482,12 @@ def price(
438
482
  plan = suite.unbounded(plan)
439
483
  _calibrate_host_ram(plan, recipe, gpu)
440
484
  min_free = int(recipe.get("min_vram_free_bytes") or need_vram)
441
- if require_live and min_free > gpu["free_bytes"]:
485
+ if not allow_shortfall and min_free > gpu["free_bytes"]:
442
486
  msg = (
443
487
  f"{recipe_id} needs at least {min_free} bytes of free VRAM now, "
444
488
  f"only {gpu['free_bytes']} bytes free"
445
- )
446
- raise deploy.AgentMemoryError(
447
- msg, PhysicsRefusal(min_free, gpu["free_bytes"], msg), "GPU memory"
448
- )
449
- if not require_live and min_free > gpu["free_bytes"]:
450
- msg = (
451
- f"{recipe_id} needs at least {min_free} bytes of loadable VRAM, "
489
+ if require_live
490
+ else f"{recipe_id} needs at least {min_free} bytes of loadable VRAM, "
452
491
  f"only {gpu['free_bytes']} bytes available"
453
492
  )
454
493
  raise deploy.AgentMemoryError(
@@ -456,7 +495,7 @@ def price(
456
495
  )
457
496
  needed_ram = suite.bounded_ram(plan) + budget.HARNESS_RAM + budget.RAM_FLOOR
458
497
  _, avail_ram = budget.host_ram(facts)
459
- if needed_ram > avail_ram:
498
+ if not allow_shortfall and needed_ram > avail_ram:
460
499
  msg = (
461
500
  f"{recipe_id} needs {needed_ram} bytes of system memory, "
462
501
  f"exceeding {avail_ram} bytes available"
@@ -199,8 +199,13 @@ def price(
199
199
  port: int = deploy.DEFAULT_PORT,
200
200
  *,
201
201
  require_live: bool = False,
202
+ allow_shortfall: bool = False,
202
203
  ) -> Plan:
203
- """The deployment plan on ``pool``; AgentMemoryError when it does not fit there."""
204
+ """The deployment plan on ``pool``; AgentMemoryError when it does not fit there.
205
+
206
+ ``allow_shortfall`` builds the plan a download needs when this computer cannot load the
207
+ model now (see ``download_plan``): platform and engine checks stay, capacity is not priced.
208
+ """
204
209
  placement = memory_pools.pools(facts).get(pool)
205
210
  if placement is None:
206
211
  raise plan_envelope.PlanError(f"this computer has no pool {pool}")
@@ -208,7 +213,14 @@ def price(
208
213
  raise plan_envelope.PlanError(f"this version no longer ships {model.id}")
209
214
  if model.entry.runtime == "strata-poly":
210
215
  return library_poly.price(
211
- facts, model.entry.id, pool, base_dir, port, posture(), require_live=require_live
216
+ facts,
217
+ model.entry.id,
218
+ pool,
219
+ base_dir,
220
+ port,
221
+ posture(),
222
+ require_live=require_live,
223
+ allow_shortfall=allow_shortfall,
212
224
  )
213
225
  if require_live and pool == "unified" and metal.supported(facts):
214
226
  if problem := metal.problem(facts):
@@ -239,7 +251,8 @@ def price(
239
251
  entries=effective_catalog,
240
252
  resolver=deploy.catalog_pins,
241
253
  )
242
- validate_plan_bounds(facts, model, pool, plan, effective_catalog)
254
+ if not allow_shortfall:
255
+ validate_plan_bounds(facts, model, pool, plan, effective_catalog)
243
256
  return plan
244
257
 
245
258
 
@@ -259,6 +272,29 @@ class Priced:
259
272
  blocker: Reason | None = None # driver/runtime incompatibility when no pool priced
260
273
  reclaimable_desktop_vram: bool = False # fits discrete GPU once desktop apps near 1 GiB idle
261
274
  reclaim_bytes: int = 0 # approximate VRAM to free when reclaimable_desktop_vram is True
275
+ download_pool: str = "" # fit "none": the pool a later load would run in
276
+
277
+ @property
278
+ def memory_shortfall(self) -> Reason | None:
279
+ """The structured capacity shortfall, when only memory stands between here and a load.
280
+
281
+ ``library status`` publishes it as ``availability.reason`` on a downloadable row whose
282
+ ``fit`` is ``none``, so a client offers a download now and names the exact VRAM/RAM gap.
283
+ """
284
+ if self.fit != "none" or self.plan is not None:
285
+ return None
286
+ reason: Reason = {
287
+ "code": "MEMORY_INSUFFICIENT",
288
+ "need_bytes": self.need_bytes,
289
+ "have_bytes": self.have_bytes,
290
+ }
291
+ if self.memory_kind in ("vram", "ram", "unified"):
292
+ reason["memory_kind"] = self.memory_kind # type: ignore[typeddict-item]
293
+ if self.reclaimable_desktop_vram:
294
+ reason["reclaimable_desktop_vram"] = True
295
+ if self.reclaim_bytes > 0:
296
+ reason["reclaim_bytes"] = self.reclaim_bytes
297
+ return reason
262
298
 
263
299
 
264
300
  def _min_pool_need(model: Model, pool: str, exc: deploy.AgentMemoryError, facts: HostFacts) -> int:
@@ -350,7 +386,7 @@ def judge(
350
386
  )
351
387
  order = sorted(memory_pools.pools(facts), key=lambda p: -memory_pools.pool_free(now, p))
352
388
  fallback: Priced | None = None
353
- shortfall: tuple[int, int, str] | None = None
389
+ shortfall: tuple[int, int, str, str] | None = None
354
390
  blocker: Reason | None = None
355
391
  for pool in order:
356
392
  if pool == "system":
@@ -363,7 +399,7 @@ def judge(
363
399
  if exc.memory == "system memory"
364
400
  else ("unified" if pool == "unified" else "vram")
365
401
  )
366
- gap = (exc.needed_bytes, exc.available_bytes, kind)
402
+ gap = (exc.needed_bytes, exc.available_bytes, kind, pool)
367
403
  if shortfall is None or gap[0] - gap[1] < shortfall[0] - shortfall[1]:
368
404
  shortfall = gap
369
405
  continue
@@ -390,7 +426,7 @@ def judge(
390
426
  )
391
427
  if fallback is not None:
392
428
  return fallback
393
- need, have, memory_kind = shortfall or (0, 0, "")
429
+ need, have, memory_kind, pool = shortfall or (0, 0, "", "")
394
430
  reclaim = (
395
431
  blocker is None
396
432
  and memory_kind == "vram"
@@ -410,6 +446,7 @@ def judge(
410
446
  blocker=blocker,
411
447
  reclaimable_desktop_vram=reclaim,
412
448
  reclaim_bytes=max(1, need - have) if reclaim else 0,
449
+ download_pool=pool,
413
450
  )
414
451
 
415
452
 
@@ -461,7 +498,16 @@ def _gpu_unsupported_reason(facts: HostFacts) -> Reason | None:
461
498
  return {"code": "GPU_UNSUPPORTED", "gpu_vendor": vendor}
462
499
 
463
500
 
464
- def download_reason(facts: HostFacts, priced: Priced, disk_free: int) -> Reason | None:
501
+ def download_reason(
502
+ facts: HostFacts, priced: Priced, disk_free: int, download_bytes: int = 0
503
+ ) -> Reason | None:
504
+ """Why this computer cannot fetch ``model`` at all; None when it can.
505
+
506
+ Only hard blockers refuse a download: platform, GPU vendor, engine/driver or runtime
507
+ incompatibility, and disk space. Memory and VRAM capacity is not one of them: the weights
508
+ can be fetched now and loaded after the user frees memory, so those rows stay downloadable
509
+ and report the shortfall as ``availability.reason`` instead.
510
+ """
465
511
  if platform_problem(facts):
466
512
  return {"code": "PLATFORM_UNSUPPORTED"}
467
513
  if priced.plan is None:
@@ -469,23 +515,79 @@ def download_reason(facts: HostFacts, priced: Priced, disk_free: int) -> Reason
469
515
  return priced.blocker
470
516
  if gpu_reason := _gpu_unsupported_reason(facts):
471
517
  return gpu_reason
472
- reason: Reason = {
473
- "code": "MEMORY_INSUFFICIENT",
474
- "need_bytes": priced.need_bytes,
475
- "have_bytes": priced.have_bytes,
476
- }
477
- if priced.memory_kind in ("vram", "ram", "unified"):
478
- reason["memory_kind"] = priced.memory_kind # type: ignore[typeddict-item]
479
- if priced.reclaimable_desktop_vram:
480
- reason["reclaimable_desktop_vram"] = True
481
- if priced.reclaim_bytes > 0:
482
- reason["reclaim_bytes"] = priced.reclaim_bytes
483
- return reason
518
+ if download_bytes > disk_free:
519
+ return {
520
+ "code": "DISK_INSUFFICIENT",
521
+ "need_bytes": download_bytes,
522
+ "have_bytes": disk_free,
523
+ }
524
+ return None
484
525
  if (need := missing_bytes(priced.plan)) > disk_free:
485
526
  return {"code": "DISK_INSUFFICIENT", "need_bytes": need, "have_bytes": disk_free}
486
527
  return None
487
528
 
488
529
 
530
+ def download_plan(
531
+ facts: HostFacts,
532
+ model: Model,
533
+ pool: str,
534
+ base_dir: str,
535
+ catalog: tuple[cat.CatalogEntry, ...],
536
+ need_bytes: int = 0,
537
+ ) -> Plan:
538
+ """The plan ``library download`` fetches for a model that cannot load here now.
539
+
540
+ Files, engine pin and endpoint are the real ones; only capacity admission is skipped, so a
541
+ user can fetch the weights today and ``library load`` prices live memory again later. A
542
+ ``pool`` that cannot be named at all still raises ``PlanError``.
543
+ """
544
+ if not pool:
545
+ raise plan_envelope.PlanError(f"{model.id} has no pool to run in on this computer")
546
+ if model.entry.runtime == "strata-poly":
547
+ return library_poly.price(
548
+ facts,
549
+ model.entry.id,
550
+ pool,
551
+ base_dir,
552
+ deploy.DEFAULT_PORT,
553
+ posture(),
554
+ allow_shortfall=True,
555
+ )
556
+ try:
557
+ return price(facts, model, pool, base_dir, catalog, allow_shortfall=True)
558
+ except deploy.AgentMemoryError:
559
+ # The planner refuses to build a deployment it cannot fit; the inflation only buys the
560
+ # same files and engine pin, and the record is re-priced when the model is loaded.
561
+ # The agent budget is free memory less the safety reserve; grow the card past both so
562
+ # the same files and engine pin can be planned.
563
+ room = max(need_bytes, memory_pools.pool_total(facts, pool))
564
+ return price(
565
+ _spacious(facts, pool, room + AGENT_VRAM_RESERVE_BYTES + (1 << 30)),
566
+ model,
567
+ pool,
568
+ base_dir,
569
+ catalog,
570
+ allow_shortfall=True,
571
+ )
572
+
573
+
574
+ def _spacious(facts: HostFacts, pool: str, need: int) -> HostFacts:
575
+ """``facts`` with ``pool`` grown to ``need`` bytes, so a download plan can be built."""
576
+ seen = copy.deepcopy(facts)
577
+ index = memory_pools.gpu_index(pool)
578
+ if index is not None:
579
+ for gpu in seen.get("gpus") or []:
580
+ if gpu["index"] == index:
581
+ gpu["total_bytes"] = max(gpu["total_bytes"], need)
582
+ gpu["free_bytes"] = max(gpu["free_bytes"], need)
583
+ gpu["used_bytes"] = max(0, gpu["total_bytes"] - gpu["free_bytes"])
584
+ return seen
585
+ ram = seen["ram"]
586
+ ram["total_bytes"] = max(ram["total_bytes"], need)
587
+ ram["available_bytes"] = max(ram["available_bytes"], need)
588
+ return seen
589
+
590
+
489
591
  def _smartest_library_fallback(facts: HostFacts, base_dir: str) -> tuple[str, str] | None:
490
592
  """Best live-fitting llama.cpp library model ranked by ``llm_rank.choose()``."""
491
593
  catalog = entries()
@@ -591,7 +693,10 @@ def floor_metadata(
591
693
  return shortfall_bytes, 0, False, sum(f.size_bytes for f in model.variant.files)
592
694
  if model.entry.runtime == "strata-poly":
593
695
  recipe = suite.recipe(model.entry.id)
594
- window = int(recipe.get("context") or model.entry.n_ctx_train)
696
+ # Apple Silicon prices its own window: a recipe whose CUDA tier starts at a short
697
+ # offload window declares the Metal one separately (``metal_context``).
698
+ metal_window = recipe.get("metal_context") if metal.supported(facts) else None
699
+ window = int(metal_window or recipe.get("context") or model.entry.n_ctx_train)
595
700
  metal_unified = metal.supported(facts)
596
701
  active = model.entry.agent_posture(
597
702
  context_policy.posture_for(posture(), "metal" if metal_unified else "cuda")
@@ -366,15 +366,51 @@ def _remove_service(plan: Plan, run: Executor, *, keep_key: bool = True) -> None
366
366
  hosts.delete_record(hosts.LOCAL_ID, plan["name"], deploy_dir=plan["service"]["deploy_dir"])
367
367
 
368
368
 
369
+ def _forget_deploy_dir(deploy_dir: str, name: str) -> None:
370
+ """Delete one deployment directory (its log/key) and purge its manifest entry."""
371
+ path = Path(os.path.expanduser(deploy_dir))
372
+ if path.parent.name == "deployments" and path.is_dir():
373
+ shutil.rmtree(path, ignore_errors=True)
374
+ hosts.delete_record(hosts.LOCAL_ID, name, purged=True, deploy_dir=deploy_dir)
375
+
376
+
369
377
  def _forget_deployment(plan: Plan) -> None:
370
378
  """The removed server's directory (its log) and its manifest entry: nothing of the model is
371
379
  left for a later purge to find."""
372
- deploy_dir = Path(os.path.expanduser(plan["service"]["deploy_dir"]))
373
- if deploy_dir.parent.name == "deployments" and deploy_dir.is_dir():
374
- shutil.rmtree(deploy_dir, ignore_errors=True)
375
- hosts.delete_record(
376
- hosts.LOCAL_ID, plan["name"], purged=True, deploy_dir=plan["service"]["deploy_dir"]
377
- )
380
+ _forget_deploy_dir(plan["service"]["deploy_dir"], plan["name"])
381
+
382
+
383
+ def _prior_key_dirs(record: Record) -> list[Path]:
384
+ """Candidate deployment directories that may hold a preserved api-key or .pinned-api-key."""
385
+ raw: list[str] = []
386
+ active_dir = record["plan"]["service"]["deploy_dir"]
387
+ last_dir = record.get("last_deploy_dir")
388
+ if record["state"] == "idle":
389
+ if last_dir:
390
+ raw.append(last_dir)
391
+ raw.append(active_dir)
392
+ else:
393
+ raw.append(active_dir)
394
+ if last_dir:
395
+ raw.append(last_dir)
396
+ if (baseline := record.get("baseline_plan")) is not None:
397
+ raw.append(baseline["service"]["deploy_dir"])
398
+ dirs: list[Path] = []
399
+ seen: set[Path] = set()
400
+ for item in raw:
401
+ path = Path(os.path.expanduser(item))
402
+ resolved = path.resolve()
403
+ if resolved not in seen:
404
+ seen.add(resolved)
405
+ dirs.append(path)
406
+ return dirs
407
+
408
+
409
+ def _saved_prior_key(dirs: list[Path]) -> str | None:
410
+ for path in dirs:
411
+ if key := deploy.saved_api_key_in(path):
412
+ return key
413
+ return None
378
414
 
379
415
 
380
416
  def _clear_load_timing(record: Record) -> None:
@@ -510,11 +546,16 @@ def stop(record: Record, run: Executor, *, keep_key: bool = True) -> None:
510
546
  library_state.save(record)
511
547
  record.pop("load_posture", None)
512
548
  _clear_load_timing(record)
549
+ stopped_deploy_dir = record["plan"]["service"]["deploy_dir"]
513
550
  if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
514
551
  if keep_key:
515
552
  _remove_service(record["plan"], run)
516
553
  else:
517
554
  _remove_service(record["plan"], run, keep_key=False)
555
+ if not keep_key:
556
+ record.pop("last_deploy_dir", None)
557
+ elif deploy.saved_api_key_in(stopped_deploy_dir) is not None:
558
+ record["last_deploy_dir"] = stopped_deploy_dir
518
559
  record["state"] = "idle"
519
560
  for key in ("registration", "error", "note"):
520
561
  record.pop(key, None) # type: ignore[misc]
@@ -668,6 +709,7 @@ def _serve(
668
709
  raise
669
710
  record["state"] = "loaded"
670
711
  record["ever_loaded"] = True
712
+ record["last_deploy_dir"] = record["plan"]["service"]["deploy_dir"]
671
713
  record.pop("error", None)
672
714
  record.pop("note", None)
673
715
  library_state.save(record)
@@ -1011,10 +1053,8 @@ def load(
1011
1053
  with library_state.held(claims):
1012
1054
  handle = library_state.JobHandle(claims[0])
1013
1055
  handle.update("load", 0, len(LOAD_STEPS), load_step="prepare")
1014
- prior_deploy_dir = Path(os.path.expanduser(record["plan"]["service"]["deploy_dir"]))
1015
- prior_key = deploy.saved_api_key(record["plan"])
1016
- if prior_key is None and (baseline := record.get("baseline_plan")) is not None:
1017
- prior_key = deploy.saved_api_key(baseline)
1056
+ prior_dirs = _prior_key_dirs(record)
1057
+ prior_key = _saved_prior_key(prior_dirs)
1018
1058
  for target in targets:
1019
1059
  stop(target, executor)
1020
1060
  if record["state"] != "idle": # a server that stopped answering, or a failed load
@@ -1030,10 +1070,13 @@ def load(
1030
1070
  handle,
1031
1071
  replace(load_ctx, fallback_api_key=prior_key),
1032
1072
  )
1033
- active_deploy_dir = Path(os.path.expanduser(record["plan"]["service"]["deploy_dir"]))
1034
- if prior_deploy_dir.resolve() != active_deploy_dir.resolve():
1035
- with contextlib.suppress(OSError):
1036
- (prior_deploy_dir / "api-key").unlink(missing_ok=True)
1073
+ active_deploy_dir = Path(
1074
+ os.path.expanduser(record["plan"]["service"]["deploy_dir"])
1075
+ ).resolve()
1076
+ for prior_dir in prior_dirs:
1077
+ if prior_dir.resolve() != active_deploy_dir:
1078
+ with contextlib.suppress(OSError):
1079
+ (prior_dir / "api-key").unlink(missing_ok=True)
1037
1080
  return _row(model, base_dir)
1038
1081
 
1039
1082
 
@@ -1063,6 +1106,7 @@ def remove(model_id: str, base_dir: str) -> Row:
1063
1106
  record, job = _claim(model, "remove")
1064
1107
  with library_state.held([job]):
1065
1108
  active_plan = record["plan"]
1109
+ last_deploy_dir = record.get("last_deploy_dir")
1066
1110
  if record["state"] != "idle":
1067
1111
  stop(record, library_jobs.executor(), keep_key=False)
1068
1112
  with library_state.locked():
@@ -1070,8 +1114,18 @@ def remove(model_id: str, base_dir: str) -> Row:
1070
1114
  library_jobs.delete_weights(weight_dests, library_jobs.in_use(model.id))
1071
1115
  library_jobs.prune_empty_custom_dirs(weight_dests, library_state.base_of(record))
1072
1116
  _forget_deployment(record["plan"])
1117
+ forgotten = {
1118
+ Path(os.path.expanduser(record["plan"]["service"]["deploy_dir"])).resolve()
1119
+ }
1073
1120
  if active_plan["name"] != record["plan"]["name"]:
1074
1121
  _forget_deployment(active_plan)
1122
+ forgotten.add(
1123
+ Path(os.path.expanduser(active_plan["service"]["deploy_dir"])).resolve()
1124
+ )
1125
+ if last_deploy_dir:
1126
+ last_path = Path(os.path.expanduser(last_deploy_dir))
1127
+ if last_path.resolve() not in forgotten:
1128
+ _forget_deploy_dir(last_deploy_dir, last_path.name)
1075
1129
  library_state.forget(model.id)
1076
1130
  runtime_index.refresh()
1077
1131
  return _row(model, base_dir)
@@ -142,6 +142,9 @@ class Record(_RecordRequired, total=False):
142
142
  pi_model: str # what pi offers once it is loaded; fixed when the record is made
143
143
  load_posture: LoadPosture # elastic posture & warning metadata recorded on load
144
144
  baseline_plan: Plan # pristine capacity plan preserved while a degraded/active load runs
145
+ last_deploy_dir: (
146
+ str # last deployment directory whose api-key / .pinned-api-key may outlive unload
147
+ )
145
148
  custom: CustomMeta # custom hub model metadata (absent for curated models)
146
149
  verification: VerificationRecord # smoke-test verification state (custom models)
147
150
  catalog_entry: dict[str, object] # schema-3 entry snapshot for custom models
@@ -485,6 +485,9 @@ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None
485
485
  elif engine == "polystrata":
486
486
  recipe = next((r for r in suite.recipes("llm") if r["id"] == model.entry.id), None)
487
487
  concurrency = suite.effective_parallel(recipe, ()) if recipe is not None else 1
488
+ if recipe is not None and lib.facts["platform"] == "darwin":
489
+ # Apple Silicon runs its own slot count where the CUDA tier is the offload one.
490
+ concurrency = int(str(recipe.get("metal_parallel") or concurrency))
488
491
  else:
489
492
  concurrency = 1 if engine == "strata" else library_pricing.posture().slots
490
493
  found["concurrency"] = concurrency
@@ -934,10 +937,17 @@ def row(lib: Library, model: Model, *, now_utc: dt.datetime | None = None) -> Ro
934
937
  availability: Availability = {"downloadable": True}
935
938
  if record is None:
936
939
  reason = library_pricing.download_reason(
937
- lib.facts, priced, library_pricing.base_free(lib.base_dir)
940
+ lib.facts, priced, library_pricing.base_free(lib.base_dir), fallback_download
938
941
  )
939
942
  if reason is not None:
940
943
  availability = {"downloadable": False, "reason": reason}
944
+ if availability["downloadable"]:
945
+ # Downloadable (or downloaded) but not loadable until memory is freed: the row keeps fit
946
+ # "none" and carries the structured shortfall in ``availability.reason``, where a blocked
947
+ # download carries its refusal, so a client offers "Download only" and shows the exact
948
+ # VRAM/RAM gap.
949
+ if (shortfall := priced.memory_shortfall) is not None:
950
+ availability["reason"] = shortfall
941
951
  launch: dict[str, object] = dict(plan["launch"]) if plan is not None else {}
942
952
  found: Row = {
943
953
  "id": model.id,
@@ -3,7 +3,8 @@
3
3
  One process resolves the region once, lazily, the first time something is about to be downloaded:
4
4
 
5
5
  1. ``SIMPLEX_REGION`` (or the CLI's ``--region``, which sets it) when it is ``cn`` or ``global``;
6
- ``auto`` or unset means not forced. Linger passes the region it resolved this way.
6
+ ``auto`` or unset means not forced. Overrides only this process in memory without modifying
7
+ ``region.json`` on disk (reusing cached ``ecosystems`` when disk already matches).
7
8
  2. ``SIMPLEX_REGION_FILE`` (when set by Linger to share ``<home>/runtime/region.json``) or
8
9
  ``$LOCALMODELS_STATE/region.json`` when it is younger than ``STALE_AFTER`` (6 hours; 1 hour
9
10
  when ``method`` is ``fallback``) and its ``network_fingerprint`` matches the current proxy
@@ -343,13 +344,7 @@ def current_region(env: Mapping[str, str] | None = None) -> str:
343
344
  for name in [k for k, rec in _ecosystems.items() if rec["region"] != explicit]:
344
345
  _ecosystems.pop(name, None)
345
346
  found = saved(env=active_env)
346
- raw_pair = _read_doc(active_env)
347
- raw_doc = raw_pair[0] if raw_pair is not None else None
348
- is_user_pref = raw_doc is not None and raw_doc.get("method") == "user"
349
- same_region_on_disk = raw_doc is not None and raw_doc.get("region") == explicit
350
- if not is_user_pref and not same_region_on_disk:
351
- save(explicit, "env", env=active_env)
352
- elif found is not None and found["region"] == explicit:
347
+ if found is not None and found["region"] == explicit:
353
348
  _ecosystems.update(_parse_ecosystems(found.get("ecosystems")))
354
349
  _resolved = explicit
355
350
  return explicit
@@ -441,7 +436,8 @@ def ecosystem_record(
441
436
  with _LOCK:
442
437
  _ecosystems[ecosystem] = measured
443
438
  reg = _resolved or explicit or measured["region"]
444
- save(reg, "probe", ecosystems=dict(_ecosystems), env=active_env)
439
+ if explicit is None:
440
+ save(reg, "probe", ecosystems=dict(_ecosystems), env=active_env)
445
441
  return measured
446
442
 
447
443