@simplexai/localmodels-linux-arm64 0.1.0-dev.110 → 0.1.0-dev.111

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 (46) hide show
  1. package/README.md +1 -1
  2. package/bootstrap.identity +1 -1
  3. package/bootstrap.sha256 +44 -44
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/catalog.json +430 -75
  6. package/modules/localmodels/custom_hub.py +66 -2
  7. package/modules/localmodels/custom_hub_http.py +18 -0
  8. package/modules/localmodels/deploy.py +65 -5
  9. package/modules/localmodels/download-mirrors.json +70 -0
  10. package/modules/localmodels/engine_adapters/strata_poly.py +20 -4
  11. package/modules/localmodels/engine_adapters/suite_plan.py +3 -0
  12. package/modules/localmodels/engines-strata-poly-0.2.20-poly.10.json +132 -0
  13. package/modules/localmodels/http_local.py +46 -0
  14. package/modules/localmodels/library_custom.py +73 -0
  15. package/modules/localmodels/library_jobs.py +0 -12
  16. package/modules/localmodels/library_poly.py +11 -5
  17. package/modules/localmodels/library_presentation.py +28 -0
  18. package/modules/localmodels/library_serve.py +30 -21
  19. package/modules/localmodels/library_smoke.py +1 -1
  20. package/modules/localmodels/library_state.py +20 -1
  21. package/modules/localmodels/library_status.py +46 -55
  22. package/modules/localmodels/mirrors.py +217 -21
  23. package/modules/localmodels/npm_transport.py +46 -35
  24. package/modules/localmodels/plan_envelope.py +8 -1
  25. package/modules/localmodels/region.py +91 -20
  26. package/modules/localmodels/remote_ops_common.py +1 -0
  27. package/modules/localmodels/remote_ops_download.py +574 -126
  28. package/modules/localmodels/remote_ops_prepare.py +8 -2
  29. package/modules/localmodels/remote_ops_ranges.py +80 -44
  30. package/modules/localmodels/remote_ops_redirect.py +3 -1
  31. package/modules/localmodels/remote_ops_remove.py +4 -2
  32. package/modules/localmodels/runtime_index.py +3 -1
  33. package/modules/localmodels/stack.py +1 -6
  34. package/modules/localmodels/stack_suite.py +1 -1
  35. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.9.txt → strata-poly-serve-0.2.20-poly.10.txt} +1 -1
  36. package/modules/localmodels/suite.py +80 -3
  37. package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/METADATA +1 -1
  38. package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/RECORD +40 -40
  39. package/package.json +1 -1
  40. package/tool.json +1 -1
  41. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +0 -132
  42. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/WHEEL +0 -0
  43. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/entry_points.txt +0 -0
  44. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/licenses/LICENSE +0 -0
  45. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/licenses/NOTICE +0 -0
  46. /package/modules/{simplex_localmodels-0.1.0.dev110.dist-info → simplex_localmodels-0.1.0.dev111.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -30,6 +30,7 @@ from localmodels import (
30
30
  library_state,
31
31
  library_status,
32
32
  plan_envelope,
33
+ region,
33
34
  remote_ops,
34
35
  remote_ops_download,
35
36
  runtime_index,
@@ -358,6 +359,9 @@ def _build_download_plan(
358
359
  engine_doc: dict[str, object],
359
360
  est_memory: int,
360
361
  n_ctx_train: int,
362
+ attach_mirrors: bool = True,
363
+ has_token: bool = False,
364
+ existing_mirrors: Mapping[str, Sequence[remote_ops.Source]] | None = None,
361
365
  ) -> Plan:
362
366
  base = base_dir.rstrip("/")
363
367
  models_dir = f"{base}/models"
@@ -375,6 +379,13 @@ def _build_download_plan(
375
379
  }
376
380
  for f in all_files
377
381
  ]
382
+ if attach_mirrors:
383
+ _attach_modelscope_mirrors(planned_files, fetched, has_token=has_token)
384
+ elif existing_mirrors:
385
+ for item in planned_files:
386
+ prior = existing_mirrors.get(item["path"])
387
+ if prior:
388
+ item["mirrors"] = list(prior)
378
389
  stem = re.sub(r"\.gguf$", "", Path(weight_files[0].path).name, flags=re.IGNORECASE)
379
390
  model_alias = gguf.model_id_from_stem(stem)
380
391
  where = plan_envelope.deployment(
@@ -454,6 +465,62 @@ def _build_download_plan(
454
465
  )
455
466
 
456
467
 
468
+ def _offline_download() -> bool:
469
+ return os.environ.get("SIMPLEX_OFFLINE", "").strip().lower() in {"1", "true", "yes"}
470
+
471
+
472
+ def _download_region() -> str:
473
+ """Region used when a custom download plan looks for a ModelScope copy.
474
+
475
+ ``fetch_repo(hub="auto")`` stays on ``readonly_region`` so search and inspect never probe
476
+ and never write ``region.json``. A download plan matches catalog downloads by calling
477
+ ``current_region()`` (explicit env, a fresh cache, or a probe).
478
+ """
479
+ return region.current_region()
480
+
481
+
482
+ def _explicit_hf_endpoint(fetched: custom_hub.FetchedRepo) -> bool:
483
+ if os.environ.get("HF_ENDPOINT", "").strip():
484
+ return True
485
+ ep = (fetched.endpoint or "").rstrip("/")
486
+ return bool(ep) and ep not in (region.HF_API, region.HF_MIRROR)
487
+
488
+
489
+ def _attach_modelscope_mirrors(
490
+ planned_files: list[ReusableFile],
491
+ fetched: custom_hub.FetchedRepo,
492
+ *,
493
+ has_token: bool = False,
494
+ ) -> None:
495
+ """In cn, mount a same-sha256 ModelScope copy of a public Hugging Face custom file.
496
+
497
+ The download still accepts bytes only when their SHA-256 matches. Offline mode, an explicit
498
+ HF endpoint, gated or token-authenticated repos (preventing private repo leakage to public
499
+ modelscope.cn and public probes under corporate HF_ENDPOINT), a non-cn region, and any
500
+ listing failure leave the plan unchanged.
501
+ """
502
+ if (
503
+ fetched.hub != "huggingface"
504
+ or _offline_download()
505
+ or _explicit_hf_endpoint(fetched)
506
+ or fetched.gated
507
+ or has_token
508
+ or bool(custom_hub.resolve_token("huggingface", None, hub_explicit=True))
509
+ ):
510
+ return
511
+ if _download_region() != "cn":
512
+ return
513
+ mirrors = custom_hub.modelscope_mirror_urls(fetched.repo_id, planned_files, timeout=2.0)
514
+ for item in planned_files:
515
+ url = mirrors.get(item["path"])
516
+ if not url or url == item.get("url"):
517
+ continue
518
+ existing = list(item.get("mirrors") or [])
519
+ if any(entry.get("url") == url for entry in existing):
520
+ continue
521
+ item["mirrors"] = [*existing, {"source": "modelscope", "url": url}]
522
+
523
+
457
524
  def _auth_headers_for_plan(
458
525
  plan: Plan, token: str | None, *, hub: CustomHub
459
526
  ) -> dict[str, str] | None:
@@ -650,6 +717,7 @@ def download_custom(payload: Mapping[str, object], base_dir: str) -> Row:
650
717
  engine_doc=engine_doc,
651
718
  est_memory=est_memory,
652
719
  n_ctx_train=remote_header.n_ctx_train if remote_header is not None else 32768,
720
+ has_token=bool(resolved_token),
653
721
  )
654
722
  _check_disk_and_memory(
655
723
  custom_model_id,
@@ -835,6 +903,9 @@ def _commit_custom_record(
835
903
  sha_overrides=sha_overrides,
836
904
  header=local_header,
837
905
  )
906
+ prior_mirrors: dict[str, list[remote_ops.Source]] = {
907
+ f["path"]: list(f["mirrors"]) for f in plan["files"] if f.get("mirrors")
908
+ }
838
909
  final_plan = _build_download_plan(
839
910
  facts=facts,
840
911
  base_dir=base_dir,
@@ -850,6 +921,8 @@ def _commit_custom_record(
850
921
  engine_doc=engine_doc,
851
922
  est_memory=est_memory,
852
923
  n_ctx_train=local_header.n_ctx_train if local_header is not None else 32768,
924
+ attach_mirrors=False,
925
+ existing_mirrors=prior_mirrors,
853
926
  )
854
927
  selector = library_direct.pi_model(custom_model_id, str(final_plan["endpoint"]["model"]))
855
928
  record: Record = library_state.new_record(
@@ -22,7 +22,6 @@ from localmodels import (
22
22
  app,
23
23
  deploy_steps,
24
24
  deployment_lifecycle,
25
- draft_spec,
26
25
  frontend,
27
26
  hosts,
28
27
  library_direct,
@@ -764,14 +763,3 @@ def cancel(model_id: str, base_dir: str) -> Row:
764
763
  prune_empty_custom_dirs(gone, job.get("base_dir") or base_dir)
765
764
  library_state.clear_job(model.id)
766
765
  return library_status.row(library_status.Library.read(probe(), base_dir), model)
767
-
768
-
769
- def files_missing(plan: Plan) -> list[str]:
770
- """The files ``plan`` cannot start without that are not verified in place. Its optional
771
- drafter is never one: a load plans without it (``library_elastic.load_posture``)."""
772
- optional = draft_spec.drafter_dest(plan)
773
- return [
774
- Path(f["dest"]).name
775
- for f in plan["files"]
776
- if f["dest"] != optional and not plan_envelope.verified_in_place(f)
777
- ]
@@ -261,14 +261,20 @@ def _ram_experts_bytes(recipe: suite.SuiteRecipe) -> int:
261
261
 
262
262
 
263
263
  def _calibrate_host_ram(plan: Plan, recipe: suite.SuiteRecipe, gpu: GPU) -> None:
264
- """Discount unused ``--ram-experts-mib`` spill when ``gpu`` fits most/all weights in VRAM.
264
+ """Discount unused expert spill when ``gpu`` fits most/all weights in VRAM.
265
265
 
266
266
  Recipes targeting 8-16 GB cards (such as ``inkling-2-mini-q3-poly``) size
267
- ``memory_estimate_bytes`` for heavy 8 GB RAM expert offloading. On a 16 GB card where
268
- nearly all experts stay in VRAM (~1.52 GiB host RAM actual), charging the full 8 GB spill
269
- blocks ``library load`` at ~16.89 GB free RAM.
267
+ ``memory_estimate_bytes`` for heavy 8 GB RAM expert offloading, either through an explicit
268
+ ``--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.
270
276
  """
271
- ram_experts = _ram_experts_bytes(recipe)
277
+ ram_experts = _ram_experts_bytes(recipe) or max(0, int(recipe.get("host_ram_spill_bytes") or 0))
272
278
  recipe_base = int(recipe.get("memory_estimate_bytes") or 0)
273
279
  if ram_experts <= 0 or recipe_base <= ram_experts:
274
280
  return
@@ -55,6 +55,34 @@ _Q4_REFERENCE_PRIORITY: tuple[str, ...] = (
55
55
  )
56
56
 
57
57
 
58
+ HUB_REPO = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*")
59
+
60
+
61
+ def card(model: Model, vision_on: bool) -> Row:
62
+ """The model card fields of a row, each only when the catalog states it: family,
63
+ publisher and parameter scales as written there, the architecture from its MoE flag, its
64
+ license, the Hugging Face page of the repository the weights come from, and vision when
65
+ this deployment reads images (its projector is pinned and priced). Nothing is guessed from
66
+ a name; Linger rejects a whole status document over one value outside its sets."""
67
+ entry = model.entry
68
+ found: dict[str, object] = {
69
+ "family": entry.family,
70
+ "publisher": entry.publisher.strip()[:120],
71
+ "architecture": "moe" if entry.moe else "dense",
72
+ "parameters": entry.parameters,
73
+ "active_parameters": entry.active_parameters if entry.moe else "",
74
+ "license": entry.license.strip()[:120],
75
+ }
76
+ if HUB_REPO.fullmatch(entry.repo):
77
+ found["source_url"] = f"https://huggingface.co/{entry.repo}"
78
+ caps = [c for c in entry.capabilities if c != "vision" or vision_on]
79
+ if vision_on and "vision" not in caps:
80
+ caps = ["vision", *caps]
81
+ if caps:
82
+ found["capabilities"] = caps
83
+ return cast(Row, {k: v for k, v in found.items() if v})
84
+
85
+
58
86
  def _slug(text: str) -> str:
59
87
  cleaned = _SLUG_BAD_RE.sub("-", text.strip().lower()).strip("-._")
60
88
  return cleaned or "model"
@@ -17,7 +17,7 @@ import math
17
17
  import os
18
18
  import shutil
19
19
  import time
20
- from dataclasses import dataclass
20
+ from dataclasses import dataclass, field, replace
21
21
  from pathlib import Path
22
22
 
23
23
  from localmodels import (
@@ -156,6 +156,7 @@ class LoadContext:
156
156
  base: str = ""
157
157
  pool: str = ""
158
158
  port: int = 0
159
+ fallback_api_key: str | None = field(default=None, repr=False)
159
160
 
160
161
 
161
162
  def _deploy_load_step(step: str) -> LoadStep:
@@ -166,14 +167,6 @@ def _deploy_load_step(step: str) -> LoadStep:
166
167
  return "load"
167
168
 
168
169
 
169
- def base_of(record: Record) -> str:
170
- """The base directory the model was downloaded into."""
171
- if record.get("base_dir"):
172
- return record["base_dir"]
173
- deploy_dir = os.path.expanduser(record["plan"]["service"]["deploy_dir"])
174
- return os.path.dirname(os.path.dirname(deploy_dir))
175
-
176
-
177
170
  def _reserved(skip: str) -> dict[str, int]:
178
171
  found: dict[str, int] = {}
179
172
  for model, (job, alive) in library_state.jobs().items():
@@ -301,7 +294,7 @@ def _room(
301
294
  now,
302
295
  model,
303
296
  record["pool"],
304
- base_of(record),
297
+ library_state.base_of(record),
305
298
  library_pricing.entries(),
306
299
  allow_overcommit=True,
307
300
  force=force,
@@ -361,8 +354,11 @@ def _start_code(finished: FinishedRecord, *, custom: bool = False) -> str:
361
354
  return "ENGINE_START_FAILED"
362
355
 
363
356
 
364
- def _remove_service(plan: Plan, run: Executor) -> None:
365
- outcome = run.run_action("remove", stack_lifecycle.plan_params(plan), timeout=600)[0]
357
+ def _remove_service(plan: Plan, run: Executor, *, keep_key: bool = True) -> None:
358
+ params = stack_lifecycle.plan_params(plan)
359
+ if keep_key:
360
+ params["keep_key"] = True
361
+ outcome = run.run_action("remove", params, timeout=600)[0]
366
362
  if outcome.get("event") != "result":
367
363
  raise LibraryError(
368
364
  "ENGINE_START_FAILED", f"stopping {plan['name']}: {outcome.get('message')}"
@@ -500,7 +496,7 @@ def _restore_baseline_plan(record: Record) -> None:
500
496
  record["plan"] = baseline
501
497
 
502
498
 
503
- def stop(record: Record, run: Executor) -> None:
499
+ def stop(record: Record, run: Executor, *, keep_key: bool = True) -> None:
504
500
  """Demote a loaded record, then stop and remove the model's server; its weights stay."""
505
501
  had_registration = record.pop("registration", None) is not None
506
502
  if record["state"] == "loaded":
@@ -515,7 +511,10 @@ def stop(record: Record, run: Executor) -> None:
515
511
  record.pop("load_posture", None)
516
512
  _clear_load_timing(record)
517
513
  if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
518
- _remove_service(record["plan"], run)
514
+ if keep_key:
515
+ _remove_service(record["plan"], run)
516
+ else:
517
+ _remove_service(record["plan"], run, keep_key=False)
519
518
  record["state"] = "idle"
520
519
  for key in ("registration", "error", "note"):
521
520
  record.pop(key, None) # type: ignore[misc]
@@ -620,13 +619,13 @@ def _serve(
620
619
  ) -> Record:
621
620
  load_started = time.monotonic()
622
621
  first_load = not bool(record.get("ever_loaded") or record.get("tokens_per_second") is not None)
623
- base = base_of(record)
622
+ base = library_state.base_of(record)
624
623
  use_jinja, autostart = _custom_flags(record)
625
624
  facts, elastic = _serve_elastic_plan(model, record, facts, base, port, ctx, use_jinja=use_jinja)
626
625
  plan = elastic.plan
627
626
  if not autostart:
628
627
  plan["service"]["autostart"] = False
629
- if missing := library_jobs.files_missing(plan):
628
+ if missing := library_state.files_missing(plan):
630
629
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing), failed=True)
631
630
  steps = [str(step) for step in LOAD_STEPS]
632
631
  record["load_posture"] = _load_posture_record(elastic)
@@ -639,6 +638,7 @@ def _serve(
639
638
  base=base,
640
639
  pool=record["pool"],
641
640
  port=port,
641
+ fallback_api_key=ctx.fallback_api_key,
642
642
  )
643
643
  if record.get("baseline_plan") is None:
644
644
  record["baseline_plan"] = record["plan"]
@@ -735,7 +735,8 @@ def _start(
735
735
  pre_deploy_ms = max(0, round((time.monotonic() - started_at) * 1000))
736
736
  oom_retries = 0
737
737
  while True:
738
- finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
738
+ resolved_key = deploy.resolve_api_key(plan, fallback_key=ctx.fallback_api_key)
739
+ finished = app.run_deploy(hosts.LOCAL_ID, plan, api_key=resolved_key, on_event=seen)
739
740
  if finished["ok"]:
740
741
  break
741
742
  code = _start_code(finished, custom=record.get("custom") is not None)
@@ -893,7 +894,7 @@ def _try_claim_load_locked(
893
894
  record = library_state.load(model.id)
894
895
  if record is None:
895
896
  raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
896
- if missing := library_jobs.files_missing(record["plan"]):
897
+ if missing := library_state.files_missing(record["plan"]):
897
898
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
898
899
  facts = library_jobs.probe()
899
900
  url = str(record["plan"]["endpoint"]["base_url"])
@@ -1010,6 +1011,10 @@ def load(
1010
1011
  with library_state.held(claims):
1011
1012
  handle = library_state.JobHandle(claims[0])
1012
1013
  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)
1013
1018
  for target in targets:
1014
1019
  stop(target, executor)
1015
1020
  if record["state"] != "idle": # a server that stopped answering, or a failed load
@@ -1023,8 +1028,12 @@ def load(
1023
1028
  executor,
1024
1029
  port,
1025
1030
  handle,
1026
- load_ctx,
1031
+ replace(load_ctx, fallback_api_key=prior_key),
1027
1032
  )
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)
1028
1037
  return _row(model, base_dir)
1029
1038
 
1030
1039
 
@@ -1055,11 +1064,11 @@ def remove(model_id: str, base_dir: str) -> Row:
1055
1064
  with library_state.held([job]):
1056
1065
  active_plan = record["plan"]
1057
1066
  if record["state"] != "idle":
1058
- stop(record, library_jobs.executor())
1067
+ stop(record, library_jobs.executor(), keep_key=False)
1059
1068
  with library_state.locked():
1060
1069
  weight_dests = library_jobs.dests(record["plan"])
1061
1070
  library_jobs.delete_weights(weight_dests, library_jobs.in_use(model.id))
1062
- library_jobs.prune_empty_custom_dirs(weight_dests, base_of(record))
1071
+ library_jobs.prune_empty_custom_dirs(weight_dests, library_state.base_of(record))
1063
1072
  _forget_deployment(record["plan"])
1064
1073
  if active_plan["name"] != record["plan"]["name"]:
1065
1074
  _forget_deployment(active_plan)
@@ -291,7 +291,7 @@ def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
291
291
  if record is None:
292
292
  raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
293
293
  _validate_smoke_record(model.id, record)
294
- if missing := library_jobs.files_missing(record["plan"]):
294
+ if missing := library_state.files_missing(record["plan"]):
295
295
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
296
296
  facts = library_jobs.probe()
297
297
  taken = {
@@ -22,7 +22,7 @@ from contextlib import contextmanager
22
22
  from pathlib import Path
23
23
  from typing import Literal, TypedDict
24
24
 
25
- from localmodels import hosts, process_identity
25
+ from localmodels import draft_spec, hosts, plan_envelope, process_identity
26
26
  from localmodels.contracts import decode
27
27
  from localmodels.library_model import LibraryError, LoadBreakdownMs, Note, Problem
28
28
  from localmodels.plan_envelope import utc_now
@@ -234,6 +234,25 @@ def locked(state_dir: Path | None = None) -> Iterator[None]:
234
234
  held.discard(resolved)
235
235
 
236
236
 
237
+ def base_of(record: Record) -> str:
238
+ """The base directory the model was downloaded into."""
239
+ if record.get("base_dir"):
240
+ return record["base_dir"]
241
+ deploy_dir = os.path.expanduser(record["plan"]["service"]["deploy_dir"])
242
+ return os.path.dirname(os.path.dirname(deploy_dir))
243
+
244
+
245
+ def files_missing(plan: Plan) -> list[str]:
246
+ """The files ``plan`` cannot start without that are not verified in place. Its optional
247
+ drafter is never one: a load plans without it (``library_elastic.load_posture``)."""
248
+ optional = draft_spec.drafter_dest(plan)
249
+ return [
250
+ Path(f["dest"]).name
251
+ for f in plan["files"]
252
+ if f["dest"] != optional and not plan_envelope.verified_in_place(f)
253
+ ]
254
+
255
+
237
256
  def load(model: str) -> Record | None:
238
257
  try:
239
258
  value = json.loads(record_path(model).read_text(encoding="utf-8"))
@@ -6,8 +6,6 @@ from __future__ import annotations
6
6
 
7
7
  import datetime as dt
8
8
  import os
9
- import re
10
- import urllib.request
11
9
  from collections.abc import Iterable, Mapping
12
10
  from dataclasses import dataclass, field
13
11
  from typing import Any, cast
@@ -17,6 +15,7 @@ from localmodels import (
17
15
  debug_mode,
18
16
  deployment_lifecycle,
19
17
  hosts,
18
+ http_local,
20
19
  library_direct,
21
20
  library_elastic,
22
21
  library_order,
@@ -82,7 +81,9 @@ ARCH = {
82
81
  "arm64": "arm64",
83
82
  "aarch64": "arm64",
84
83
  }
85
- HEALTH_TIMEOUT_S = 2.0
84
+ HEALTH_TIMEOUT_S = 3.0
85
+ HEALTH_RETRIES = 3
86
+ HEALTH_RETRY_BACKOFF_S = 0.5
86
87
  _PATH: Any = os.path
87
88
  _SIDECAR_SUFFIXES = (".sha256", ".part", ".part.ranges", ".tmp")
88
89
 
@@ -172,12 +173,12 @@ def platform_name(facts: HostFacts) -> str:
172
173
  def answering(base_url: str) -> bool:
173
174
  """llama-server's ``/health`` answers 200 without a key once the model is loaded."""
174
175
  url = base_url.removesuffix("/").removesuffix("/v1") + "/health"
175
- opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
176
- try:
177
- with opener.open(url, timeout=HEALTH_TIMEOUT_S) as response:
178
- return bool(response.status == 200)
179
- except OSError:
180
- return False
176
+ return http_local.probe_health(
177
+ url,
178
+ timeout=HEALTH_TIMEOUT_S,
179
+ retries=HEALTH_RETRIES,
180
+ backoff_s=HEALTH_RETRY_BACKOFF_S,
181
+ )
181
182
 
182
183
 
183
184
  @dataclass
@@ -301,9 +302,11 @@ def _state(lib: Library, model: str, record: Record | None) -> tuple[str, Proble
301
302
  return "failed", {"code": code, "detail": f"the {job['kind']} process ended early"}
302
303
  if record is None:
303
304
  return "absent", None
305
+ if record["state"] == "loaded" and lib.healthy(str(record["plan"]["endpoint"]["base_url"])):
306
+ return "loaded", None
307
+ if missing := library_state.files_missing(record["plan"]):
308
+ return "failed", _missing_files(missing)
304
309
  if record["state"] == "loaded":
305
- if lib.healthy(str(record["plan"]["endpoint"]["base_url"])):
306
- return "loaded", None
307
310
  return "failed", {
308
311
  "code": "HEALTH_CHECK_FAILED",
309
312
  "detail": "the model server does not answer; load it again",
@@ -318,25 +321,41 @@ def _state(lib: Library, model: str, record: Record | None) -> tuple[str, Proble
318
321
  return "idle", None
319
322
 
320
323
 
324
+ def _missing_files(names: list[str]) -> Problem:
325
+ return {
326
+ "code": "MODEL_FILES_MISSING",
327
+ "detail": "Remove and re-download; missing: " + ", ".join(names),
328
+ }
329
+
330
+
321
331
  def _plan_of(
322
332
  lib: Library,
323
333
  model: Model,
324
334
  record: Record | None,
325
335
  priced: Priced,
326
336
  *,
327
- state: str | None = None,
337
+ state: str,
328
338
  ) -> Plan | None:
329
- """The plan a row shows: its record's (preferring ``baseline_plan`` whenever not loaded so a
330
- prior degraded load never pollutes idle/failed specs); for a model a live job is downloading,
331
- the price on the pool that job recorded (status never moves a running download to another card)."""
339
+ """Show a running server as started, but a standby curated model as the next load
340
+ would plan it. Never move an installed model to another pool or base directory."""
332
341
  if record is not None:
333
- if (
334
- state is not None
335
- and state != "loaded"
336
- and (baseline := record.get("baseline_plan")) is not None
337
- ):
338
- return baseline
339
- return record["plan"]
342
+ if state == "loaded":
343
+ return record["plan"]
344
+ if state in ("idle", "failed") and "custom" not in record:
345
+ base = library_state.base_of(record)
346
+ if priced.pool == record["pool"] and base == lib.base_dir and priced.plan is not None:
347
+ return priced.plan
348
+ try:
349
+ return library_pricing.price(
350
+ memory_pools.capacity(lib.facts, reclaimable=lib.reclaimable()),
351
+ model,
352
+ record["pool"],
353
+ base,
354
+ lib.catalog,
355
+ )
356
+ except plan_envelope.PlanError:
357
+ pass # Unsupported hardware or retired recipe: retain the installation receipt.
358
+ return record.get("baseline_plan", record["plan"])
340
359
  job, alive = lib.jobs.get(model.id, (None, False))
341
360
  if job is not None and alive and job["pool"] != priced.pool:
342
361
  try:
@@ -363,34 +382,6 @@ def pi_model_of(model: Model, record: Record | None) -> str | None:
363
382
  return library_direct.pi_model(model.id, model.variant.model_id)
364
383
 
365
384
 
366
- HUB_REPO = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*")
367
-
368
-
369
- def card(model: Model, vision_on: bool) -> Row:
370
- """The model card fields of a row, each only when the catalog states it: family,
371
- publisher and parameter scales as written there, the architecture from its MoE flag, its
372
- license, the Hugging Face page of the repository the weights come from, and vision when
373
- this deployment reads images (its projector is pinned and priced). Nothing is guessed from
374
- a name; Linger rejects a whole status document over one value outside its sets."""
375
- entry = model.entry
376
- found: dict[str, object] = {
377
- "family": entry.family,
378
- "publisher": entry.publisher.strip()[:120],
379
- "architecture": "moe" if entry.moe else "dense",
380
- "parameters": entry.parameters,
381
- "active_parameters": entry.active_parameters if entry.moe else "",
382
- "license": entry.license.strip()[:120],
383
- }
384
- if HUB_REPO.fullmatch(entry.repo):
385
- found["source_url"] = f"https://huggingface.co/{entry.repo}"
386
- caps = [c for c in entry.capabilities if c != "vision" or vision_on]
387
- if vision_on and "vision" not in caps:
388
- caps = ["vision", *caps]
389
- if caps:
390
- found["capabilities"] = caps
391
- return cast(Row, {k: v for k, v in found.items() if v})
392
-
393
-
394
385
  def _apply_live_fit(
395
386
  lib: Library,
396
387
  found: Row,
@@ -410,7 +401,7 @@ def _apply_live_fit(
410
401
  lib.facts,
411
402
  model,
412
403
  record["pool"],
413
- lib.base_dir,
404
+ library_state.base_of(record),
414
405
  lib.catalog,
415
406
  lib.reserved(),
416
407
  fallback_need=memory,
@@ -610,7 +601,7 @@ def _apply_record_meta(
610
601
  found["oom_retries"] = int(retries)
611
602
  if lp.get("forced"):
612
603
  found["forced"] = True
613
- if state == "idle" and (note := record.get("note")):
604
+ if state == "idle" and not found["fits_now"] and (note := record.get("note")):
614
605
  found["note"] = note
615
606
  if state == "failed" and problem is not None:
616
607
  found["error"] = sanitize_problem(problem)
@@ -927,6 +918,8 @@ def row(lib: Library, model: Model, *, now_utc: dt.datetime | None = None) -> Ro
927
918
  priced = lib.judge(model)
928
919
  state, problem = _state(lib, model.id, record)
929
920
  plan = _plan_of(lib, model, record, priced, state=state)
921
+ if state == "idle" and plan is not None and (missing := library_state.files_missing(plan)):
922
+ state, problem = "failed", _missing_files(missing)
930
923
  job, alive = lib.jobs.get(model.id, (None, False))
931
924
  fallback_memory, fallback_window, fallback_vision, fallback_download = (
932
925
  library_pricing.floor_metadata(
@@ -938,8 +931,6 @@ def row(lib: Library, model: Model, *, now_utc: dt.datetime | None = None) -> Ro
938
931
  memory = memory_pools.memory_bytes(plan) if plan is not None else fallback_memory
939
932
  if record is None and job is not None and alive:
940
933
  memory = job["memory_bytes"] or memory
941
- if record is not None and record["state"] != "loaded" and record.get("memory_bytes"):
942
- memory = record["memory_bytes"]
943
934
  availability: Availability = {"downloadable": True}
944
935
  if record is None:
945
936
  reason = library_pricing.download_reason(
@@ -981,7 +972,7 @@ def row(lib: Library, model: Model, *, now_utc: dt.datetime | None = None) -> Ro
981
972
  found["download"] = _downloading(job)
982
973
  elif state == "loading" and job is not None and alive:
983
974
  found["load"] = _loading(job)
984
- found.update(card(model, found["vision"]))
975
+ found.update(library_presentation.card(model, found["vision"]))
985
976
  _apply_engine_meta(lib, found, model, plan)
986
977
  library_presentation.apply_row_meta(lib.facts, found, model, plan)
987
978
  _apply_record_meta(found, model, record, state, problem, now_utc=observed_now)