hardware_check.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. #!/usr/bin/env python3
  2. """hardware_check.py — Detect whether this machine can realistically run ComfyUI locally.
  3. Improvements over v1:
  4. - Multi-GPU detection: scans all NVIDIA / AMD GPUs, picks the best one (most VRAM)
  5. - Apple Silicon: detects Rosetta-via-x86_64 false negative; warns instead of misclassifying
  6. - Apple generation: defaults to None (unknown) instead of mis-tagging as M1
  7. - WSL2 detection: identifies WSL2 + nvidia-smi situation explicitly
  8. - ROCm: prefers `rocm-smi --json` for new ROCm 6.x output
  9. - Disk space check: warns if /home or workspace volume has < 25 GB free
  10. - PyTorch verification (optional): tries to import torch and check device availability
  11. - Windows: prefers PowerShell `Get-CimInstance` over deprecated `wmic`
  12. - More accurate VRAM thresholds and verdict reasons
  13. Emits a structured JSON report. Exit codes match `verdict`:
  14. 0 → ok
  15. 1 → marginal
  16. 2 → cloud
  17. Usage:
  18. python3 hardware_check.py [--json] [--check-pytorch]
  19. """
  20. from __future__ import annotations
  21. import json
  22. import os
  23. import platform
  24. import re
  25. import shutil
  26. import subprocess
  27. import sys
  28. from typing import Any
  29. # Thresholds (GiB).
  30. MIN_VRAM_GB_USABLE = 6
  31. OK_VRAM_GB = 8
  32. GREAT_VRAM_GB = 12
  33. MIN_MAC_RAM_GB = 16
  34. OK_MAC_RAM_GB = 32
  35. MIN_FREE_DISK_GB = 25 # ComfyUI core ~5 GB + one model ~5–24 GB
  36. _COMFY_CLI_FLAG = {
  37. "nvidia": "--nvidia",
  38. "amd": "--amd",
  39. "apple-silicon": "--m-series",
  40. "intel": None,
  41. "comfy-cloud": None,
  42. "cpu": "--cpu",
  43. }
  44. def _run(cmd: list[str], timeout: int = 8) -> str:
  45. try:
  46. out = subprocess.run(
  47. cmd, stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout, check=False
  48. )
  49. return (out.stdout or "") + (out.stderr or "")
  50. except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
  51. return ""
  52. def is_wsl() -> bool:
  53. """Return True when running under Windows Subsystem for Linux."""
  54. if platform.system() != "Linux":
  55. return False
  56. if "microsoft" in platform.release().lower() or "wsl" in platform.release().lower():
  57. return True
  58. try:
  59. with open("/proc/version", "r", encoding="utf-8") as fh:
  60. return "microsoft" in fh.read().lower()
  61. except OSError:
  62. return False
  63. def is_rosetta() -> bool:
  64. """Return True when Python is running translated under Rosetta on Apple Silicon."""
  65. if platform.system() != "Darwin":
  66. return False
  67. if platform.machine() == "arm64":
  68. return False
  69. # x86_64 on Darwin — could be Intel Mac or Rosetta. Probe sysctl.
  70. out = _run(["sysctl", "-in", "sysctl.proc_translated"]).strip()
  71. return out == "1"
  72. def detect_nvidia() -> dict | None:
  73. """Detect NVIDIA GPUs. Returns the GPU with the most VRAM, plus list of all."""
  74. if not shutil.which("nvidia-smi"):
  75. return None
  76. out = _run([
  77. "nvidia-smi",
  78. "--query-gpu=index,name,memory.total,driver_version",
  79. "--format=csv,noheader,nounits",
  80. ])
  81. if not out.strip():
  82. return None
  83. gpus = []
  84. for line in out.strip().splitlines():
  85. parts = [p.strip() for p in line.split(",")]
  86. if len(parts) < 3:
  87. continue
  88. try:
  89. idx = int(parts[0])
  90. name = parts[1]
  91. vram_mb = int(parts[2])
  92. except ValueError:
  93. continue
  94. driver = parts[3] if len(parts) > 3 else ""
  95. gpus.append({
  96. "vendor": "nvidia",
  97. "index": idx,
  98. "name": name,
  99. "vram_gb": round(vram_mb / 1024, 1),
  100. "driver": driver,
  101. })
  102. if not gpus:
  103. return None
  104. # Pick GPU with most VRAM
  105. best = max(gpus, key=lambda g: g["vram_gb"])
  106. if len(gpus) > 1:
  107. best["all_gpus"] = gpus
  108. return best
  109. def detect_rocm() -> dict | None:
  110. if not shutil.which("rocm-smi"):
  111. return None
  112. # Prefer JSON output (new ROCm 6.x)
  113. out = _run(["rocm-smi", "--showproductname", "--showmeminfo", "vram", "--json"])
  114. if out.strip().startswith("{"):
  115. try:
  116. data = json.loads(out)
  117. cards = []
  118. for card_id, info in data.items():
  119. if not card_id.startswith("card"):
  120. continue
  121. name = (info.get("Card series") or info.get("Card model")
  122. or info.get("Marketing Name") or "AMD GPU")
  123. vram_b = info.get("VRAM Total Memory (B)") or info.get("vram_total_memory_b") or 0
  124. try:
  125. vram_b = int(vram_b)
  126. except (ValueError, TypeError):
  127. vram_b = 0
  128. cards.append({
  129. "vendor": "amd",
  130. "name": str(name).strip(),
  131. "vram_gb": round(vram_b / (1024**3), 1),
  132. "driver": "rocm",
  133. })
  134. if cards:
  135. best = max(cards, key=lambda c: c["vram_gb"])
  136. if len(cards) > 1:
  137. best["all_gpus"] = cards
  138. return best
  139. except json.JSONDecodeError:
  140. pass
  141. # Fall back to text parsing
  142. out = _run(["rocm-smi", "--showproductname", "--showmeminfo", "vram"])
  143. if not out.strip():
  144. return None
  145. name_m = re.search(r"Card (?:series|model|Marketing Name):\s*(.+)", out)
  146. vram_m = re.search(r"VRAM Total Memory \(B\):\s*(\d+)", out)
  147. vram_gb = round(int(vram_m.group(1)) / (1024**3), 1) if vram_m else 0.0
  148. return {
  149. "vendor": "amd",
  150. "name": name_m.group(1).strip() if name_m else "AMD GPU",
  151. "vram_gb": vram_gb,
  152. "driver": "rocm",
  153. }
  154. def detect_apple_silicon() -> dict | None:
  155. if platform.system() != "Darwin":
  156. return None
  157. if platform.machine() != "arm64":
  158. return None
  159. chip = _run(["sysctl", "-n", "machdep.cpu.brand_string"]).strip()
  160. m = re.search(r"Apple M(\d+)", chip)
  161. generation = int(m.group(1)) if m else None
  162. mem_bytes = 0
  163. try:
  164. mem_bytes = int(_run(["sysctl", "-n", "hw.memsize"]).strip() or 0)
  165. except ValueError:
  166. pass
  167. ram_gb = round(mem_bytes / (1024**3), 1) if mem_bytes else 0.0
  168. # Detect chip variant ("Pro", "Max", "Ultra") — affects performance even at same gen
  169. variant = None
  170. for v in ("Ultra", "Max", "Pro"):
  171. if v in chip:
  172. variant = v
  173. break
  174. return {
  175. "vendor": "apple",
  176. "name": chip or "Apple Silicon",
  177. "generation": generation,
  178. "variant": variant,
  179. "unified_memory_gb": ram_gb,
  180. }
  181. def detect_intel_arc() -> dict | None:
  182. if platform.system() not in {"Linux", "Windows"}:
  183. return None
  184. if shutil.which("clinfo"):
  185. out = _run(["clinfo", "--list"])
  186. if "Intel" in out and ("Arc" in out or "Xe" in out):
  187. return {"vendor": "intel", "name": "Intel Arc/Xe", "vram_gb": 0.0}
  188. # Windows: try Get-CimInstance
  189. if platform.system() == "Windows" and shutil.which("powershell"):
  190. out = _run(["powershell", "-NoProfile",
  191. "Get-CimInstance Win32_VideoController | Select-Object Name | Format-List"])
  192. if "Intel" in out and ("Arc" in out or "Iris Xe" in out):
  193. return {"vendor": "intel", "name": "Intel Arc/Iris Xe", "vram_gb": 0.0}
  194. return None
  195. def total_system_ram_gb() -> float:
  196. sysname = platform.system()
  197. if sysname == "Darwin":
  198. try:
  199. return round(int(_run(["sysctl", "-n", "hw.memsize"]).strip() or 0) / (1024**3), 1)
  200. except ValueError:
  201. return 0.0
  202. if sysname == "Linux":
  203. try:
  204. with open("/proc/meminfo", "r", encoding="utf-8") as fh:
  205. for line in fh:
  206. if line.startswith("MemTotal:"):
  207. kb = int(line.split()[1])
  208. return round(kb / (1024**2), 1)
  209. except OSError:
  210. return 0.0
  211. if sysname == "Windows":
  212. if shutil.which("powershell"):
  213. out = _run([
  214. "powershell", "-NoProfile",
  215. "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory",
  216. ])
  217. m = re.search(r"(\d{8,})", out)
  218. if m:
  219. return round(int(m.group(1)) / (1024**3), 1)
  220. # Fall back to wmic for older Windows
  221. out = _run(["wmic", "ComputerSystem", "get", "TotalPhysicalMemory"])
  222. m = re.search(r"(\d{6,})", out)
  223. if m:
  224. return round(int(m.group(1)) / (1024**3), 1)
  225. return 0.0
  226. def total_free_disk_gb(path: str = ".") -> float:
  227. try:
  228. usage = shutil.disk_usage(path)
  229. return round(usage.free / (1024**3), 1)
  230. except OSError:
  231. return 0.0
  232. def check_pytorch_cuda() -> dict | None:
  233. """Optional PyTorch availability check. Only run when --check-pytorch is set."""
  234. try:
  235. import torch # type: ignore[import-not-found]
  236. except Exception as e:
  237. return {"available": False, "reason": f"torch not importable: {e}"}
  238. info: dict[str, Any] = {
  239. "available": True,
  240. "torch_version": torch.__version__,
  241. }
  242. try:
  243. info["cuda_available"] = bool(torch.cuda.is_available())
  244. if info["cuda_available"]:
  245. info["cuda_device_count"] = torch.cuda.device_count()
  246. info["cuda_device_0"] = torch.cuda.get_device_name(0)
  247. except Exception:
  248. info["cuda_available"] = False
  249. try:
  250. info["mps_available"] = bool(torch.backends.mps.is_available())
  251. except Exception:
  252. info["mps_available"] = False
  253. return info
  254. def classify(gpu: dict | None, ram_gb: float, free_disk_gb: float, *, wsl: bool, rosetta: bool) -> tuple[str, str, list[str]]:
  255. notes: list[str] = []
  256. if rosetta:
  257. notes.append(
  258. "Detected Python running under Rosetta on Apple Silicon. "
  259. "ComfyUI MPS support requires native ARM64 Python — install via "
  260. "`brew install python` or arm64 Miniforge, then re-run."
  261. )
  262. return "cloud", "comfy-cloud", notes
  263. if wsl and gpu and gpu["vendor"] == "nvidia":
  264. notes.append("Detected WSL2 + NVIDIA — confirm `nvidia-smi` works in your WSL distro before installing.")
  265. if free_disk_gb and free_disk_gb < MIN_FREE_DISK_GB:
  266. notes.append(
  267. f"Free disk space ({free_disk_gb} GB) is below the {MIN_FREE_DISK_GB} GB recommended minimum. "
  268. "ComfyUI core (~5 GB) plus one SDXL model (~6.5 GB) needs space; Flux Dev needs ~24 GB."
  269. )
  270. # Host RAM matters even for discrete-GPU systems: ComfyUI swaps model
  271. # weights through CPU RAM when shuffling between text encoders / VAE / UNet.
  272. # Apple's unified-memory check is handled below so don't double-warn.
  273. if ram_gb and ram_gb < 8 and gpu and gpu.get("vendor") != "apple":
  274. notes.append(
  275. f"System RAM ({ram_gb} GB) is low. ComfyUI swaps model weights through "
  276. "host RAM; <8 GB causes severe slowdowns. 16+ GB recommended."
  277. )
  278. if gpu is None:
  279. notes.append(
  280. "No supported accelerator found (NVIDIA CUDA / AMD ROCm / Apple Silicon / Intel Arc)."
  281. )
  282. notes.append(
  283. "CPU-only ComfyUI works but is unusably slow for modern models — use Comfy Cloud."
  284. )
  285. return "cloud", "comfy-cloud", notes
  286. if gpu["vendor"] == "apple":
  287. gen = gpu.get("generation")
  288. variant = gpu.get("variant")
  289. mem = gpu.get("unified_memory_gb", 0.0)
  290. gen_str = f"M{gen}" if gen else "Apple Silicon"
  291. if variant:
  292. gen_str += f" {variant}"
  293. if mem < MIN_MAC_RAM_GB:
  294. notes.append(
  295. f"{gen_str} with {mem} GB unified memory — below the {MIN_MAC_RAM_GB} GB practical minimum."
  296. )
  297. notes.append("SD1.5 may work; SDXL/Flux will swap or OOM. Recommend Comfy Cloud.")
  298. return "cloud", "comfy-cloud", notes
  299. if mem < OK_MAC_RAM_GB:
  300. notes.append(
  301. f"{gen_str} with {mem} GB — SDXL works but slow. Flux/video likely too tight."
  302. )
  303. return "marginal", "apple-silicon", notes
  304. notes.append(f"{gen_str} with {mem} GB unified memory — good for SDXL/Flux.")
  305. return "ok", "apple-silicon", notes
  306. if gpu["vendor"] == "intel":
  307. notes.append("Intel Arc detected — ComfyUI IPEX support is experimental; Comfy Cloud is more reliable.")
  308. return "marginal", "intel", notes
  309. # Discrete NVIDIA / AMD
  310. vram = gpu.get("vram_gb", 0.0)
  311. name = gpu["name"]
  312. if vram < MIN_VRAM_GB_USABLE:
  313. notes.append(
  314. f"{name} has only {vram} GB VRAM — below the {MIN_VRAM_GB_USABLE} GB practical minimum."
  315. )
  316. notes.append("Most modern models won't load. Recommend Comfy Cloud.")
  317. return "cloud", "comfy-cloud", notes
  318. if vram < OK_VRAM_GB:
  319. notes.append(
  320. f"{name} ({vram} GB VRAM) — SD1.5 works, SDXL tight, Flux/video unlikely."
  321. )
  322. return "marginal", gpu["vendor"], notes
  323. if vram < GREAT_VRAM_GB:
  324. notes.append(f"{name} ({vram} GB VRAM) — SDXL comfortable, Flux possible with optimizations.")
  325. return "ok", gpu["vendor"], notes
  326. notes.append(f"{name} ({vram} GB VRAM) — can run everything including Flux/video.")
  327. return "ok", gpu["vendor"], notes
  328. def build_report(*, check_pytorch: bool = False) -> dict:
  329. sysname = platform.system()
  330. arch = platform.machine()
  331. ram_gb = total_system_ram_gb()
  332. free_disk_gb = total_free_disk_gb(os.path.expanduser("~"))
  333. rosetta = is_rosetta()
  334. wsl = is_wsl()
  335. gpu = (
  336. detect_nvidia()
  337. or detect_rocm()
  338. or detect_apple_silicon()
  339. or detect_intel_arc()
  340. )
  341. # Intel Mac: arm64 detect failed AND no other GPU paths
  342. if gpu is None and sysname == "Darwin" and arch != "arm64" and not rosetta:
  343. notes = [
  344. "Intel Mac detected — no MPS backend available.",
  345. "ComfyUI will fall back to CPU which is unusably slow. Use Comfy Cloud.",
  346. ]
  347. report = {
  348. "os": sysname,
  349. "arch": arch,
  350. "system_ram_gb": ram_gb,
  351. "free_disk_gb": free_disk_gb,
  352. "wsl": False,
  353. "rosetta": False,
  354. "gpu": None,
  355. "verdict": "cloud",
  356. "recommended_install_path": "comfy-cloud",
  357. "comfy_cli_flag": None,
  358. "notes": notes,
  359. "install_urls": _install_urls(),
  360. }
  361. if check_pytorch:
  362. report["pytorch"] = check_pytorch_cuda()
  363. return report
  364. verdict, install_path, notes = classify(
  365. gpu, ram_gb, free_disk_gb, wsl=wsl, rosetta=rosetta,
  366. )
  367. report = {
  368. "os": sysname,
  369. "arch": arch,
  370. "system_ram_gb": ram_gb,
  371. "free_disk_gb": free_disk_gb,
  372. "wsl": wsl,
  373. "rosetta": rosetta,
  374. "gpu": gpu,
  375. "verdict": verdict,
  376. "recommended_install_path": install_path,
  377. "comfy_cli_flag": _COMFY_CLI_FLAG.get(install_path),
  378. "notes": notes,
  379. "install_urls": _install_urls(),
  380. }
  381. if check_pytorch:
  382. report["pytorch"] = check_pytorch_cuda()
  383. return report
  384. def _install_urls() -> dict:
  385. return {
  386. "desktop": "https://docs.comfy.org/installation/desktop",
  387. "manual": "https://docs.comfy.org/installation/manual_install",
  388. "comfy_cli": "https://docs.comfy.org/comfy-cli/getting-started",
  389. "cloud": "https://platform.comfy.org",
  390. }
  391. def main(argv: list[str] | None = None) -> int:
  392. import argparse
  393. p = argparse.ArgumentParser(description="Check whether this machine can run ComfyUI locally.")
  394. p.add_argument("--json", action="store_true", help="Emit machine-readable JSON only")
  395. p.add_argument("--check-pytorch", action="store_true",
  396. help="Also probe `torch` for CUDA/MPS availability (slower)")
  397. args = p.parse_args(argv)
  398. report = build_report(check_pytorch=args.check_pytorch)
  399. if args.json:
  400. print(json.dumps(report, indent=2))
  401. else:
  402. print(f"OS: {report['os']} ({report['arch']})")
  403. if report.get("wsl"):
  404. print("Env: WSL2")
  405. if report.get("rosetta"):
  406. print("Env: Rosetta (x86_64 Python on Apple Silicon)")
  407. print(f"RAM: {report['system_ram_gb']} GB")
  408. print(f"Free disk: {report['free_disk_gb']} GB (~/)")
  409. if report["gpu"]:
  410. g = report["gpu"]
  411. if g["vendor"] == "apple":
  412. print(f"GPU: {g['name']} — {g.get('unified_memory_gb', 0)} GB unified memory")
  413. else:
  414. print(f"GPU: {g['name']} — {g.get('vram_gb', 0)} GB VRAM")
  415. if g.get("all_gpus") and len(g["all_gpus"]) > 1:
  416. print(f" ({len(g['all_gpus'])} GPUs total; using best by VRAM)")
  417. else:
  418. print("GPU: (none detected)")
  419. print(f"Verdict: {report['verdict']} → {report['recommended_install_path']}")
  420. if report["comfy_cli_flag"]:
  421. print(f" run: comfy --skip-prompt install {report['comfy_cli_flag']}")
  422. if report.get("pytorch"):
  423. pt = report["pytorch"]
  424. if pt.get("available"):
  425. line = f"PyTorch: {pt.get('torch_version')}"
  426. if pt.get("cuda_available"):
  427. line += f" + CUDA ({pt.get('cuda_device_0', '?')})"
  428. if pt.get("mps_available"):
  429. line += " + MPS"
  430. print(line)
  431. else:
  432. print(f"PyTorch: not available — {pt.get('reason')}")
  433. for n in report["notes"]:
  434. print(f" • {n}")
  435. if report["verdict"] == "ok":
  436. return 0
  437. if report["verdict"] == "marginal":
  438. return 1
  439. return 2
  440. if __name__ == "__main__":
  441. sys.exit(main())