@simplexai/localmodels-linux-arm64 0.1.0-dev.59 → 0.1.0-dev.61

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 (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +126 -107
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +107 -44
  5. package/modules/localmodels/apple_sensors.py +431 -0
  6. package/modules/localmodels/auth_proxy.py +185 -19
  7. package/modules/localmodels/bifrost_admin.py +30 -0
  8. package/modules/localmodels/bifrost_checks.py +2 -2
  9. package/modules/localmodels/bifrost_config.py +132 -9
  10. package/modules/localmodels/bifrost_models.py +1 -1
  11. package/modules/localmodels/catalog.json +509 -54
  12. package/modules/localmodels/catalog.py +21 -4
  13. package/modules/localmodels/catalog_add.py +42 -11
  14. package/modules/localmodels/catalog_license.py +2 -0
  15. package/modules/localmodels/catalog_recipes.py +2 -0
  16. package/modules/localmodels/cli_parser.py +6 -2
  17. package/modules/localmodels/context_policy.py +40 -4
  18. package/modules/localmodels/custom_hub.py +983 -0
  19. package/modules/localmodels/custom_hub_http.py +579 -0
  20. package/modules/localmodels/custom_probe.py +451 -0
  21. package/modules/localmodels/debug_mode.py +13 -0
  22. package/modules/localmodels/debug_stub_server.py +156 -1
  23. package/modules/localmodels/deploy.py +38 -7
  24. package/modules/localmodels/deploy_steps.py +5 -0
  25. package/modules/localmodels/download-mirrors.json +20 -0
  26. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  27. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  28. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  29. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  30. package/modules/localmodels/engines.py +38 -8
  31. package/modules/localmodels/estimator.py +60 -7
  32. package/modules/localmodels/gateway.py +48 -3
  33. package/modules/localmodels/gateway_app_bifrost.py +18 -18
  34. package/modules/localmodels/gateway_bifrost.py +102 -16
  35. package/modules/localmodels/gateway_cli.py +14 -80
  36. package/modules/localmodels/gateway_server.py +88 -16
  37. package/modules/localmodels/gguf.py +6 -0
  38. package/modules/localmodels/gpu_specs.py +35 -1
  39. package/modules/localmodels/harness.py +1 -2
  40. package/modules/localmodels/hf_repo.py +12 -4
  41. package/modules/localmodels/host_sensors.py +704 -0
  42. package/modules/localmodels/install.py +4 -4
  43. package/modules/localmodels/library_cli.py +181 -3
  44. package/modules/localmodels/library_custom.py +831 -0
  45. package/modules/localmodels/library_elastic.py +35 -7
  46. package/modules/localmodels/library_gateway.py +94 -32
  47. package/modules/localmodels/library_jobs.py +76 -11
  48. package/modules/localmodels/library_kept.py +50 -6
  49. package/modules/localmodels/library_model.py +254 -2
  50. package/modules/localmodels/library_pricing.py +83 -4
  51. package/modules/localmodels/library_serve.py +178 -60
  52. package/modules/localmodels/library_smoke.py +315 -0
  53. package/modules/localmodels/library_state.py +77 -1
  54. package/modules/localmodels/library_status.py +126 -4
  55. package/modules/localmodels/npm_transport.py +4 -58
  56. package/modules/localmodels/nvml_ctypes.py +431 -0
  57. package/modules/localmodels/plan_envelope.py +14 -6
  58. package/modules/localmodels/recommend_cli.py +2 -1
  59. package/modules/localmodels/records.py +1 -0
  60. package/modules/localmodels/remote_ops.py +120 -665
  61. package/modules/localmodels/remote_ops_common.py +729 -0
  62. package/modules/localmodels/remote_ops_download.py +396 -241
  63. package/modules/localmodels/remote_ops_mirrors.py +26 -65
  64. package/modules/localmodels/remote_ops_prepare.py +43 -35
  65. package/modules/localmodels/remote_ops_ranges.py +98 -65
  66. package/modules/localmodels/remote_ops_remove.py +30 -22
  67. package/modules/localmodels/remote_ops_service.py +103 -95
  68. package/modules/localmodels/remote_ops_verify.py +113 -65
  69. package/modules/localmodels/runtime-lock.json +19 -19
  70. package/modules/localmodels/runtime_cli.py +15 -5
  71. package/modules/localmodels/runtime_io.py +54 -1
  72. package/modules/localmodels/service_control.py +32 -1
  73. package/modules/localmodels/service_wiring.py +2 -3
  74. package/modules/localmodels/service_worker.py +6 -2
  75. package/modules/localmodels/services_cli.py +35 -27
  76. package/modules/localmodels/source_byok.py +3 -5
  77. package/modules/localmodels/speech-sv.txt +93 -0
  78. package/modules/localmodels/speech_admission.py +437 -0
  79. package/modules/localmodels/speech_catalog.py +170 -0
  80. package/modules/localmodels/speech_cli.py +273 -0
  81. package/modules/localmodels/speech_jobs.py +772 -0
  82. package/modules/localmodels/speech_model.py +404 -0
  83. package/modules/localmodels/speech_serve.py +287 -0
  84. package/modules/localmodels/speech_server.py +837 -0
  85. package/modules/localmodels/speech_state.py +697 -0
  86. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  87. package/modules/localmodels/speech_workers.py +783 -0
  88. package/modules/localmodels/stack.py +0 -33
  89. package/modules/localmodels/stack_auto.py +5 -3
  90. package/modules/localmodels/stack_aux_gpu.py +45 -4
  91. package/modules/localmodels/stack_capacity.py +77 -8
  92. package/modules/localmodels/stack_cli.py +16 -1
  93. package/modules/localmodels/stack_compose.py +1 -1
  94. package/modules/localmodels/stack_down.py +24 -1
  95. package/modules/localmodels/stack_hardware.py +57 -88
  96. package/modules/localmodels/stack_hardware_text.py +4 -59
  97. package/modules/localmodels/stack_lifecycle.py +2 -2
  98. package/modules/localmodels/stack_memory.py +14 -3
  99. package/modules/localmodels/stack_suite.py +9 -10
  100. package/modules/localmodels/stack_summary.py +4 -4
  101. package/modules/localmodels/stack_view.py +77 -53
  102. package/modules/localmodels/stack_view_demo.py +36 -5
  103. package/modules/localmodels/stack_view_events.py +147 -12
  104. package/modules/localmodels/stack_view_gpu.py +97 -17
  105. package/modules/localmodels/stack_view_llm.py +16 -1
  106. package/modules/localmodels/stack_view_measure.py +4 -1
  107. package/modules/localmodels/stack_view_schema.py +54 -8
  108. package/modules/localmodels/stack_view_serve.py +40 -3
  109. package/modules/localmodels/stack_view_slots.py +89 -10
  110. package/modules/localmodels/stack_view_telemetry.py +163 -0
  111. package/modules/localmodels/stack_view_text.py +5 -2
  112. package/modules/localmodels/stack_view_tick.py +658 -0
  113. package/modules/localmodels/stack_view_words.py +4 -0
  114. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  115. package/modules/localmodels/suite.py +3 -1
  116. package/modules/localmodels/telemetry_math.py +538 -0
  117. package/modules/localmodels/transport.py +3 -2
  118. package/modules/localmodels/tui_views.py +2 -2
  119. package/modules/localmodels/web/view/view.js +1 -1
  120. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
  121. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
  122. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
  123. package/package.json +1 -1
  124. package/tool.json +1 -1
  125. package/modules/localmodels/bifrost_datasheet.py +0 -53
  126. package/modules/localmodels/bifrost_provider.py +0 -88
  127. package/modules/localmodels/bifrost_unit.py +0 -99
  128. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
  129. package/modules/localmodels/gateway_switch.py +0 -51
  130. package/modules/localmodels/library_floor.py +0 -78
  131. package/modules/localmodels/service_stop.py +0 -52
  132. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -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()
@@ -0,0 +1,431 @@
1
+ """Persistent ctypes binding to NVIDIA NVML (libnvidia-ml.so.1 / nvml.dll).
2
+
3
+ Provides zero-fork, read-only GPU telemetry (compute utilization, memory controller utilization,
4
+ VRAM total/used/free, temperature, power draw & limit, and per-process VRAM) on Linux and Windows.
5
+ Falls back cleanly (returning None) whenever NVML is unavailable or fails, without raising.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import atexit
11
+ import ctypes
12
+ import os
13
+ import sys
14
+ import threading
15
+ import time
16
+ from typing import Any, TypedDict
17
+
18
+ NVML_SUCCESS = 0
19
+ NVML_ERROR_UNINITIALIZED = 1
20
+ NVML_ERROR_INSUFFICIENT_SIZE = 7
21
+ NVML_ERROR_GPU_IS_LOST = 15
22
+ NVML_TEMPERATURE_GPU = 0
23
+ NVML_VALUE_NOT_AVAILABLE = 0xFFFFFFFFFFFFFFFF # 2**64 - 1 (WDDM / unsupported)
24
+ _RESET_ERRORS = frozenset({NVML_ERROR_UNINITIALIZED, NVML_ERROR_GPU_IS_LOST})
25
+ _RETRY_COOLDOWN_S = 30.0
26
+ _MAX_PROCESS_SLOTS = 256
27
+ _NAME_BUF_SIZE = 96
28
+
29
+
30
+ class NvmlProcess(TypedDict):
31
+ pid: int
32
+ used_bytes: int | None
33
+ kind: str # compute | graphics
34
+
35
+
36
+ class NvmlDeviceSample(TypedDict):
37
+ index: int
38
+ name: str
39
+ util_pct: float | None
40
+ mem_ctrl_util_pct: float | None
41
+ vram_total_bytes: int | None
42
+ vram_used_bytes: int | None
43
+ vram_free_bytes: int | None
44
+ temp_c: float | None
45
+ power_w: float | None
46
+ power_limit_w: float | None
47
+ processes: list[NvmlProcess]
48
+ basis: str # live
49
+
50
+
51
+ class _NvmlUtilization(ctypes.Structure):
52
+ _fields_ = [("gpu", ctypes.c_uint), ("memory", ctypes.c_uint)]
53
+
54
+
55
+ class _NvmlMemory(ctypes.Structure):
56
+ _fields_ = [
57
+ ("total", ctypes.c_ulonglong),
58
+ ("free", ctypes.c_ulonglong),
59
+ ("used", ctypes.c_ulonglong),
60
+ ]
61
+
62
+
63
+ class _NvmlProcessInfoV2(ctypes.Structure):
64
+ _fields_ = [
65
+ ("pid", ctypes.c_uint),
66
+ ("usedGpuMemory", ctypes.c_ulonglong),
67
+ ("gpuInstanceId", ctypes.c_uint),
68
+ ("computeInstanceId", ctypes.c_uint),
69
+ ]
70
+
71
+
72
+ def _candidate_libraries(platform: str | None = None) -> tuple[str, ...]:
73
+ plat = sys.platform if platform is None else platform
74
+ if plat == "win32":
75
+ candidates = ["nvml.dll"]
76
+ sys_root = os.environ.get("SystemRoot", r"C:\Windows")
77
+ prog_files = os.environ.get("ProgramFiles", r"C:\Program Files")
78
+ candidates.append(os.path.join(sys_root, "System32", "nvml.dll"))
79
+ candidates.append(os.path.join(prog_files, "NVIDIA Corporation", "NVSMI", "nvml.dll"))
80
+ return tuple(candidates)
81
+ if plat.startswith("linux"):
82
+ return ("libnvidia-ml.so.1", "libnvidia-ml.so")
83
+ return ()
84
+
85
+
86
+ def _load_library(platform: str | None = None) -> Any | None:
87
+ plat = sys.platform if platform is None else platform
88
+ # nvml.h exports cdecl symbols on both Linux and Windows; CDLL matches nvidia-ml-py/pynvml.
89
+ for name in _candidate_libraries(plat):
90
+ try:
91
+ return ctypes.CDLL(name)
92
+ except OSError:
93
+ continue
94
+ return None
95
+
96
+
97
+ def _resolve_fn(lib: Any, *names: str) -> Any | None:
98
+ for name in names:
99
+ fn = getattr(lib, name, None)
100
+ if fn is not None:
101
+ return fn
102
+ return None
103
+
104
+
105
+ def _set_proto(fn: Any, argtypes: list[Any], restype: Any = ctypes.c_int) -> None:
106
+ if fn is not None and hasattr(fn, "argtypes") and hasattr(fn, "restype"):
107
+ fn.argtypes = argtypes
108
+ fn.restype = restype
109
+
110
+
111
+ def _bind_prototypes(lib: Any) -> None:
112
+ """Bind explicit ctypes argtypes/restype on every NVML C entry point we invoke."""
113
+ c_uint_p = ctypes.POINTER(ctypes.c_uint)
114
+ c_void_pp = ctypes.POINTER(ctypes.c_void_p)
115
+ proc_p = ctypes.POINTER(_NvmlProcessInfoV2)
116
+ specs: list[tuple[tuple[str, ...], list[Any]]] = [
117
+ (("nvmlInit_v2", "nvmlInit"), []),
118
+ (("nvmlShutdown",), []),
119
+ (("nvmlDeviceGetCount_v2", "nvmlDeviceGetCount"), [c_uint_p]),
120
+ (
121
+ ("nvmlDeviceGetHandleByIndex_v2", "nvmlDeviceGetHandleByIndex"),
122
+ [ctypes.c_uint, c_void_pp],
123
+ ),
124
+ (("nvmlDeviceGetName",), [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint]),
125
+ (
126
+ ("nvmlDeviceGetUtilizationRates",),
127
+ [ctypes.c_void_p, ctypes.POINTER(_NvmlUtilization)],
128
+ ),
129
+ (("nvmlDeviceGetMemoryInfo",), [ctypes.c_void_p, ctypes.POINTER(_NvmlMemory)]),
130
+ (("nvmlDeviceGetTemperature",), [ctypes.c_void_p, ctypes.c_uint, c_uint_p]),
131
+ (("nvmlDeviceGetPowerUsage",), [ctypes.c_void_p, c_uint_p]),
132
+ (
133
+ ("nvmlDeviceGetEnforcedPowerLimit", "nvmlDeviceGetPowerManagementLimit"),
134
+ [ctypes.c_void_p, c_uint_p],
135
+ ),
136
+ (
137
+ (
138
+ "nvmlDeviceGetComputeRunningProcesses_v3",
139
+ "nvmlDeviceGetComputeRunningProcesses_v2",
140
+ ),
141
+ [ctypes.c_void_p, c_uint_p, proc_p],
142
+ ),
143
+ (
144
+ (
145
+ "nvmlDeviceGetGraphicsRunningProcesses_v3",
146
+ "nvmlDeviceGetGraphicsRunningProcesses_v2",
147
+ ),
148
+ [ctypes.c_void_p, c_uint_p, proc_p],
149
+ ),
150
+ ]
151
+ for names, argtypes in specs:
152
+ _set_proto(_resolve_fn(lib, *names), argtypes)
153
+
154
+
155
+ class _NvmlSession:
156
+ """Lazy, process-lifetime NVML handle guarded by a lock with cooldown retry & loss recovery."""
157
+
158
+ def __init__(self) -> None:
159
+ self._lock = threading.Lock()
160
+ self._lib: Any | None = None
161
+ self._initialized = False
162
+ self._failed_until = 0.0
163
+
164
+ def reset(self) -> None:
165
+ with self._lock:
166
+ self._shutdown_locked()
167
+ self._failed_until = 0.0
168
+
169
+ def _shutdown_locked(self) -> None:
170
+ if self._initialized and self._lib is not None:
171
+ shutdown = _resolve_fn(self._lib, "nvmlShutdown")
172
+ if shutdown is not None:
173
+ try:
174
+ shutdown()
175
+ except (OSError, ValueError):
176
+ pass
177
+ self._initialized = False
178
+ self._lib = None
179
+
180
+ def _ensure_locked(self) -> Any | None:
181
+ if self._initialized and self._lib is not None:
182
+ return self._lib
183
+ now = time.monotonic()
184
+ if now < self._failed_until:
185
+ return None
186
+ lib = _load_library()
187
+ if lib is None:
188
+ self._failed_until = now + _RETRY_COOLDOWN_S
189
+ return None
190
+ _bind_prototypes(lib)
191
+ init_fn = _resolve_fn(lib, "nvmlInit_v2", "nvmlInit")
192
+ if init_fn is None:
193
+ self._failed_until = now + _RETRY_COOLDOWN_S
194
+ return None
195
+ try:
196
+ rc = int(init_fn())
197
+ except (OSError, ValueError, TypeError):
198
+ self._failed_until = now + _RETRY_COOLDOWN_S
199
+ return None
200
+ if rc != NVML_SUCCESS:
201
+ self._failed_until = now + _RETRY_COOLDOWN_S
202
+ return None
203
+ self._lib = lib
204
+ self._initialized = True
205
+ self._failed_until = 0.0
206
+ return lib
207
+
208
+ def read_all(self, *, include_processes: bool = True) -> list[NvmlDeviceSample] | None:
209
+ with self._lock:
210
+ lib = self._ensure_locked()
211
+ if lib is None:
212
+ return None
213
+ devices, needs_reset = _query_devices(lib, include_processes=include_processes)
214
+ if needs_reset:
215
+ self._shutdown_locked()
216
+ self._failed_until = 0.0
217
+ return devices
218
+
219
+ def shutdown(self) -> None:
220
+ with self._lock:
221
+ self._shutdown_locked()
222
+
223
+
224
+ def _query_name(lib: Any, handle: ctypes.c_void_p, index: int) -> str:
225
+ fn = _resolve_fn(lib, "nvmlDeviceGetName")
226
+ if fn is None:
227
+ return f"GPU {index}"
228
+ buf = ctypes.create_string_buffer(_NAME_BUF_SIZE)
229
+ try:
230
+ if int(fn(handle, buf, ctypes.c_uint(_NAME_BUF_SIZE))) == NVML_SUCCESS:
231
+ return buf.value.decode("utf-8", "replace").strip() or f"GPU {index}"
232
+ except (OSError, ValueError, TypeError):
233
+ pass
234
+ return f"GPU {index}"
235
+
236
+
237
+ def _query_utilization(lib: Any, handle: ctypes.c_void_p) -> tuple[float | None, float | None]:
238
+ fn = _resolve_fn(lib, "nvmlDeviceGetUtilizationRates")
239
+ if fn is None:
240
+ return None, None
241
+ util = _NvmlUtilization()
242
+ try:
243
+ if int(fn(handle, ctypes.byref(util))) == NVML_SUCCESS:
244
+ gpu = float(util.gpu) if 0 <= util.gpu <= 100 else None
245
+ mem = float(util.memory) if 0 <= util.memory <= 100 else None
246
+ return gpu, mem
247
+ except (OSError, ValueError, TypeError):
248
+ pass
249
+ return None, None
250
+
251
+
252
+ def _query_memory(lib: Any, handle: ctypes.c_void_p) -> tuple[int | None, int | None, int | None]:
253
+ fn = _resolve_fn(lib, "nvmlDeviceGetMemoryInfo")
254
+ if fn is None:
255
+ return None, None, None
256
+ info = _NvmlMemory()
257
+ try:
258
+ if int(fn(handle, ctypes.byref(info))) == NVML_SUCCESS:
259
+ return int(info.total), int(info.used), int(info.free)
260
+ except (OSError, ValueError, TypeError):
261
+ pass
262
+ return None, None, None
263
+
264
+
265
+ def _query_temp(lib: Any, handle: ctypes.c_void_p) -> float | None:
266
+ fn = _resolve_fn(lib, "nvmlDeviceGetTemperature")
267
+ if fn is None:
268
+ return None
269
+ temp = ctypes.c_uint(0)
270
+ try:
271
+ if int(fn(handle, ctypes.c_uint(NVML_TEMPERATURE_GPU), ctypes.byref(temp))) == NVML_SUCCESS:
272
+ return float(temp.value)
273
+ except (OSError, ValueError, TypeError):
274
+ pass
275
+ return None
276
+
277
+
278
+ def _query_power(lib: Any, handle: ctypes.c_void_p) -> tuple[float | None, float | None]:
279
+ usage_w: float | None = None
280
+ limit_w: float | None = None
281
+ fn_usage = _resolve_fn(lib, "nvmlDeviceGetPowerUsage")
282
+ if fn_usage is not None:
283
+ mw = ctypes.c_uint(0)
284
+ try:
285
+ if int(fn_usage(handle, ctypes.byref(mw))) == NVML_SUCCESS:
286
+ usage_w = round(mw.value / 1000.0, 2)
287
+ except (OSError, ValueError, TypeError):
288
+ pass
289
+ fn_limit = _resolve_fn(
290
+ lib, "nvmlDeviceGetEnforcedPowerLimit", "nvmlDeviceGetPowerManagementLimit"
291
+ )
292
+ if fn_limit is not None:
293
+ mw_limit = ctypes.c_uint(0)
294
+ try:
295
+ if int(fn_limit(handle, ctypes.byref(mw_limit))) == NVML_SUCCESS and mw_limit.value > 0:
296
+ limit_w = round(mw_limit.value / 1000.0, 2)
297
+ except (OSError, ValueError, TypeError):
298
+ pass
299
+ return usage_w, limit_w
300
+
301
+
302
+ def _query_processes_of_kind(
303
+ lib: Any, handle: ctypes.c_void_p, fn_names: tuple[str, ...], kind: str
304
+ ) -> list[NvmlProcess]:
305
+ fn = _resolve_fn(lib, *fn_names)
306
+ if fn is None:
307
+ return []
308
+ count = ctypes.c_uint(_MAX_PROCESS_SLOTS)
309
+ buf = (_NvmlProcessInfoV2 * _MAX_PROCESS_SLOTS)()
310
+ try:
311
+ rc = int(fn(handle, ctypes.byref(count), buf))
312
+ except (OSError, ValueError, TypeError):
313
+ return []
314
+ if rc == NVML_ERROR_INSUFFICIENT_SIZE and count.value > 0:
315
+ capped = min(int(count.value), 1024)
316
+ count = ctypes.c_uint(capped)
317
+ buf = (_NvmlProcessInfoV2 * capped)()
318
+ try:
319
+ rc = int(fn(handle, ctypes.byref(count), buf))
320
+ except (OSError, ValueError, TypeError):
321
+ return []
322
+ if rc != NVML_SUCCESS:
323
+ return []
324
+ found: list[NvmlProcess] = []
325
+ for i in range(min(int(count.value), len(buf))):
326
+ raw_mem = int(buf[i].usedGpuMemory)
327
+ used = None if raw_mem == NVML_VALUE_NOT_AVAILABLE else raw_mem
328
+ found.append({"pid": int(buf[i].pid), "used_bytes": used, "kind": kind})
329
+ return found
330
+
331
+
332
+ def _query_processes(lib: Any, handle: ctypes.c_void_p) -> list[NvmlProcess]:
333
+ compute = _query_processes_of_kind(
334
+ lib,
335
+ handle,
336
+ (
337
+ "nvmlDeviceGetComputeRunningProcesses_v3",
338
+ "nvmlDeviceGetComputeRunningProcesses_v2",
339
+ ),
340
+ "compute",
341
+ )
342
+ graphics = _query_processes_of_kind(
343
+ lib,
344
+ handle,
345
+ (
346
+ "nvmlDeviceGetGraphicsRunningProcesses_v3",
347
+ "nvmlDeviceGetGraphicsRunningProcesses_v2",
348
+ ),
349
+ "graphics",
350
+ )
351
+ seen: dict[int, NvmlProcess] = {}
352
+ for proc in (*compute, *graphics):
353
+ prev = seen.get(proc["pid"])
354
+ if prev is None or (prev["used_bytes"] is None and proc["used_bytes"] is not None):
355
+ seen[proc["pid"]] = proc
356
+ return list(seen.values())
357
+
358
+
359
+ def _query_devices(
360
+ lib: Any, *, include_processes: bool = True
361
+ ) -> tuple[list[NvmlDeviceSample] | None, bool]:
362
+ count_fn = _resolve_fn(lib, "nvmlDeviceGetCount_v2", "nvmlDeviceGetCount")
363
+ handle_fn = _resolve_fn(lib, "nvmlDeviceGetHandleByIndex_v2", "nvmlDeviceGetHandleByIndex")
364
+ if count_fn is None or handle_fn is None:
365
+ return None, False
366
+ count = ctypes.c_uint(0)
367
+ try:
368
+ rc = int(count_fn(ctypes.byref(count)))
369
+ except (OSError, ValueError, TypeError):
370
+ return None, False
371
+ if rc != NVML_SUCCESS:
372
+ return None, rc in _RESET_ERRORS
373
+ devices: list[NvmlDeviceSample] = []
374
+ for index in range(int(count.value)):
375
+ handle = ctypes.c_void_p()
376
+ try:
377
+ h_rc = int(handle_fn(ctypes.c_uint(index), ctypes.byref(handle)))
378
+ except (OSError, ValueError, TypeError):
379
+ continue
380
+ if h_rc != NVML_SUCCESS:
381
+ if h_rc in _RESET_ERRORS:
382
+ return None, True
383
+ continue
384
+ util_pct, mem_ctrl_pct = _query_utilization(lib, handle)
385
+ total_b, used_b, free_b = _query_memory(lib, handle)
386
+ power_w, power_limit_w = _query_power(lib, handle)
387
+ devices.append(
388
+ {
389
+ "index": index,
390
+ "name": _query_name(lib, handle, index),
391
+ "util_pct": util_pct,
392
+ "mem_ctrl_util_pct": mem_ctrl_pct,
393
+ "vram_total_bytes": total_b,
394
+ "vram_used_bytes": used_b,
395
+ "vram_free_bytes": free_b,
396
+ "temp_c": _query_temp(lib, handle),
397
+ "power_w": power_w,
398
+ "power_limit_w": power_limit_w,
399
+ "processes": _query_processes(lib, handle) if include_processes else [],
400
+ "basis": "live",
401
+ }
402
+ )
403
+ return devices, False
404
+
405
+
406
+ _SESSION = _NvmlSession()
407
+ atexit.register(_SESSION.shutdown)
408
+
409
+
410
+ def read_devices(*, include_processes: bool = True) -> list[NvmlDeviceSample] | None:
411
+ """Read live NVML metrics for all NVIDIA GPUs; None when NVML is unavailable."""
412
+ return _SESSION.read_all(include_processes=include_processes)
413
+
414
+
415
+ def read_process_vram() -> dict[int, int] | None:
416
+ """Per-PID VRAM bytes summed across NVIDIA GPUs via NVML; None when NVML is unavailable."""
417
+ devices = _SESSION.read_all(include_processes=True)
418
+ if devices is None:
419
+ return None
420
+ used: dict[int, int] = {}
421
+ for dev in devices:
422
+ for proc in dev["processes"]:
423
+ mem = proc["used_bytes"]
424
+ if mem is not None and mem > 0:
425
+ used[proc["pid"]] = used.get(proc["pid"], 0) + mem
426
+ return used
427
+
428
+
429
+ def reset_session() -> None:
430
+ """Reset the cached NVML session (for unit tests and driver reload recovery)."""
431
+ _SESSION.reset()
@@ -364,14 +364,20 @@ def cpu_threads(facts: HostFacts) -> int:
364
364
 
365
365
 
366
366
  def verified_in_place(f: ReusableFile) -> bool:
367
- """An existing destination with the download action's matching SHA256 receipt."""
367
+ """An existing destination with the download action's matching SHA256 receipt (or exact size
368
+ plus GGUF magic header when the hub published no SHA256)."""
368
369
  path = Path(f["dest"]).expanduser()
369
370
  try:
370
- return (
371
- path.is_file()
372
- and path.stat().st_size == f["size_bytes"]
373
- and Path(str(path) + ".sha256").read_text().strip() == f["sha256"]
374
- )
371
+ if not path.is_file() or path.stat().st_size != f["size_bytes"]:
372
+ return False
373
+ if not f["sha256"]:
374
+ if f["size_bytes"] <= 0:
375
+ return False
376
+ if path.name.lower().endswith(".gguf"):
377
+ with path.open("rb") as handle:
378
+ return handle.read(4) == b"GGUF"
379
+ return True
380
+ return Path(str(path) + ".sha256").read_text().strip() == f["sha256"]
375
381
  except (OSError, UnicodeError):
376
382
  return False
377
383
 
@@ -450,6 +456,8 @@ def plan_envelope(
450
456
  for key in ("limits", "slice", "slice_limits", "config_files"):
451
457
  if key in service:
452
458
  svc[key] = service[key]
459
+ if "autostart" in service:
460
+ svc["autostart"] = service["autostart"]
453
461
  return {
454
462
  "schema": PLAN_SCHEMA,
455
463
  "name": where.name,
@@ -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
  )
@@ -109,6 +109,7 @@ class Launch(RequiredLaunch, total=False):
109
109
  slice: str # the suite slice that bounds every component together
110
110
  slice_limits: dict[str, str]
111
111
  config_files: dict[str, str] # {path: content} written beside the launch script
112
+ autostart: bool # False skips systemd enable on boot (standby_on_restart custom models)
112
113
 
113
114
 
114
115
  class RequiredService(TypedDict):