@simplexai/localmodels-darwin-x64 0.1.0-dev.60 → 0.1.0-dev.62

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 (79) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +78 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +5 -3
  5. package/modules/localmodels/auth_proxy.py +185 -19
  6. package/modules/localmodels/catalog.json +363 -0
  7. package/modules/localmodels/catalog.py +1 -1
  8. package/modules/localmodels/catalog_add.py +5 -5
  9. package/modules/localmodels/catalog_license.py +2 -0
  10. package/modules/localmodels/catalog_recipes.py +2 -0
  11. package/modules/localmodels/cli_parser.py +6 -2
  12. package/modules/localmodels/context_policy.py +40 -4
  13. package/modules/localmodels/custom_hub_http.py +27 -104
  14. package/modules/localmodels/debug_mode.py +13 -0
  15. package/modules/localmodels/debug_stub_server.py +156 -1
  16. package/modules/localmodels/deploy.py +11 -2
  17. package/modules/localmodels/download-mirrors.json +12 -0
  18. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  19. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  20. package/modules/localmodels/gateway_app_bifrost.py +14 -14
  21. package/modules/localmodels/gateway_bifrost.py +4 -1
  22. package/modules/localmodels/gateway_cli.py +14 -80
  23. package/modules/localmodels/gateway_server.py +88 -16
  24. package/modules/localmodels/gpu_specs.py +35 -1
  25. package/modules/localmodels/harness.py +1 -2
  26. package/modules/localmodels/hf_repo.py +12 -4
  27. package/modules/localmodels/install.py +4 -4
  28. package/modules/localmodels/library_jobs.py +4 -0
  29. package/modules/localmodels/library_serve.py +69 -13
  30. package/modules/localmodels/memcalc_load.py +9 -4
  31. package/modules/localmodels/npm_transport.py +4 -58
  32. package/modules/localmodels/recommend_cli.py +2 -1
  33. package/modules/localmodels/remote_ops.py +120 -713
  34. package/modules/localmodels/remote_ops_common.py +670 -0
  35. package/modules/localmodels/remote_ops_download.py +399 -381
  36. package/modules/localmodels/remote_ops_mirrors.py +27 -66
  37. package/modules/localmodels/remote_ops_prepare.py +43 -35
  38. package/modules/localmodels/remote_ops_ranges.py +102 -63
  39. package/modules/localmodels/remote_ops_redirect.py +393 -0
  40. package/modules/localmodels/remote_ops_remove.py +30 -22
  41. package/modules/localmodels/remote_ops_service.py +102 -95
  42. package/modules/localmodels/remote_ops_verify.py +94 -63
  43. package/modules/localmodels/runtime_cli.py +15 -5
  44. package/modules/localmodels/runtime_io.py +54 -1
  45. package/modules/localmodels/source_cli.py +136 -23
  46. package/modules/localmodels/speech-sv.txt +93 -0
  47. package/modules/localmodels/speech_admission.py +437 -0
  48. package/modules/localmodels/speech_catalog.py +170 -0
  49. package/modules/localmodels/speech_cli.py +273 -0
  50. package/modules/localmodels/speech_jobs.py +776 -0
  51. package/modules/localmodels/speech_model.py +404 -0
  52. package/modules/localmodels/speech_serve.py +287 -0
  53. package/modules/localmodels/speech_server.py +837 -0
  54. package/modules/localmodels/speech_state.py +697 -0
  55. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  56. package/modules/localmodels/speech_workers.py +783 -0
  57. package/modules/localmodels/stack.py +0 -33
  58. package/modules/localmodels/stack_auto.py +5 -3
  59. package/modules/localmodels/stack_aux_gpu.py +45 -4
  60. package/modules/localmodels/stack_capacity.py +77 -8
  61. package/modules/localmodels/stack_cli.py +16 -1
  62. package/modules/localmodels/stack_compose.py +1 -1
  63. package/modules/localmodels/stack_down.py +24 -1
  64. package/modules/localmodels/stack_hardware.py +57 -88
  65. package/modules/localmodels/stack_hardware_text.py +4 -59
  66. package/modules/localmodels/stack_memory.py +13 -3
  67. package/modules/localmodels/stack_suite.py +9 -10
  68. package/modules/localmodels/stack_summary.py +4 -4
  69. package/modules/localmodels/stack_view_llm.py +1 -1
  70. package/modules/localmodels/transport.py +4 -2
  71. package/modules/localmodels/tui_views.py +2 -2
  72. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
  73. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +75 -61
  74. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +9 -0
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
  78. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -17,6 +17,7 @@ import os
