llmctl-cli 0.4.1__py3-none-any.whl

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.
llmctl/doctor.py ADDED
@@ -0,0 +1,204 @@
1
+ """Cross-platform environment diagnostics (`llmctl doctor`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ import shutil
7
+ import subprocess
8
+ from dataclasses import asdict, dataclass
9
+
10
+ from llmctl.config import AppConfig
11
+ from llmctl.hardware import detect_hardware
12
+ from llmctl.presets import list_presets
13
+ from llmctl.service import select_backend
14
+ from llmctl.service.base import is_in_container
15
+ from llmctl.ui import Console
16
+
17
+
18
+ @dataclass
19
+ class CheckResult:
20
+ """Single diagnostic check outcome."""
21
+
22
+ name: str
23
+ status: str # "ok" | "warn" | "info" | "error"
24
+ message: str
25
+
26
+ def to_dict(self) -> dict[str, str]:
27
+ return asdict(self)
28
+
29
+
30
+ def _is_ollama_running(sys_platform: str) -> bool:
31
+ if sys_platform == "win32":
32
+ if not shutil.which("tasklist"):
33
+ return False
34
+ proc = subprocess.run(
35
+ ["tasklist", "/FI", "IMAGENAME eq ollama.exe"],
36
+ capture_output=True,
37
+ text=True,
38
+ check=False,
39
+ )
40
+ return "ollama.exe" in proc.stdout.lower()
41
+
42
+ if shutil.which("pgrep"):
43
+ proc = subprocess.run(["pgrep", "-x", "ollama"], capture_output=True, check=False)
44
+ if proc.returncode == 0:
45
+ return True
46
+ if sys_platform.startswith("linux") and shutil.which("systemctl"):
47
+ for args in (
48
+ ["is-active", "--quiet", "ollama"],
49
+ ["--user", "is-active", "--quiet", "ollama"],
50
+ ):
51
+ if (
52
+ subprocess.run(["systemctl", *args], capture_output=True, check=False).returncode
53
+ == 0
54
+ ):
55
+ return True
56
+ return False
57
+
58
+
59
+ def collect_diagnostics(config: AppConfig) -> list[CheckResult]:
60
+ """Run all cross-platform environment checks and return structured results."""
61
+ checks: list[CheckResult] = []
62
+ in_container = is_in_container()
63
+ env_label = "Contenedor" if in_container else "Host local"
64
+ py_ver = platform.python_version()
65
+ checks.append(
66
+ CheckResult(
67
+ name="environment",
68
+ status="info",
69
+ message=f"{env_label} | {platform.system()} {platform.machine()} | Python {py_ver}",
70
+ )
71
+ )
72
+
73
+ checks.append(CheckResult("python", "ok", f"Python {py_ver} compatible (>= 3.11)"))
74
+
75
+ if config.is_remote:
76
+ checks.append(
77
+ CheckResult(
78
+ "server_binary",
79
+ "info",
80
+ f"Modo remoto ({config.api_root}); binario local no requerido",
81
+ )
82
+ )
83
+ elif config.server_binary:
84
+ checks.append(CheckResult("server_binary", "ok", f"llama-server en {config.server_binary}"))
85
+ else:
86
+ checks.append(
87
+ CheckResult(
88
+ "server_binary",
89
+ "warn",
90
+ "llama-server no encontrado en PATH (configura LLMCTL_SERVER_BIN o config.toml)",
91
+ )
92
+ )
93
+
94
+ if config.models_ini.is_file():
95
+ presets = list_presets(config.models_ini)
96
+ checks.append(
97
+ CheckResult(
98
+ "models_ini",
99
+ "ok",
100
+ f"{config.models_ini} ({len(presets)} preset(s) configurados)",
101
+ )
102
+ )
103
+ else:
104
+ checks.append(
105
+ CheckResult(
106
+ "models_ini",
107
+ "warn",
108
+ f"No existe {config.models_ini} (se creará automáticamente al añadir un modelo)",
109
+ )
110
+ )
111
+
112
+ if config.hf_token:
113
+ checks.append(CheckResult("hf_token", "ok", "Token de Hugging Face configurado"))
114
+ else:
115
+ checks.append(
116
+ CheckResult(
117
+ "hf_token",
118
+ "warn",
119
+ "HF_TOKEN / token local no detectado (solo requerido para repos privados)",
120
+ )
121
+ )
122
+
123
+ checks.append(
124
+ CheckResult(
125
+ "profile",
126
+ "info",
127
+ f"Perfil activo: {config.profile or 'default'} | API: {config.api_root}"
128
+ + (" (con API key)" if config.api_key else ""),
129
+ )
130
+ )
131
+
132
+ hw = detect_hardware(sys_platform=config.sys_platform)
133
+ if hw.gpus:
134
+ gpu_desc = ", ".join(f"{g.name} ({g.vram_total_gb:.1f} GiB)" for g in hw.gpus)
135
+ checks.append(CheckResult("gpu", "ok", f"Acelerador detectado: {gpu_desc}"))
136
+ else:
137
+ checks.append(
138
+ CheckResult(
139
+ "gpu",
140
+ "warn",
141
+ f"Sin GPU dedicada/Metal/Vulkan detectada (modo CPU/RAM, "
142
+ f"{hw.cpu_cores_physical} núcleos físicos)",
143
+ )
144
+ )
145
+ checks.append(
146
+ CheckResult(
147
+ "ram",
148
+ "ok" if hw.ram_total_gb > 0 else "warn",
149
+ f"RAM total: {hw.ram_total_gb:.1f} GiB (útil ~{hw.ram_usable_gb:.1f} GiB) | "
150
+ f"CPU: {hw.cpu_cores_physical}C/{hw.cpu_cores_logical}T",
151
+ )
152
+ )
153
+
154
+ backend = select_backend(config)
155
+ svc_status = backend.status()
156
+ checks.append(
157
+ CheckResult(
158
+ "service_backend",
159
+ "ok" if (svc_status.running or svc_status.api_reachable) else "warn",
160
+ f"Backend '{backend.name}': {svc_status.detail}",
161
+ )
162
+ )
163
+
164
+ if not in_container and not config.is_remote:
165
+ if _is_ollama_running(config.sys_platform):
166
+ checks.append(
167
+ CheckResult(
168
+ "ollama",
169
+ "warn",
170
+ "Ollama está en ejecución en segundo plano (puede competir por RAM/VRAM).",
171
+ )
172
+ )
173
+ else:
174
+ checks.append(CheckResult("ollama", "ok", "Ollama no está corriendo en segundo plano"))
175
+
176
+ return checks
177
+
178
+
179
+ def run_doctor(config: AppConfig, console: Console) -> int:
180
+ """Execute diagnostics and print results in human or JSON format."""
181
+ checks = collect_diagnostics(config)
182
+ has_errors = any(c.status == "error" for c in checks)
183
+
184
+ if console.json_mode:
185
+ console.emit_json(
186
+ {
187
+ "ok": not has_errors,
188
+ "checks": [c.to_dict() for c in checks],
189
+ "config": config.to_dict(),
190
+ }
191
+ )
192
+ return 1 if has_errors else 0
193
+
194
+ console.header("llmctl doctor")
195
+ for check in checks:
196
+ if check.status == "ok":
197
+ console.ok(check.message)
198
+ elif check.status == "warn":
199
+ console.warn(check.message)
200
+ elif check.status == "error":
201
+ console.error(check.message)
202
+ else:
203
+ console.info(check.message)
204
+ return 1 if has_errors else 0
llmctl/hardware.py ADDED
@@ -0,0 +1,506 @@
1
+ """Cross-platform RAM and GPU/VRAM hardware probing (Linux, macOS, Windows)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import platform
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ from dataclasses import asdict, dataclass, field
13
+ from pathlib import Path
14
+
15
+ GIB = 1024**3
16
+ MIB_PER_GIB = 1024.0
17
+
18
+
19
+ @dataclass
20
+ class GpuInfo:
21
+ """Single detected GPU / accelerator device."""
22
+
23
+ vendor: str
24
+ name: str
25
+ vram_total_gb: float
26
+ vram_used_gb: float | None = None
27
+ utilization_pct: float | None = None
28
+ unified_memory: bool = False
29
+
30
+ def to_dict(self) -> dict[str, object]:
31
+ return asdict(self)
32
+
33
+
34
+ @dataclass
35
+ class HardwareInfo:
36
+ """Summary of host RAM and GPU capacity for model sizing."""
37
+
38
+ os_name: str
39
+ arch: str
40
+ ram_total_gb: float
41
+ ram_available_gb: float | None
42
+ ram_usable_gb: float
43
+ vram_total_gb: float
44
+ vram_used_gb: float | None
45
+ vram_safe_gb: float
46
+ unified_memory: bool = False
47
+ cpu_cores_physical: int = 1
48
+ cpu_cores_logical: int = 1
49
+ gpus: list[GpuInfo] = field(default_factory=list)
50
+
51
+ def to_dict(self) -> dict[str, object]:
52
+ data = asdict(self)
53
+ data["gpus"] = [gpu.to_dict() for gpu in self.gpus]
54
+ return data
55
+
56
+
57
+ def _run_text(cmd: list[str], *, timeout: float = 5.0) -> str | None:
58
+ try:
59
+ proc = subprocess.run(
60
+ cmd,
61
+ capture_output=True,
62
+ text=True,
63
+ timeout=timeout,
64
+ check=False,
65
+ )
66
+ except (OSError, subprocess.SubprocessError):
67
+ return None
68
+ if proc.returncode != 0:
69
+ return None
70
+ return proc.stdout.strip()
71
+
72
+
73
+ def _parse_float(raw: str) -> float | None:
74
+ cleaned = raw.strip().rstrip("%").strip()
75
+ if not cleaned or cleaned.upper() in {"N/A", "[N/A]", "NONE", "UNKNOWN"}:
76
+ return None
77
+ try:
78
+ return float(cleaned)
79
+ except ValueError:
80
+ return None
81
+
82
+
83
+ def _detect_ram_linux(meminfo_path: Path = Path("/proc/meminfo")) -> tuple[float, float | None]:
84
+ total_kb: int | None = None
85
+ avail_kb: int | None = None
86
+ free_kb: int | None = None
87
+ try:
88
+ text = meminfo_path.read_text(encoding="utf-8", errors="replace")
89
+ except OSError:
90
+ return 0.0, None
91
+
92
+ for line in text.splitlines():
93
+ parts = line.split()
94
+ if len(parts) < 2:
95
+ continue
96
+ key, value = parts[0], parts[1]
97
+ if not value.isdigit():
98
+ continue
99
+ if key == "MemTotal:":
100
+ total_kb = int(value)
101
+ elif key == "MemAvailable:":
102
+ avail_kb = int(value)
103
+ elif key == "MemFree:":
104
+ free_kb = int(value)
105
+
106
+ total_gb = (total_kb / (1024 * 1024)) if total_kb is not None else 0.0
107
+ avail_val = avail_kb if avail_kb is not None else free_kb
108
+ avail_gb = (avail_val / (1024 * 1024)) if avail_val is not None else None
109
+ return total_gb, avail_gb
110
+
111
+
112
+ def _detect_ram_macos() -> tuple[float, float | None]:
113
+ memsize_out = _run_text(["sysctl", "-n", "hw.memsize"])
114
+ if not memsize_out or not memsize_out.isdigit():
115
+ return 0.0, None
116
+ total_gb = int(memsize_out) / GIB
117
+
118
+ vm_out = _run_text(["vm_stat"])
119
+ if not vm_out:
120
+ return total_gb, None
121
+
122
+ page_size = 4096
123
+ m_page = re.search(r"page size of (\d+) bytes", vm_out)
124
+ if m_page:
125
+ page_size = int(m_page.group(1))
126
+
127
+ free_pages = 0
128
+ for key in ("Pages free", "Pages inactive", "Pages speculative"):
129
+ match = re.search(rf"^{re.escape(key)}:\s+(\d+)\.", vm_out, re.MULTILINE)
130
+ if match:
131
+ free_pages += int(match.group(1))
132
+ avail_gb = (free_pages * page_size) / GIB if free_pages > 0 else None
133
+ return total_gb, avail_gb
134
+
135
+
136
+ def _detect_ram_windows() -> tuple[float, float | None]:
137
+ try:
138
+ import ctypes
139
+
140
+ class MemoryStatusEx(ctypes.Structure):
141
+ _fields_ = [
142
+ ("dwLength", ctypes.c_ulong),
143
+ ("dwMemoryLoad", ctypes.c_ulong),
144
+ ("ullTotalPhys", ctypes.c_ulonglong),
145
+ ("ullAvailPhys", ctypes.c_ulonglong),
146
+ ("ullTotalPageFile", ctypes.c_ulonglong),
147
+ ("ullAvailPageFile", ctypes.c_ulonglong),
148
+ ("ullTotalVirtual", ctypes.c_ulonglong),
149
+ ("ullAvailVirtual", ctypes.c_ulonglong),
150
+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
151
+ ]
152
+
153
+ status = MemoryStatusEx()
154
+ status.dwLength = ctypes.sizeof(MemoryStatusEx)
155
+ windll = getattr(ctypes, "windll", None)
156
+ if windll is None:
157
+ return 0.0, None
158
+ if not windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
159
+ return 0.0, None
160
+ return status.ullTotalPhys / GIB, status.ullAvailPhys / GIB
161
+ except Exception:
162
+ return 0.0, None
163
+
164
+
165
+ def detect_ram(*, sys_platform: str | None = None) -> tuple[float, float | None]:
166
+ """Return (total_ram_gb, available_ram_gb) portably across Linux, macOS, and Windows."""
167
+ plat = sys.platform if sys_platform is None else sys_platform
168
+ if plat == "darwin":
169
+ return _detect_ram_macos()
170
+ if plat == "win32":
171
+ return _detect_ram_windows()
172
+ return _detect_ram_linux()
173
+
174
+
175
+ def _detect_nvidia_gpus() -> list[GpuInfo]:
176
+ if not shutil.which("nvidia-smi"):
177
+ return []
178
+ out = _run_text(
179
+ [
180
+ "nvidia-smi",
181
+ "--query-gpu=name,memory.used,memory.total,utilization.gpu",
182
+ "--format=csv,noheader,nounits",
183
+ ]
184
+ )
185
+ if not out:
186
+ return []
187
+
188
+ gpus: list[GpuInfo] = []
189
+ for line in out.splitlines():
190
+ cols = [c.strip() for c in line.split(",")]
191
+ if len(cols) < 3:
192
+ continue
193
+ name = cols[0]
194
+ used_mib = _parse_float(cols[1])
195
+ total_mib = _parse_float(cols[2])
196
+ util_pct = _parse_float(cols[3]) if len(cols) >= 4 else None
197
+ if total_mib is None or total_mib <= 0:
198
+ continue
199
+ gpus.append(
200
+ GpuInfo(
201
+ vendor="nvidia",
202
+ name=name,
203
+ vram_total_gb=total_mib / MIB_PER_GIB,
204
+ vram_used_gb=(used_mib / MIB_PER_GIB) if used_mib is not None else None,
205
+ utilization_pct=util_pct,
206
+ unified_memory=False,
207
+ )
208
+ )
209
+ return gpus
210
+
211
+
212
+ def _detect_amd_gpus() -> list[GpuInfo]:
213
+ if shutil.which("amd-smi"):
214
+ out = _run_text(["amd-smi", "static", "--asic", "--vram", "--json"])
215
+ if out:
216
+ try:
217
+ data = json.loads(out)
218
+ items = data if isinstance(data, list) else data.get("gpu_data", [])
219
+ gpus: list[GpuInfo] = []
220
+ for idx, entry in enumerate(items):
221
+ if not isinstance(entry, dict):
222
+ continue
223
+ asic = entry.get("asic", {})
224
+ vram = entry.get("vram", {})
225
+ name = str(asic.get("market_name") or f"AMD GPU #{idx}")
226
+ size_obj = vram.get("size", {})
227
+ total_mib = _parse_float(
228
+ str(size_obj.get("value") if isinstance(size_obj, dict) else size_obj)
229
+ )
230
+ if total_mib and total_mib > 0:
231
+ gpus.append(
232
+ GpuInfo(
233
+ vendor="amd",
234
+ name=name,
235
+ vram_total_gb=total_mib / MIB_PER_GIB,
236
+ )
237
+ )
238
+ if gpus:
239
+ return gpus
240
+ except (json.JSONDecodeError, TypeError, AttributeError):
241
+ pass
242
+
243
+ if shutil.which("rocm-smi"):
244
+ out = _run_text(["rocm-smi", "--showmeminfo", "vram", "--showproductname", "--json"])
245
+ if out:
246
+ try:
247
+ data = json.loads(out)
248
+ gpus = []
249
+ if isinstance(data, dict):
250
+ for key, info in data.items():
251
+ if not isinstance(info, dict):
252
+ continue
253
+ total_b = _parse_float(str(info.get("VRAM Total Memory (B)", "")))
254
+ used_b = _parse_float(str(info.get("VRAM Total Used Memory (B)", "")))
255
+ name = str(info.get("Card Series") or info.get("Card Model") or key)
256
+ if total_b and total_b > 0:
257
+ gpus.append(
258
+ GpuInfo(
259
+ vendor="amd",
260
+ name=name,
261
+ vram_total_gb=total_b / GIB,
262
+ vram_used_gb=(used_b / GIB) if used_b is not None else None,
263
+ )
264
+ )
265
+ if gpus:
266
+ return gpus
267
+ except (json.JSONDecodeError, TypeError):
268
+ pass
269
+
270
+ return []
271
+
272
+
273
+ def _detect_apple_silicon(ram_total_gb: float, *, arch: str) -> list[GpuInfo]:
274
+ if arch.lower() not in {"arm64", "aarch64"}:
275
+ return []
276
+ brand = _run_text(["sysctl", "-n", "machdep.cpu.brand_string"]) or "Apple Silicon"
277
+ wired_mib_raw = _run_text(["sysctl", "-n", "iogpu.wired_limit_mb"])
278
+ wired_mib = _parse_float(wired_mib_raw) if wired_mib_raw else None
279
+ if wired_mib and wired_mib > 0:
280
+ gpu_budget_gb = wired_mib / MIB_PER_GIB
281
+ else:
282
+ # macOS allows Metal to wire ~75% of unified memory by default
283
+ gpu_budget_gb = round(ram_total_gb * 0.75, 2)
284
+
285
+ return [
286
+ GpuInfo(
287
+ vendor="apple",
288
+ name=f"{brand} (Metal Unified)",
289
+ vram_total_gb=gpu_budget_gb,
290
+ vram_used_gb=None,
291
+ utilization_pct=None,
292
+ unified_memory=True,
293
+ )
294
+ ]
295
+
296
+
297
+ def detect_cpu_cores(*, sys_platform: str | None = None) -> tuple[int, int]:
298
+ """Return (physical_cores, logical_cores) portably across Linux, macOS, and Windows."""
299
+ plat = sys.platform if sys_platform is None else sys_platform
300
+ logical = max(1, os.cpu_count() or 1)
301
+
302
+ if plat == "darwin":
303
+ phys_out = _run_text(["sysctl", "-n", "hw.physicalcpu"])
304
+ if phys_out and phys_out.isdigit() and int(phys_out) > 0:
305
+ return int(phys_out), logical
306
+ return logical, logical
307
+
308
+ if plat.startswith("linux"):
309
+ cpuinfo = Path("/proc/cpuinfo")
310
+ if cpuinfo.is_file():
311
+ try:
312
+ text = cpuinfo.read_text(encoding="utf-8", errors="ignore")
313
+ pairs: set[tuple[str, str]] = set()
314
+ phys_id = "0"
315
+ for line in text.splitlines():
316
+ if line.startswith("physical id"):
317
+ phys_id = line.split(":", 1)[1].strip()
318
+ elif line.startswith("core id"):
319
+ pairs.add((phys_id, line.split(":", 1)[1].strip()))
320
+ if pairs:
321
+ return len(pairs), logical
322
+ except OSError:
323
+ pass
324
+
325
+ return max(1, logical // 2) if logical >= 4 else logical, logical
326
+
327
+
328
+ def recommended_cpu_threads(hw: HardwareInfo) -> int:
329
+ """Return recommended llama-server --threads count for CPU inference."""
330
+ return max(1, min(hw.cpu_cores_physical, hw.cpu_cores_logical))
331
+
332
+
333
+ def recommended_cpu_ctx_size(hw: HardwareInfo) -> int:
334
+ """Return a conservative context size for CPU-only execution."""
335
+ return 4096 if hw.ram_total_gb <= 16.0 else 8192
336
+
337
+
338
+ def _detect_vulkan_gpus(ram_total_gb: float) -> tuple[list[GpuInfo], bool]:
339
+ """Detect discrete or integrated GPUs exposed via Vulkan (Intel Arc/Iris, AMD iGPU)."""
340
+ if not shutil.which("vulkaninfo"):
341
+ return [], False
342
+ out = _run_text(["vulkaninfo", "--summary"])
343
+ if not out:
344
+ return [], False
345
+
346
+ devices: list[tuple[str, str]] = []
347
+ cur_type = ""
348
+ cur_name = ""
349
+ for line in out.splitlines():
350
+ stripped = line.strip()
351
+ if stripped.startswith("deviceType"):
352
+ cur_type = stripped.split("=", 1)[1].strip()
353
+ elif stripped.startswith("deviceName"):
354
+ cur_name = stripped.split("=", 1)[1].strip()
355
+ if cur_name and cur_type:
356
+ devices.append((cur_type, cur_name))
357
+ cur_type, cur_name = "", ""
358
+
359
+ gpus: list[GpuInfo] = []
360
+ any_integrated = False
361
+ for dev_type, dev_name in devices:
362
+ lower = dev_name.lower()
363
+ if "CPU" in dev_type or any(sw in lower for sw in ("llvmpipe", "lavapipe", "swiftshader")):
364
+ continue
365
+ is_integrated = "INTEGRATED" in dev_type
366
+ if is_integrated:
367
+ any_integrated = True
368
+ budget_gb = round(max(1.0, ram_total_gb * 0.5), 2) if is_integrated else 0.0
369
+ gpus.append(
370
+ GpuInfo(
371
+ vendor="vulkan",
372
+ name=f"{dev_name} ({'Vulkan iGPU' if is_integrated else 'Vulkan'})",
373
+ vram_total_gb=budget_gb,
374
+ vram_used_gb=None,
375
+ utilization_pct=None,
376
+ unified_memory=is_integrated,
377
+ )
378
+ )
379
+ return gpus, any_integrated and all(g.unified_memory for g in gpus)
380
+
381
+
382
+ def _detect_windows_cim_gpus(ram_total_gb: float) -> tuple[list[GpuInfo], bool]:
383
+ """Best-effort Windows GPU/iGPU probe via PowerShell CIM when nvidia-smi/vulkaninfo absent."""
384
+ if not shutil.which("powershell"):
385
+ return [], False
386
+ out = _run_text(
387
+ [
388
+ "powershell",
389
+ "-NoProfile",
390
+ "-Command",
391
+ (
392
+ "Get-CimInstance Win32_VideoController | "
393
+ "Select-Object Name,AdapterRAM | ConvertTo-Json"
394
+ ),
395
+ ],
396
+ timeout=6.0,
397
+ )
398
+ if not out:
399
+ return [], False
400
+ try:
401
+ parsed = json.loads(out)
402
+ except json.JSONDecodeError:
403
+ return [], False
404
+ items = parsed if isinstance(parsed, list) else [parsed]
405
+ gpus: list[GpuInfo] = []
406
+ for item in items:
407
+ if not isinstance(item, dict):
408
+ continue
409
+ name = str(item.get("Name") or "").strip()
410
+ if not name or "microsoft basic" in name.lower():
411
+ continue
412
+ adapter_ram = _parse_float(str(item.get("AdapterRAM") or ""))
413
+ is_igpu = any(k in name.lower() for k in ("intel", "uhd", "iris", "radeon(tm) graphics"))
414
+ vram_gb = (
415
+ round(max(1.0, ram_total_gb * 0.5), 2)
416
+ if is_igpu
417
+ else round((adapter_ram or 0.0) / GIB, 2)
418
+ )
419
+ gpus.append(
420
+ GpuInfo(
421
+ vendor="igpu" if is_igpu else "gpu",
422
+ name=name,
423
+ vram_total_gb=vram_gb,
424
+ unified_memory=is_igpu,
425
+ )
426
+ )
427
+ return gpus, bool(gpus) and all(g.unified_memory for g in gpus)
428
+
429
+
430
+ def detect_gpus(
431
+ *,
432
+ sys_platform: str | None = None,
433
+ arch: str | None = None,
434
+ ram_total_gb: float = 0.0,
435
+ ) -> tuple[list[GpuInfo], bool]:
436
+ """Detect available GPUs (Metal, NVIDIA, AMD, Vulkan/iGPU) and return (gpus, unified_memory)."""
437
+ plat = sys.platform if sys_platform is None else sys_platform
438
+ machine = platform.machine() if arch is None else arch
439
+
440
+ if plat == "darwin":
441
+ apple_gpus = _detect_apple_silicon(ram_total_gb, arch=machine)
442
+ if apple_gpus:
443
+ return apple_gpus, True
444
+
445
+ nvidia = _detect_nvidia_gpus()
446
+ if nvidia:
447
+ return nvidia, False
448
+
449
+ amd = _detect_amd_gpus()
450
+ if amd:
451
+ return amd, False
452
+
453
+ vulkan_gpus, vulkan_unified = _detect_vulkan_gpus(ram_total_gb)
454
+ if vulkan_gpus:
455
+ return vulkan_gpus, vulkan_unified
456
+
457
+ if plat == "win32":
458
+ win_gpus, win_unified = _detect_windows_cim_gpus(ram_total_gb)
459
+ if win_gpus:
460
+ return win_gpus, win_unified
461
+
462
+ return [], False
463
+
464
+
465
+ def detect_hardware(
466
+ *,
467
+ sys_platform: str | None = None,
468
+ arch: str | None = None,
469
+ ) -> HardwareInfo:
470
+ """Probe host RAM, CPU cores, and GPU capacity and compute safe sizing budgets."""
471
+ plat = sys.platform if sys_platform is None else sys_platform
472
+ machine = platform.machine() if arch is None else arch
473
+ ram_total_gb, ram_avail_gb = detect_ram(sys_platform=plat)
474
+ phys_cores, log_cores = detect_cpu_cores(sys_platform=plat)
475
+ gpus, unified = detect_gpus(sys_platform=plat, arch=machine, ram_total_gb=ram_total_gb)
476
+
477
+ if gpus:
478
+ vram_total_gb = sum(g.vram_total_gb for g in gpus)
479
+ used_vals = [g.vram_used_gb for g in gpus if g.vram_used_gb is not None]
480
+ vram_used_gb = sum(used_vals) if len(used_vals) == len(gpus) else None
481
+ else:
482
+ vram_total_gb = 0.0
483
+ vram_used_gb = None
484
+
485
+ if unified:
486
+ vram_safe_gb = max(0.0, vram_total_gb - 1.0)
487
+ ram_usable_gb = vram_safe_gb
488
+ else:
489
+ vram_safe_gb = max(0.0, vram_total_gb - 1.5) if vram_total_gb > 0 else 0.0
490
+ ram_reserve = 4.0 if ram_total_gb <= 16.0 else 5.0
491
+ ram_usable_gb = max(0.0, ram_total_gb - ram_reserve)
492
+
493
+ return HardwareInfo(
494
+ os_name=plat,
495
+ arch=machine,
496
+ ram_total_gb=round(ram_total_gb, 2),
497
+ ram_available_gb=round(ram_avail_gb, 2) if ram_avail_gb is not None else None,
498
+ ram_usable_gb=round(ram_usable_gb, 2),
499
+ vram_total_gb=round(vram_total_gb, 2),
500
+ vram_used_gb=round(vram_used_gb, 2) if vram_used_gb is not None else None,
501
+ vram_safe_gb=round(vram_safe_gb, 2),
502
+ unified_memory=unified,
503
+ cpu_cores_physical=phys_cores,
504
+ cpu_cores_logical=log_cores,
505
+ gpus=gpus,
506
+ )