17
17
  import shutil
18
18
  from dataclasses import dataclass
19
19
  from pathlib import Path
20
+ from typing import cast
20
21
 
21
22
  from localmodels import (
22
23
  app,
@@ -35,6 +36,7 @@ from localmodels import (
35
36
  metal,
36
37
  plan_envelope,
37
38
  source_byok,
39
+ speech_admission,
38
40
  stack_lifecycle,
39
41
  stack_ports,
40
42
  stack_verify,
@@ -375,20 +377,26 @@ def stop(record: Record, run: Executor) -> None:
375
377
  library_state.save(record)
376
378
 
377
379
 
378
- def _serve(
380
+ def demote_speech_if_holding_pool(state_dir: Path | None, pool_id: str) -> bool:
381
+ """Demote a running speech sidecar to CPU when it holds GPU/unified memory on ``pool_id``."""
382
+ return speech_admission.demote_speech_if_holding_pool(state_dir, pool_id)
383
+
384
+
385
+ def _serve_elastic_plan(
379
386
  model: Model,
380
387
  record: Record,
381
388
  facts: HostFacts,
382
- run: Executor,
389
+ base: str,
383
390
  port: int,
384
- handle: JobHandle,
385
391
  ctx: LoadContext,
386
- ) -> Record:
387
- base = base_of(record)
388
- now = library_pricing.live(facts, _reserved(model.id))
389
- use_jinja, autostart = _custom_flags(record)
390
- try:
391
- elastic = library_elastic.price_elastic(
392
+ *,
393
+ use_jinja: bool,
394
+ ) -> tuple[HostFacts, ElasticPlan]:
395
+ """Price the elastic plan for ``_serve``, demoting GPU-resident speech first when tight."""
396
+
397
+ def price(seen: HostFacts) -> ElasticPlan:
398
+ now = library_pricing.live(seen, _reserved(model.id))
399
+ return library_elastic.price_elastic(
392
400
  now,
393
401
  model,
394
402
  record["pool"],
@@ -400,7 +408,18 @@ def _serve(
400
408
  ctx_override=ctx.ctx_override,
401
409
  use_jinja=use_jinja,
402
410
  )
403
- except deploy.AgentMemoryError as exc: # after --unload: no longer a refusal
411
+
412
+ try:
413
+ elastic = price(facts)
414
+ except deploy.AgentMemoryError as exc:
415
+ if demote_speech_if_holding_pool(hosts.state_dir(), record["pool"]):
416
+ fresh = library_jobs.probe()
417
+ try:
418
+ return fresh, price(fresh)
419
+ except deploy.AgentMemoryError as retry_exc:
420
+ raise _fail(
421
+ record, _no_room_error(model, retry_exc, record["pool"], failed=True)
422
+ ) from None
404
423
  raise _fail(record, _no_room_error(model, exc, record["pool"], failed=True)) from None
405
424
  except engines.CudaDriverError as exc:
406
425
  raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc), failed=True) from None
@@ -422,6 +441,25 @@ def _serve(
422
441
  can_force=False,
423
442
  ),
424
443
  ) from None
444
+ if elastic.degraded and demote_speech_if_holding_pool(hosts.state_dir(), record["pool"]):
445
+ fresh = library_jobs.probe()
446
+ with contextlib.suppress(deploy.AgentMemoryError, library_pricing.LiveMemoryUnavailable):
447
+ return fresh, price(fresh)
448
+ return facts, elastic
449
+
450
+
451
+ def _serve(
452
+ model: Model,
453
+ record: Record,
454
+ facts: HostFacts,
455
+ run: Executor,
456
+ port: int,
457
+ handle: JobHandle,
458
+ ctx: LoadContext,
459
+ ) -> Record:
460
+ base = base_of(record)
461
+ use_jinja, autostart = _custom_flags(record)
462
+ facts, elastic = _serve_elastic_plan(model, record, facts, base, port, ctx, use_jinja=use_jinja)
425
463
  plan = elastic.plan
426
464
  if not autostart:
427
465
  plan["service"]["autostart"] = False
@@ -614,8 +652,10 @@ def _admit(
614
652
  ) -> None:
615
653
  """Under ``locked()``: LOAD_NO_ROOM unless the model fits its pool in ``facts`` (probed
616
654
  under the same lock), less every live load's reservation, plus what ``targets`` and a
617
- stale server of the model itself give back. The caller commits its own reservation before
618
- releasing the lock, so the next claimant sees it."""
655
+ stale server of the model itself give back. If speech holds VRAM/unified memory on the
656
+ target pool and admission would fail or degrade posture, demote speech to CPU and re-probe
657
+ first. The caller commits its own reservation before releasing the lock, so the next
658
+ claimant sees it."""
619
659
  freed: dict[str, int] = {}
620
660
  catalog = library_pricing.entries()
621
661
  for target in [*targets, *([record] if record["state"] != "idle" else [])]:
@@ -630,7 +670,23 @@ def _admit(
630
670
  freed["system"] = freed.get("system", 0) + library_pricing.host_ram_bytes(
631
671
  target["plan"], catalog
632
672
  )
633
- _room(facts, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
673
+ try:
674
+ elastic = _room(facts, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
675
+ except LibraryError as exc:
676
+ if exc.code == "LOAD_NO_ROOM" and demote_speech_if_holding_pool(
677
+ hosts.state_dir(), record["pool"]
678
+ ):
679
+ fresh = library_jobs.probe()
680
+ _room(fresh, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
681
+ cast(dict[str, object], facts).clear()
682
+ facts.update(fresh)
683
+ return
684
+ raise
685
+ if elastic.degraded and demote_speech_if_holding_pool(hosts.state_dir(), record["pool"]):
686
+ fresh = library_jobs.probe()
687
+ _room(fresh, model, record, freed, force=ctx.force, ctx=ctx.ctx_override)
688
+ cast(dict[str, object], facts).clear()
689
+ facts.update(fresh)
634
690
 
635
691
 
636
692
  def _row(model: Model, base_dir: str) -> Row:
@@ -14,7 +14,7 @@ from dataclasses import dataclass, replace
14
14
  from pathlib import Path
15
15
  from typing import Any
16
16
 
17
- from localmodels import estimator
17
+ from localmodels import estimator, remote_ops_redirect
18
18
  from localmodels.gguf import read_gguf_header, split_parts
19
19
  from localmodels.memcalc import (
20
20
  MIB,
@@ -73,12 +73,17 @@ def safetensors_size(directory: Path) -> tuple[int, int]:
73
73
 
74
74
  def _http_json(url: str, timeout: float) -> dict[str, Any]:
75
75
  headers = {"User-Agent": "localmodels-memcalc"}
76
- token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
77
- if token:
76
+ token = (os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or "").strip()
77
+ try:
78
+ scheme, host, _ = remote_ops_redirect.url_origin(url)
79
+ except remote_ops_redirect.UnsafeRedirectError as exc:
80
+ raise MemcalcError(f"could not fetch {url.split('?')[0]}: {exc}") from exc
81
+ if token and scheme == "https" and host and not remote_ops_redirect.is_hf_mirror_host(host):
78
82
  headers["Authorization"] = f"Bearer {token}"
79
83
  request = urllib.request.Request(url, headers=headers)
84
+ opener = urllib.request.build_opener(remote_ops_redirect.SafeRedirectHandler())
80
85
  try:
81
- with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310
86
+ with opener.open(request, timeout=timeout) as response:
82
87
  data = json.loads(response.read(16 * MIB))
83
88
  except OSError as exc:
84
89
  raise MemcalcError(f"could not fetch {url.split('?')[0]}: {exc}") from exc
@@ -6,14 +6,13 @@ import hashlib
6
6
  import http.client
7
7
  import os
8
8
  import queue
9
- import re
10
9
  import sys
11
10
  import tarfile
12
11
  import threading
13
12
  import time
14
13
  import urllib.error
15
14
  import urllib.request
16
- from collections.abc import Callable, Mapping
15
+ from collections.abc import Mapping
17
16
  from pathlib import Path
18
17
  from typing import Any, TypedDict
19
18
  from urllib.parse import urljoin, urlsplit
@@ -36,7 +35,7 @@ class UnsafeRedirect(urllib.error.URLError):
36
35
  """A URL or redirect target without HTTPS, or with credentials, that is never contacted."""
37
36
 
38
37
 
39
- def _check_url(url: str, *, redirect: bool = False) -> str:
38
+ def check_url(url: str, *, redirect: bool = False) -> str:
40
39
  try:
41
40
  parts = urlsplit(url)
42
41
  _ = parts.port
@@ -67,7 +66,7 @@ def _redirect_target(url: str, location: str, hops: int) -> str:
67
66
  target = urljoin(url, location)
68
67
  except ValueError as error:
69
68
  raise UnsafeRedirect("invalid npm redirect URL") from error
70
- return _check_url(target, redirect=True)
69
+ return check_url(target, redirect=True)
71
70
 
72
71
 
73
72
  class HttpsRedirect(urllib.request.HTTPRedirectHandler):
@@ -136,7 +135,7 @@ def package_url(name: str, version: str, region: str, env: Mapping[str, str]) ->
136
135
  def _probe(url: str, results: queue.Queue[bool]) -> None:
137
136
  deadline = time.monotonic() + 5
138
137
  try:
139
- _check_url(url)
138
+ check_url(url)
140
139
  for hops in range(6):
141
140
  parts = urlsplit(url)
142
141
  connection_type = (
@@ -239,56 +238,3 @@ def extract_bifrost(archive: Path, destination: Path, digest: str, size: int) ->
239
238
  raise ValueError("Bifrost binary SHA256 mismatch")
240
239
  destination.write_bytes(body)
241
240
  destination.chmod(0o755)
242
-
243
-
244
- def _archive_pin(build: Mapping[str, Any]) -> tuple[str, int]:
245
- """The npm tarball's SHA256 and size, which every Bifrost build of the tool lock carries."""
246
- pin = build["npm"]
247
- digest, size = pin.get("sha256"), pin.get("bytes")
248
- if (
249
- not isinstance(digest, str)
250
- or not re.fullmatch("[0-9a-f]{64}", digest)
251
- or type(size) is not int
252
- or not 0 < size <= archive_size_cap(build["size_bytes"])
253
- ):
254
- raise ValueError(
255
- "Bifrost npm archive pin is missing or invalid (the tool lock needs npm sha256 and"
256
- " bytes)"
257
- )
258
- return digest, size
259
-
260
-
261
- def _sha256(path: Path) -> str:
262
- digest = hashlib.sha256()
263
- with path.open("rb") as stream:
264
- for chunk in iter(lambda: stream.read(1 << 20), b""):
265
- digest.update(chunk)
266
- return digest.hexdigest()
267
-
268
-
269
- def fetch_bifrost(
270
- build: Mapping[str, Any],
271
- destination: Path,
272
- archive: Path,
273
- event: Callable[[dict[str, Any]], None],
274
- ) -> None:
275
- """Put the pinned Bifrost binary of ``build`` at ``destination``. The npm tarball downloads
276
- to ``archive``, which must outlive this call: an interrupted download keeps
277
- ``archive.part`` for the next call to resume (``runtime_io.download``, which also moves
278
- between the npm registry and its mirror), and a complete tarball left by a crash before
279
- extraction is reused when it matches the pin. The tarball is deleted once extracted."""
280
- from localmodels import runtime_io # runtime_io reaches the region through this module
281
-
282
- digest, size = _archive_pin(build)
283
- if archive.exists() or archive.is_symlink():
284
- if archive.is_file() and not archive.is_symlink() and _sha256(archive) == digest:
285
- event({"kind": "stage", "stage": "download", "state": "reused"})
286
- else:
287
- archive.unlink()
288
- if not archive.exists():
289
- pin = build["npm"]
290
- url = _check_url(package_url(pin["package"], pin["version"], "global", os.environ))
291
- artifact = {"url": url, "algorithm": "sha256", "digest": digest, "maxBytes": size}
292
- runtime_io.download(artifact, archive, event)
293
- extract_bifrost(archive, destination, build["sha256"], build["size_bytes"])
294
- archive.unlink()
@@ -15,6 +15,7 @@ from localmodels import (
15
15
  stack,
16
16
  stack_capacity,
17
17
  stack_hardware,
18
+ stack_hardware_text,
18
19
  stack_summary,
19
20
  suite,
20
21
  )
@@ -138,7 +139,7 @@ def _show_parts(
138
139
  print(" 按上面的硬件快照规划,不是已批准的安装计划。")
139
140
  print(
140
141
  f" LLM 窗口 {stack_summary.window_label(llm['launch']['window'])},"
141
- + (stack_hardware.agent_label(llm) or f"{llm['launch']['slots']} 路,")
142
+ + (stack_hardware_text.agent_label(llm) or f"{llm['launch']['slots']} 路,")
142
143
  + _mtp_words(llm)
143
144
  + READER_WORDS.get(str(llm["launch"].get("vision") or "off"), "图片输入关闭")
144
145
  )