Spaces:
Paused

assistant / backend /hardware.py
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
88.2 kB
""" hardware.py β€” GPU/device detection and the "Fix Environment" self-repair helper (installs a hardware-matched PyTorch build at runtime). """ import os import re import subprocess import sys from pathlib import Path from typing import Optional import torch import warnings # Windows flag to suppress creating a console window for spawned subprocesses CREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0 # ── Frozen-build pip helpers ─────────────────────────────────────────────── # In the PyInstaller/Store build sys.executable is the app exe (not Python), # so we ship a minimal bundled Python+pip alongside the app and use it for # all runtime pip installs (GPU PyTorch, llama-cpp-python, agent packages). # Packages install into user_data/packages/ (writable, isolated from the # frozen bundle) and the startup hook (pyi_rth_smolagents_source.py) adds # that directory to sys.path + torch/lib to os.environ["PATH"]. FROZEN_PYTHON_EXE: Optional[str] = None # resolved once, cached def _find_frozen_python() -> Optional[str]: """Locate the bundled Python interpreter shipped with the frozen app. The build pipeline (build_standalone.py) downloads the Python embeddable package, adds pip, and places it in <app>/python/. This function finds that interpreter so pip-based installs work in the packaged build. Returns the path to python.exe or None when unavailable. """ global FROZEN_PYTHON_EXE if FROZEN_PYTHON_EXE is not None: return FROZEN_PYTHON_EXE if not getattr(sys, "frozen", False): return None # APP_ROOT = parent of internal/ (the PyInstaller contents_directory). app_root = Path(sys._MEIPASS).parent candidate = app_root / "python" / "python.exe" if candidate.is_file(): FROZEN_PYTHON_EXE = str(candidate) return FROZEN_PYTHON_EXE return None def _frozen_pip_target() -> str: """Return the --target directory for pip installs in the frozen build. Packages land in user_data/packages/ which the startup hook adds to sys.path (and torch/lib to os.environ["PATH"]). """ from backend.paths import user_data_dir return str(user_data_dir() / "packages") def _pip_base_args() -> list: """Return the base pip-install command prefix. In the frozen build the bundled Python+pip is used and every install targets user_data/packages/ (--target) for isolation. In dev/venv builds the normal sys.executable is used. """ frozen_py = _find_frozen_python() if frozen_py: return [frozen_py, "-m", "pip", "install", "--target", _frozen_pip_target()] return [sys.executable, "-m", "pip", "install"] # Canonical GPU-detection helpers live in llama_health (which never imports # backend modules, so there is no import cycle). Reuse them here instead of # maintaining a second copy β€” the compute-capability signal decides whether # any CUDA wheel can actually run on this machine. from backend.llama_health import _gpu_compute_capability, _gpu_name def _llama_cpp_cpu_wheel_url() -> Optional[str]: """Prebuilt CPU wheel for llama-cpp-python on Windows (any Python 3.x). `pip install llama-cpp-python` without an explicit wheel URL resolves to the sdist and builds from source β€” which needs a C/C++ toolchain that most end-user PCs (and always the packaged Microsoft Store build) don't have, so the install fails out of the box. Every CPU fallback must therefore install this prebuilt wheel instead. Returns None on non-Windows, where the plain PyPI package remains the fallback.""" if sys.platform != "win32": return None return ( "https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34/" "llama_cpp_python-0.3.34-py3-none-win_amd64.whl" ) def _llama_cpp_vulkan_wheel_url() -> Optional[str]: """Prebuilt Vulkan wheel for llama-cpp-python on Windows β€” hardware offload for AMD/Intel GPUs via the Vulkan backend. Like the CPU wheel it is built WITHOUT AVX-512 code paths, so it loads on the same Intel consumer CPUs the CUDA wheels crash on (see _cpu_supports_avx512).""" if sys.platform != "win32": return None return ( "https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34-vulkan/" "llama_cpp_python-0.3.34-py3-none-win_amd64.whl" ) def _cpu_supports_avx512() -> bool: """True when this CPU can actually execute AVX-512 instructions. The abetlen llama-cpp-python CUDA wheels (v0.3.34-cu124 / -cu130 β€” the ones the installer picks for a modern NVIDIA GPU with a matching CUDA runtime) are compiled WITH AVX-512 code paths. On CPUs without AVX-512 β€” every Intel consumer chip since Alder Lake, e.g. i7-14700F (Raptor Lake) β€” model LOADING crashes with STATUS_ILLEGAL_INSTRUCTION (0xc000001d / WinError -1073741795) inside llama.cpp's native code because some quantize/load paths are not runtime-dispatched: the app showed "Failed to load GGUF model … Windows Error 0xc000001d" for EVERY local GGUF on such a machine. The CPU wheel (and the vulkan wheel) are built WITHOUT AVX-512 and load fine, so the installer must pick them on such CPUs β€” GPU offload still works via the external llama-server backend, whose release binaries ship per-architecture CPU DLLs. Detected via Windows' documented IsProcessorFeaturePresent( PF_AVX512F_INSTRUCTIONS_AVAILABLE). Non-Windows / unknown OS verdicts return True so a capable machine is never denied the CUDA wheel. """ if sys.platform != "win32": return True try: import ctypes return bool(ctypes.windll.kernel32.IsProcessorFeaturePresent(41)) except Exception: # OS can't tell us β€” assume AVX-512 capable (the historical default). return True def _cpu_name() -> str: """The CPU's model name (e.g. 'Intel(R) Core(TM) i7-14700F') for installer messages β€” read from the registry, never raising.""" try: import winreg with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0", ) as key: value, _ = winreg.QueryValueEx(key, "ProcessorNameString") return str(value).strip() or "unknown CPU" except Exception: return "this CPU" def is_illegal_instruction_error(exc) -> bool: """True when an exception (or any exception in its chain) is Windows' STATUS_ILLEGAL_INSTRUCTION (0xc000001d / WinError -1073741795) β€” the signature of a native binary executing a CPU instruction this CPU does not support, e.g. an AVX-512 llama-cpp-python CUDA wheel on an Intel consumer CPU (see _cpu_supports_avx512). Used to route around a broken wheel (auto-fallback to llama-server) and to surface the REAL cause in GGUF load errors instead of "corrupted file" guesses.""" seen = set() while exc is not None and id(exc) not in seen: seen.add(id(exc)) msg = f"{exc!r} {exc}".lower() if any(tok in msg for tok in ("0xc000001d", "-1073741795", "illegal instruction", "status_illegal_instruction")): return True exc = getattr(exc, "__cause__", None) or getattr(exc, "__context__", None) return False class HardwareManager: PYTORCH_AUTO = "auto" PYTORCH_CPU = "cpu" PYTORCH_CUDA = "cuda" PYTORCH_XPU = "xpu" PYTORCH_ROCM = "rocm" LLAMA_CPP_AUTO = "auto" LLAMA_CPP_CPU = "cpu" LLAMA_CPP_CUDA = "cuda" LLAMA_CPP_VULKAN = "vulkan" @staticmethod def _normalize_gpu_brand(name: str) -> str: lowered = (name or "").lower() if any(token in lowered for token in ("nvidia", "geforce", "rtx", "gtx", "quadro")): return "nvidia" if any(token in lowered for token in ("amd", "radeon", "rx ", "vega", "firepro")): return "amd" if "intel" in lowered: return "intel" return "unknown" @staticmethod def detect_video_controllers() -> list[dict]: """Return display adapters visible to the OS. This intentionally does not depend on torch. Store/customer machines often start with CPU-only torch, which means torch cannot see Intel, AMD, or even NVIDIA hardware yet. Windows CIM is the most reliable low-friction signal for recommending an install path. VRAM note: Win32_VideoController.AdapterRAM is a 32-bit DWORD, so it caps at ~4 GB and returns the 0xFFFFFFFF "unknown" sentinel when unavailable β€” on any NVIDIA GPU with more VRAM than that it is garbage (a 24 GB card reports ~4.0 GB). NVIDIA controllers therefore get their true total VRAM from nvidia-smi (memory.total), matched by GPU name with an index-order fallback; non-NVIDIA cards keep the CIM value (their VRAM fits in a DWORD). """ controllers = [] if sys.platform == "win32": ps = ( "Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue | " "Select-Object Name,AdapterRAM,DriverVersion,DriverDate | ConvertTo-Json -Compress" ) try: result = subprocess.run( ["powershell", "-NoProfile", "-Command", ps], capture_output=True, text=True, check=False, timeout=10, creationflags=CREATE_NO_WINDOW, ) if result.returncode == 0 and result.stdout.strip(): import json data = json.loads(result.stdout) if isinstance(data, dict): data = [data] for item in data or []: name = str(item.get("Name") or "").strip() if not name: continue controllers.append({ "name": name, "brand": HardwareManager._normalize_gpu_brand(name), "adapter_ram": item.get("AdapterRAM"), "driver_version": item.get("DriverVersion") or "", "driver_date": item.get("DriverDate") or "", }) except Exception: pass # Only NVIDIA VRAM is untrustworthy (DWORD cap), so only then is # an nvidia-smi probe worth spawning β€” pure Intel/AMD machines # never pay for it. nvidia_controllers = [c for c in controllers if c["brand"] == "nvidia"] if nvidia_controllers: smi_gpus = HardwareManager._nvidia_smi_gpus() used = set() for c in nvidia_controllers: # Prefer a name match β€” CIM and nvidia-smi can order GPUs # differently on multi-GPU machines β€” then fall back to # the first unmatched GPU (index order). target = None for i, g in enumerate(smi_gpus): if i not in used and HardwareManager._gpu_names_match(c["name"], g["name"]): target = i break if target is None: for i in range(len(smi_gpus)): if i not in used: target = i break if target is not None: used.add(target) c["adapter_ram"] = HardwareManager._vram_bytes(smi_gpus[target]["vram_mib"]) if controllers: return controllers # Fallbacks for machines where CIM is unavailable. for g in HardwareManager._nvidia_smi_gpus(): controllers.append({ "name": g["name"], "brand": "nvidia", "adapter_ram": HardwareManager._vram_bytes(g["vram_mib"]), "driver_version": g.get("driver_version") or "", "driver_date": "", }) return controllers @staticmethod def _nvidia_smi_gpus() -> list[dict]: """Name + total VRAM (MiB) + driver version of each NVIDIA GPU, from nvidia-smi. Returns [] when nvidia-smi is unavailable β€” callers must treat that as "unknown VRAM", never as zero. Win32_VideoController. AdapterRAM cannot be trusted for VRAM: it is a 32-bit DWORD that caps at ~4 GB (see detect_video_controllers). """ try: result = subprocess.run( ["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"], capture_output=True, text=True, check=False, timeout=10, creationflags=CREATE_NO_WINDOW, ) if result.returncode != 0: return [] gpus = [] for line in result.stdout.splitlines(): parts = [p.strip() for p in line.split(",")] if not parts or not parts[0] or parts[0].lower() == "n/a": continue mib = 0 m = re.search(r"\d+", parts[1] if len(parts) > 1 else "") if m: mib = int(m.group(0)) gpus.append({ "name": parts[0], "vram_mib": mib, "driver_version": parts[2] if len(parts) > 2 else "", }) return gpus except Exception: return [] @staticmethod def _gpu_names_match(a: str, b: str) -> bool: """True if two GPU names refer to the same card β€” normalized substring match (either direction). CIM and nvidia-smi usually agree exactly on NVIDIA names but can differ in spacing/case.""" na = re.sub(r"[^a-z0-9]+", "", (a or "").lower()) nb = re.sub(r"[^a-z0-9]+", "", (b or "").lower()) return bool(na and nb and (na in nb or nb in na)) @staticmethod def _vram_bytes(mib: int) -> int: """Convert nvidia-smi MiB to bytes (stored in adapter_ram so existing consumers keep working).""" return int(mib) * 1024 * 1024 @staticmethod def _intel_xpu_likely_supported(gpu_name: str) -> bool: lowered = (gpu_name or "").lower() # Arc / Xe / Core Ultra iGPUs are the realistic Windows XPU target. # Older UHD/HD iGPUs usually expose graphics/Vulkan but not a usable # PyTorch XPU runtime, so recommending XPU there creates huge downloads # followed by a failed kernel test. return any(token in lowered for token in (" arc", "intel(r) arc", " iris xe", " xe graphics", "core ultra")) @staticmethod def _amd_rocm_likely_supported(gpu_name: str) -> bool: lowered = (gpu_name or "").lower() # Windows ROCm support is much narrower than "any Radeon". Keep this # conservative; CPU/Vulkan remain the broad compatibility path. return any(token in lowered for token in ("7900", "7800", "7700", "7600", "w7900", "w7800")) @staticmethod def _adapter_ram_gb(gpu: dict) -> Optional[float]: """Best-effort VRAM (GB). None/0 are unknown, and the exact 0xFFFFFFFF value is Win32_VideoController.AdapterRAM's documented "unknown" sentinel β€” never rendered as a number. The sentinel is the only DWORD value that can be reliably detected: a >4 GB card's raw AdapterRAM wraps to an arbitrary-looking number (e.g. 4293918720 for a 24 GB card), which this check alone cannot distinguish from a legit ~4 GB value. Those cases are handled by the nvidia-smi enrichment in detect_video_controllers (available on any NVIDIA machine with a working driver); a machine without nvidia-smi and without the exact sentinel keeps the raw DWORD β€” a known residual limitation. """ try: ram = gpu.get("adapter_ram") if not ram: return None ram = int(ram) # Exactly 0xFFFFFFFF is the documented "unknown" sentinel of the # 32-bit DWORD β€” a raw AdapterRAM can never exceed it, while a # real byte count (e.g. the nvidia-smi enrichment) legitimately # can, so the comparison must be exact equality, not >=. if ram == 0xFFFFFFFF: return None return ram / (1024 ** 3) except Exception: return None @staticmethod def _nvidia_generation_from_cc(cc: Optional[str]) -> str: try: major = int(str(cc).split(".")[0]) except Exception: return "unknown generation" return { 5: "Maxwell-class or older", 6: "Pascal-class", 7: "Turing/Volta-class", 8: "Ampere/Ada-class", 9: "Hopper/Ada/Blackwell-class", }.get(major, "new NVIDIA generation" if major > 9 else "legacy NVIDIA generation") @staticmethod def _intel_generation_hint(name: str) -> str: lowered = (name or "").lower() if "arc" in lowered: return "Intel Arc discrete GPU" if "core ultra" in lowered: return "Core Ultra / modern Xe iGPU" if "iris xe" in lowered or " xe graphics" in lowered: return "Iris Xe / Xe-class iGPU" if "uhd" in lowered or " hd graphics" in lowered: return "older Intel UHD/HD iGPU" return "Intel graphics" @staticmethod def get_acceleration_decision_tree() -> dict: """Detailed hardware decision tree for the Settings tab. The installer intentionally lays down a CPU baseline only. This method explains what the user can optionally install afterward and why, using hardware signals that matter for native AI packages: GPU family/generation, NVIDIA compute capability, installed CUDA runtime DLLs, driver hint, and VRAM. """ gpus = HardwareManager.detect_video_controllers() cc = _gpu_compute_capability() cuda_driver = HardwareManager.detect_nvidia_cuda_version() cuda_runtime = HardwareManager.detect_installed_cuda_runtime_major() lines = ["Install baseline: CPU PyTorch first. Optional accelerators can be installed from Settings."] adapter_details = [] for idx, gpu in enumerate(gpus): name = gpu.get("name", "Unknown GPU") brand = gpu.get("brand", "unknown") ram_gb = HardwareManager._adapter_ram_gb(gpu) ram_text = f"{ram_gb:.1f} GB" if ram_gb is not None else "unknown VRAM" detail = f"{idx}: {name} | brand={brand} | VRAM={ram_text} | driver={gpu.get('driver_version') or 'unknown'}" if brand == "nvidia": detail += f" | compute capability={cc or 'unknown'} | {HardwareManager._nvidia_generation_from_cc(cc)}" elif brand == "intel": detail += f" | {HardwareManager._intel_generation_hint(name)}" adapter_details.append(detail) if adapter_details: lines.extend(["", "Detected adapters:"] + [f"- {d}" for d in adapter_details]) else: lines.extend(["", "Detected adapters:", "- none reported by the OS"]) pytorch_choice = HardwareManager.PYTORCH_CPU pytorch_reason = "CPU PyTorch is the safe default and works on the widest range of PCs." llama_choice = HardwareManager.LLAMA_CPP_CPU llama_reason = "CPU llama.cpp is the safest GGUF baseline." brands = {g.get("brand") for g in gpus} if "nvidia" in brands: try: cc_f = float(cc) if cc else 0.0 except (TypeError, ValueError): cc_f = 0.0 lines.append("") lines.append("NVIDIA decision:") lines.append(f"- Driver CUDA hint: {cuda_driver or 'not reported'}") lines.append(f"- Installed CUDA runtime DLL family: cublas64_{cuda_runtime}.dll" if cuda_runtime else "- Installed CUDA runtime DLL family: not found") lines.append(f"- Compute capability: {cc or 'unknown'} ({HardwareManager._nvidia_generation_from_cc(cc)})") if cc_f >= 7.0: pytorch_choice = HardwareManager.PYTORCH_CUDA pytorch_reason = "NVIDIA compute capability is new enough for current CUDA PyTorch; install CUDA PyTorch only if you want GPU speed." if cuda_runtime in (12, 13): llama_choice = HardwareManager.LLAMA_CPP_CUDA llama_reason = f"CUDA runtime {cuda_runtime} DLLs are installed, so a matching llama-cpp-python CUDA wheel can load." else: llama_reason = "GPU is modern, but CUDA runtime DLLs were not found; use CPU llama.cpp or install CUDA runtime before CUDA llama.cpp." elif cc_f: pytorch_reason = f"NVIDIA compute capability {cc} is too old for current CUDA AI wheels; CPU is recommended." llama_reason = f"NVIDIA compute capability {cc} is too old for current llama.cpp CUDA kernels; CPU is recommended." if "intel" in brands or "amd" in brands: llama_choice = HardwareManager.LLAMA_CPP_VULKAN llama_reason += " Vulkan can be tried for Intel/AMD graphics, but keep CPU as fallback." else: pytorch_reason = "NVIDIA GPU was detected but compute capability could not be verified; CPU is the safe default." llama_reason = "Do not install CUDA llama.cpp blindly without compute capability and runtime verification." elif "amd" in brands: amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd") if HardwareManager._amd_rocm_likely_supported(amd_names): pytorch_choice = HardwareManager.PYTORCH_ROCM pytorch_reason = "Recent AMD GPU detected; Windows ROCm can be tried from Settings, but it is a large optional install." else: pytorch_reason = "AMD GPU detected, but Windows ROCm support is narrow; CPU PyTorch is safer." llama_choice = HardwareManager.LLAMA_CPP_VULKAN llama_reason = "AMD graphics can try the Vulkan llama.cpp wheel; CPU remains the compatibility fallback." elif "intel" in brands: intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel") if HardwareManager._intel_xpu_likely_supported(intel_names): pytorch_choice = HardwareManager.PYTORCH_XPU pytorch_reason = "Modern Intel Arc/Xe-class GPU detected; PyTorch XPU can be tried from Settings." llama_choice = HardwareManager.LLAMA_CPP_VULKAN llama_reason = "Intel graphics can try Vulkan llama.cpp; CPU remains the fallback." else: pytorch_reason = "Older Intel UHD/HD graphics detected; PyTorch XPU is not recommended. Use CPU." llama_reason = "Older Intel UHD/HD graphics may expose Vulkan, but acceleration is often limited; CPU is recommended." lines.extend([ "", f"Recommended PyTorch path: {pytorch_choice.upper()} - {pytorch_reason}", f"Recommended GGUF/llama.cpp path: {llama_choice.upper()} - {llama_reason}", "", "Rule: install GPU packages only from Settings after the app launches, and only after a real kernel/load test passes.", ]) return { "gpus": gpus, "nvidia_compute_capability": cc, "nvidia_generation": HardwareManager._nvidia_generation_from_cc(cc), "cuda_driver": cuda_driver, "cuda_runtime_major": cuda_runtime, "pytorch": {"choice": pytorch_choice, "reason": pytorch_reason}, "llama_cpp": {"choice": llama_choice, "reason": llama_reason}, "report": "\n".join(lines), } @staticmethod def _format_gpu_list(gpus: list[dict]) -> str: if not gpus: return "No discrete/integrated GPU reported by the OS." rows = [] for idx, gpu in enumerate(gpus): ram_gb = HardwareManager._adapter_ram_gb(gpu) ram_text = f"{ram_gb:.1f} GB" if ram_gb is not None else "unknown VRAM" rows.append( f"{idx}: {gpu.get('name', 'Unknown GPU')} " f"({gpu.get('brand', 'unknown')}, {ram_text}, driver {gpu.get('driver_version') or 'unknown'})" ) return "\n".join(rows) @staticmethod def get_backend_recommendations() -> dict: """Recommend install choices for PyTorch and llama.cpp separately.""" tree = HardwareManager.get_acceleration_decision_tree() return { "gpus": tree["gpus"], "pytorch": tree["pytorch"], "llama_cpp": tree["llama_cpp"], } @staticmethod def get_pytorch_install_options() -> list[str]: return [ "Auto recommended", "CPU PyTorch (works on every PC)", "NVIDIA CUDA PyTorch", "Intel XPU PyTorch", "AMD ROCm PyTorch", ] @staticmethod def parse_pytorch_install_choice(label: str) -> str: text = (label or "").lower() if "nvidia" in text or "cuda" in text: return HardwareManager.PYTORCH_CUDA if "intel" in text or "xpu" in text: return HardwareManager.PYTORCH_XPU if "amd" in text or "rocm" in text: return HardwareManager.PYTORCH_ROCM if "cpu" in text: return HardwareManager.PYTORCH_CPU return HardwareManager.PYTORCH_AUTO @staticmethod def get_llama_cpp_install_options() -> list[str]: return [ "Auto recommended", "CPU llama.cpp", "NVIDIA CUDA llama.cpp", "Vulkan llama.cpp (Intel/AMD)", ] @staticmethod def parse_llama_cpp_install_choice(label: str) -> str: text = (label or "").lower() if "nvidia" in text or "cuda" in text: return HardwareManager.LLAMA_CPP_CUDA if "vulkan" in text or "intel" in text or "amd" in text: return HardwareManager.LLAMA_CPP_VULKAN if "cpu" in text: return HardwareManager.LLAMA_CPP_CPU return HardwareManager.LLAMA_CPP_AUTO @staticmethod def format_backend_recommendations() -> str: return HardwareManager.get_acceleration_decision_tree()["report"] @staticmethod def detect_vram_gb() -> Optional[float]: """Best-effort total VRAM (in GB) of the primary CUDA GPU, if any. Returns None if there's no CUDA GPU, or detection fails for any reason β€” callers should treat None as "unknown", not "zero", since a failed *detection* is not the same as genuinely having no GPU. """ try: if torch.cuda.is_available(): props = torch.cuda.get_device_properties(0) return props.total_memory / (1024 ** 3) if hasattr(torch, "xpu") and torch.xpu.is_available(): props = torch.xpu.get_device_properties(0) return props.total_memory / (1024 ** 3) except Exception: pass return None @staticmethod def detect_system_ram_gb() -> Optional[float]: """Best-effort total system RAM (in GB). Prefers `psutil` (not a hard requirement of this app β€” see requirements.txt) since it's cross-platform; falls back to reading /proc/meminfo directly on Linux if psutil isn't installed. Returns None if neither approach works (e.g. Windows without psutil) β€” callers should treat this the same as an unknown GPU: fall back to a conservative default tier rather than guessing a number that could be wildly wrong. """ try: import psutil return psutil.virtual_memory().total / (1024 ** 3) except Exception: pass try: with open("/proc/meminfo") as f: for line in f: if line.startswith("MemTotal:"): kb = int(line.split()[1]) return kb / (1024 ** 2) except Exception: pass return None @staticmethod def get_memory_usage() -> dict: """Current live CPU + RAM + VRAM usage β€” the numbers shown next to the "Free All VRAM" buttons (Settings tab + sidebar) so users can see how much of their machine is in use (and how much freeing VRAM actually recovered). Never raises: every probe is individually guarded and degrades to None ("unknown") instead of crashing the Settings tab. Returns { "cpu": {"pct": float|None}, "ram": {"used_gb": float|None, "total_gb": float|None, "pct": float|None}, "vram": {"used_gb": float|None, "total_gb": float|None, "pct": float|None}, } - CPU comes from psutil.cpu_percent() (system-wide, the same percentage Task Manager shows). - RAM comes from psutil.virtual_memory() (used = total - available, pct = the same percentage Task Manager shows). - VRAM prefers nvidia-smi `memory.used`/`memory.total` (works even when torch is a CPU-only build), falling back to torch CUDA stats, and stays all-None on machines with no usable GPU. """ usage = { "cpu": {"pct": None}, "ram": {"used_gb": None, "total_gb": None, "pct": None}, "vram": {"used_gb": None, "total_gb": None, "pct": None}, } try: import psutil # A short real sampling interval (not None): cpu_percent(interval=None) # returns 0.0 on the FIRST call because it has no baseline to compare # against β€” the sidebar would show a bogus 0% on first render. A # 100ms sample returns a real number every time, negligible against # the 5s UI poll cadence. usage["cpu"]["pct"] = round(psutil.cpu_percent(interval=0.1), 1) except Exception: pass try: import psutil vm = psutil.virtual_memory() usage["ram"]["used_gb"] = round((vm.total - vm.available) / (1024 ** 3), 1) usage["ram"]["total_gb"] = round(vm.total / (1024 ** 3), 1) usage["ram"]["pct"] = round(vm.percent, 1) except Exception: pass # VRAM β€” nvidia-smi first (real used/total regardless of which torch # build is installed), then torch CUDA as the fallback. try: result = subprocess.run( ["nvidia-smi", "--query-gpu=memory.used,memory.total", "--format=csv,noheader,nounits"], capture_output=True, text=True, check=False, timeout=10, creationflags=CREATE_NO_WINDOW, ) if result.returncode == 0 and result.stdout.strip(): used, total = None, None for line in result.stdout.splitlines(): parts = [p.strip() for p in line.split(",")] m_used = re.search(r"\d+", parts[0]) if parts else None m_total = re.search(r"\d+", parts[1]) if len(parts) > 1 else None if m_used and m_total: used = float(m_used.group(0)) / 1024.0 # MiB -> GiB total = float(m_total.group(0)) / 1024.0 break if used is not None and total is not None: usage["vram"]["used_gb"] = round(used, 1) usage["vram"]["total_gb"] = round(total, 1) usage["vram"]["pct"] = round(used / total * 100, 1) if total else None except Exception: pass if usage["vram"]["total_gb"] is None: try: if torch.cuda.is_available(): props = torch.cuda.get_device_properties(0) total = props.total_memory / (1024 ** 3) used = torch.cuda.memory_allocated(0) / (1024 ** 3) usage["vram"]["used_gb"] = round(used, 1) usage["vram"]["total_gb"] = round(total, 1) usage["vram"]["pct"] = round(used / total * 100, 1) if total else None elif hasattr(torch, "xpu") and torch.xpu.is_available(): props = torch.xpu.get_device_properties(0) total = props.total_memory / (1024 ** 3) used = torch.xpu.memory_allocated(0) / (1024 ** 3) usage["vram"]["used_gb"] = round(used, 1) usage["vram"]["total_gb"] = round(total, 1) usage["vram"]["pct"] = round(used / total * 100, 1) if total else None except Exception: pass return usage # ────────────────────────────────────────────────────────────── # Hardware tiers β€” mirrors the "Model combos by hardware tier" table # in README.md exactly, so the HF-side dynamic model registry (see # model_registry.get_recommended_hf_models()) recommends the same # models the README documents for each tier. Checked from the # top (most capable) down, so a machine that qualifies for a higher # tier is never mistakenly placed in a lower one. # ────────────────────────────────────────────────────────────── TIER_48GB_VRAM = "48gb_vram" TIER_24GB_VRAM = "24gb_vram" TIER_16GB_VRAM = "16gb_vram" TIER_8GB_VRAM = "8gb_vram" TIER_CPU_ONLY = "cpu_only" TIER_UNKNOWN = "unknown" @staticmethod def detect_hardware_tier() -> str: """Classify the current machine into one of the README's hardware tiers, based on detected VRAM (if a CUDA GPU is present) or system RAM (CPU-only case). Returns TIER_UNKNOWN if neither VRAM nor RAM could be determined β€” callers should fall back to the app's existing small defaults (BASE_MODEL_OPTIONS) in that case rather than guessing a tier that might recommend a model too large for the actual machine. """ vram_gb = HardwareManager.detect_vram_gb() if vram_gb is not None: if vram_gb >= 44: # 48 GB tier β€” a little headroom below the nominal 48 return HardwareManager.TIER_48GB_VRAM if vram_gb >= 20: # 24 GB tier return HardwareManager.TIER_24GB_VRAM if vram_gb >= 14: # 16 GB tier return HardwareManager.TIER_16GB_VRAM if vram_gb >= 6: # 8 GB tier β€” some headroom below nominal 8 return HardwareManager.TIER_8GB_VRAM # A CUDA GPU exists but has less VRAM than any tier above # assumes β€” safer to fall back to CPU-only-style (smaller) # recommendations than to recommend an 8GB-tier model that # won't fit. return HardwareManager.TIER_CPU_ONLY ram_gb = HardwareManager.detect_system_ram_gb() if ram_gb is not None and ram_gb >= 56: # 64GB tier β€” some headroom below nominal 64 return HardwareManager.TIER_CPU_ONLY return HardwareManager.TIER_UNKNOWN @staticmethod def detect_nvidia_cuda_version() -> Optional[str]: """Best-effort read of the driver's supported CUDA version from nvidia-smi. Newer NVIDIA drivers (r580+ β€” e.g. the 610.x header line) stopped printing the legacy "CUDA Version: X.Y" text and now print "CUDA UMD Version: X.Y" instead. Parse BOTH spellings so driver detection doesn't silently fail β€” and the "Fix Environment" tool doesn't fall through to a CPU recommendation β€” on current drivers. """ try: result = subprocess.run( ["nvidia-smi"], capture_output=True, text=True, check=False, creationflags=CREATE_NO_WINDOW, ) if result.returncode == 0: for line in result.stdout.splitlines(): for marker in ("CUDA UMD Version:", "CUDA Version:"): if marker in line: val = line.split(marker)[1].strip().rstrip("|").strip() if val and val.lower() != "n/a": return val return None except Exception: return None @staticmethod def detect_installed_cuda_runtime_major() -> Optional[int]: """Best-effort read of the installed CUDA runtime DLL major version. We look for cublas64_*.dll on PATH plus common CUDA install locations. This is the version that matters for native wheels such as llama-cpp-python; the NVIDIA driver's reported CUDA version is only a compatibility hint and can disagree with the DLLs actually present on disk. """ dirs = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d.strip()] cu_path = os.environ.get("CUDA_PATH", "") if cu_path: dirs.append(os.path.join(cu_path, "bin")) for base in ( "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA", "C:/Program Files/NVIDIA Corporation/CUDNN", ): base_p = Path(base) if not base_p.is_dir(): continue for child in base_p.iterdir(): if child.is_dir(): dirs.append(str(child / "bin") if (child / "bin").is_dir() else str(child)) seen = set() majors = [] for d in dirs: try: names = os.listdir(d) except Exception: continue for f in names: m = re.match(r"cublas64_(\d+)\.dll$", f, re.IGNORECASE) if not m or f in seen: continue seen.add(f) try: majors.append(int(m.group(1))) except ValueError: pass return max(majors) if majors else None @staticmethod def get_required_torch_index(cuda_version: str) -> str: """Return the PyTorch wheel index best matching an NVIDIA driver's reported CUDA version. Mirrors the SETUP.ps1 STEP 4 mapping: a wheel is only offered if its bundled CUDA runtime is <= the driver's supported CUDA version (a driver reporting 12.6 cannot run cu128 wheels; a 12.0 driver cannot run cu121+). For drivers newer than any known tier the newest known tier is used, since a new driver does not imply a new GPU β€” SETUP.ps1 re-verifies compatibility with a real-kernel smoke test after install. Also accepts the SETUP.ps1 brand tokens for non-NVIDIA backends ("rocm7.2.1" and "xpu"), mapping them to the correct index so the Fix Environment helper never suggests a bogus CUDA tier on an AMD/Intel machine. """ if not cuda_version: return "https://download.pytorch.org/whl/cpu" if cuda_version == "xpu": return "https://download.pytorch.org/whl/xpu" if cuda_version.startswith("rocm"): return "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1" try: v_parts = cuda_version.split('.') major = int(v_parts[0]) minor = int(v_parts[1]) if major == 11: return "https://download.pytorch.org/whl/cu118" elif major == 12: if minor == 0: return "https://download.pytorch.org/whl/cu118" elif minor in (1, 2, 3): return "https://download.pytorch.org/whl/cu121" elif minor in (4, 5): return "https://download.pytorch.org/whl/cu124" elif minor in (6, 7): return "https://download.pytorch.org/whl/cu126" elif minor in (8, 9): return "https://download.pytorch.org/whl/cu128" else: return "https://download.pytorch.org/whl/cu128" elif major >= 13: # Driver newer than any known tier -> newest known-good tier # (a new driver does not imply a new GPU; SETUP.ps1's # real-kernel smoke test re-verifies compatibility). return "https://download.pytorch.org/whl/cu128" # major < 11 (pre-Pascal-era driver): no current wheel fits, # but mirror SETUP.ps1 and offer the oldest tier β€” the smoke # test decides whether it actually runs. return "https://download.pytorch.org/whl/cu118" except Exception: return "https://download.pytorch.org/whl/cpu" @staticmethod def get_system_status() -> dict: decision = HardwareManager.get_acceleration_decision_tree() recommendations = { "gpus": decision["gpus"], "pytorch": decision["pytorch"], "llama_cpp": decision["llama_cpp"], } status = { "gpu_brand": "none", "gpus": recommendations["gpus"], "recommendations": recommendations, "acceleration_report": decision["report"], "cuda_version": None, "torch_cuda_available": False, "current_device": "cpu", "recommended_index": "https://download.pytorch.org/whl/cpu" } cuda_ver = HardwareManager.detect_nvidia_cuda_version() if cuda_ver: status["gpu_brand"] = "nvidia" status["cuda_version"] = cuda_ver status["recommended_index"] = HardwareManager.get_required_torch_index(cuda_ver) try: status["torch_cuda_available"] = torch.cuda.is_available() if status["torch_cuda_available"]: status["current_device"] = "cuda" elif hasattr(torch, "xpu") and torch.xpu.is_available(): status["current_device"] = "xpu" elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): status["current_device"] = "mps" else: status["current_device"] = "cpu" except Exception: pass if status["gpu_brand"] == "none": brands = {g["brand"] for g in recommendations["gpus"]} if "nvidia" in brands: status["gpu_brand"] = "nvidia" status["cuda_version"] = "unknown" status["recommended_index"] = "https://download.pytorch.org/whl/cu128" elif "amd" in brands: status["gpu_brand"] = "amd" status["cuda_version"] = "rocm7.2.1" status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1" elif "intel" in brands: status["gpu_brand"] = "intel" status["cuda_version"] = "xpu" status["recommended_index"] = "https://download.pytorch.org/whl/xpu" choice = recommendations["pytorch"]["choice"] if choice == HardwareManager.PYTORCH_CPU: status["recommended_index"] = "https://download.pytorch.org/whl/cpu" elif choice == HardwareManager.PYTORCH_XPU: status["recommended_index"] = "https://download.pytorch.org/whl/xpu" elif choice == HardwareManager.PYTORCH_ROCM: status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1" elif choice == HardwareManager.PYTORCH_CUDA and not status["recommended_index"].endswith("/cpu"): pass if False and status["gpu_brand"] == "none": # nvidia-smi was unavailable (or unparseable). Fall back to the # Windows device list so an NVIDIA machine is never mislabeled # "no GPU". Use PowerShell CIM first (works on all modern # Windows; wmic is deprecated/removed in newer releases), then # wmic as a fallback. vc_names = "" try: result = subprocess.run( ["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue).Name -join ';'"], capture_output=True, text=True, check=False, creationflags=CREATE_NO_WINDOW, ) if result.returncode == 0: vc_names = result.stdout except Exception: pass if not vc_names: try: result = subprocess.run( ["wmic", "path", "win32_VideoController", "get", "name"], capture_output=True, text=True, check=False, creationflags=CREATE_NO_WINDOW, ) if result.returncode == 0: vc_names = result.stdout except Exception: pass if "NVIDIA" in vc_names or "GeForce" in vc_names or "RTX" in vc_names or "Quadro" in vc_names: # NVIDIA card present but nvidia-smi didn't cooperate β€” treat # it as a modern driver and point at the proven RTX-tier # index (SETUP.ps1 uses the same fallback; the app's own # real-kernel check verifies the result at runtime). status["gpu_brand"] = "nvidia" status["cuda_version"] = "unknown" status["recommended_index"] = "https://download.pytorch.org/whl/cu128" elif "Radeon" in vc_names or "AMD" in vc_names: status["gpu_brand"] = "amd" status["cuda_version"] = "rocm7.2.1" status["recommended_index"] = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1" elif "Intel" in vc_names: status["gpu_brand"] = "intel" status["cuda_version"] = "xpu" status["recommended_index"] = "https://download.pytorch.org/whl/xpu" return status @staticmethod def fix_environment_gen(choice=None): """Detect hardware and install a matching PyTorch build. choice ("auto" / "cpu" / "cuda" / "xpu" / "rocm", or None = auto): the explicit build the user picked in the Settings popup. Auto still decides by hardware; a non-viable explicit pick degrades to CPU with a clear message (never a mismatched GPU install β€” mirrors install_llama_cpp_python_gen).""" status = HardwareManager.get_system_status() if status["torch_cuda_available"]: yield "βœ… Environment is already correctly configured for GPU!", "cuda", "" return if hasattr(torch, "xpu") and torch.xpu.is_available(): yield "βœ… Environment is already correctly configured for GPU!", "xpu", "" return choice = (choice or "auto").lower() if choice not in ("auto", "cpu", "cuda", "xpu", "rocm"): yield (f"❌ Unknown PyTorch build '{choice}' " "(expected auto / cpu / cuda / xpu / rocm)."), "cpu", f"❌ Unknown PyTorch build '{choice}'." return brand = status["gpu_brand"] cc = _gpu_compute_capability() try: cc_f = float(cc) if cc else 0.0 except (TypeError, ValueError): cc_f = 0.0 gpus = status.get("gpus") or [] intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel") amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd") # Resolve the build that will actually be installed. Every explicit # pick is guarded by the same machine signals the plan popup uses β€” # a non-viable pick degrades to CPU with a clear message, never a # mismatched GPU wheel (mirrors install_llama_cpp_python_gen). if choice == "cpu": effective = HardwareManager.PYTORCH_CPU elif choice == "cuda": if brand == "nvidia" and cc_f >= 7.0: effective = HardwareManager.PYTORCH_CUDA else: yield ("⚠️ The NVIDIA CUDA PyTorch build is not usable on this machine " "(requires a modern NVIDIA GPU). Falling back to the CPU build."), "cpu", \ "⚠️ The NVIDIA CUDA PyTorch build is not usable on this machine. Falling back to the CPU build." effective = HardwareManager.PYTORCH_CPU elif choice == "xpu": if brand == "intel" and HardwareManager._intel_xpu_likely_supported(intel_names): effective = HardwareManager.PYTORCH_XPU else: yield ("⚠️ The Intel XPU PyTorch build is not usable on this machine " "(requires a modern Intel Arc / Xe-class GPU). Falling back to the CPU build."), "cpu", \ "⚠️ The Intel XPU PyTorch build is not usable on this machine. Falling back to the CPU build." effective = HardwareManager.PYTORCH_CPU elif choice == "rocm": if brand == "amd" and HardwareManager._amd_rocm_likely_supported(amd_names): effective = HardwareManager.PYTORCH_ROCM else: yield ("⚠️ The AMD ROCm PyTorch build is not usable on this machine " "(Windows ROCm needs a recent Radeon RX 7000-class GPU). Falling back to the CPU build."), "cpu", \ "⚠️ The AMD ROCm PyTorch build is not usable on this machine. Falling back to the CPU build." effective = HardwareManager.PYTORCH_CPU else: # auto β€” the historical hardware-driven decision tree effective = status.get("recommendations", {}).get("pytorch", {}).get( "choice", HardwareManager.PYTORCH_CPU) if effective == HardwareManager.PYTORCH_CPU: report = status.get("acceleration_report") or HardwareManager.format_backend_recommendations() if choice == "cpu": # An explicit CPU pick needs no full report β€” just confirm the # user's choice (the report would mask this line in the log). yield "CPU PyTorch selected by the user.", "cpu", "CPU PyTorch selected by the user." else: yield "CPU PyTorch is recommended for this machine.", "cpu", report yield "No GPU PyTorch package was installed. The current CPU baseline is the safest option.", "cpu", "" return # Resolve the wheel index for the effective build (never the auto # recommendation's index β€” an explicit pick must map to its own tier). if effective == HardwareManager.PYTORCH_CUDA: index = HardwareManager.get_required_torch_index(status.get("cuda_version") or "") if index.endswith("/cpu"): # NVIDIA GPU present but driver CUDA version unknown β€” the same # proven RTX-tier index get_system_status falls back to. index = "https://download.pytorch.org/whl/cu128" elif effective == HardwareManager.PYTORCH_XPU: index = "https://download.pytorch.org/whl/xpu" else: # PYTORCH_ROCM index = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1" yield "πŸš€ Starting environment fix...", "cuda", "πŸš€ Starting environment fix..." yield f"πŸ” Detected GPU: {brand.upper()}", "cuda", f"πŸ” Detected GPU: {brand.upper()}" yield f"πŸ”— Using PyTorch index: {index}", "cuda", f"πŸ”— Using PyTorch index: {index}" try: if effective == HardwareManager.PYTORCH_ROCM: # AMD ROCm: SDK wheels must be installed before the torch # wheels, and everything comes from repo.radeon.com (the # CUDA-tier install below would resolve nothing there). roc_base = "https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1" sdk_wheels = [ f"{roc_base}/rocm_sdk_core-7.2.1-py3-none-win_amd64.whl", f"{roc_base}/rocm_sdk_devel-7.2.1-py3-none-win_amd64.whl", f"{roc_base}/rocm_sdk_libraries_custom-7.2.1-py3-none-win_amd64.whl", f"{roc_base}/rocm-7.2.1.tar.gz", ] torch_wheels = [ f"{roc_base}/torch-2.9.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl", f"{roc_base}/torchaudio-2.9.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl", f"{roc_base}/torchvision-0.24.1%2Brocm7.2.1-cp312-cp312-win_amd64.whl", ] yield "Running: pip install ROCm SDK wheels", "cuda", "Running: pip install ROCm SDK wheels" sdk_cmd = _pip_base_args() + ["--no-cache-dir"] + sdk_wheels process = subprocess.Popen( sdk_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, creationflags=CREATE_NO_WINDOW, ) for line in process.stdout: yield "πŸ› οΈ Installing...", "cuda", line.strip() process.wait() if process.returncode != 0: yield f"❌ ROCm SDK install failed with exit code {process.returncode}", "cpu", f"❌ ROCm SDK install failed with exit code {process.returncode}" return cmd = _pip_base_args() + ["--no-cache-dir"] + torch_wheels elif effective == HardwareManager.PYTORCH_XPU: # Intel XPU: pin exact versions (index outage bug #185608 # can silently downgrade to an old torch otherwise). cmd = _pip_base_args() + [ "torch==2.11.0", "torchvision==0.26.0", "torchaudio==2.11.0", "--index-url", index] else: cmd = _pip_base_args() + ["torch<2.12", "torchvision", "torchaudio", "--index-url", index] yield f"Running: {' '.join(cmd)}", "cuda", f"Running: {' '.join(cmd)}" process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, creationflags=CREATE_NO_WINDOW, ) for line in process.stdout: yield "πŸ› οΈ Installing...", "cuda", line.strip() process.wait() if process.returncode == 0: yield "✨ Installation successful!", "cuda", "✨ Installation successful!" yield "βœ… Environment fixed! Please RESTART the app to apply changes.", "cuda", "βœ… Environment fixed! Please RESTART the app to apply changes." else: yield f"❌ Installation failed with exit code {process.returncode}", "cpu", f"❌ Installation failed with exit code {process.returncode}" yield "❌ Installation failed. Check the logs above.", "cpu", "❌ Installation failed. Check the logs above." except Exception as e: yield f"❌ Error: {str(e)}", "cpu", f"❌ Error: {str(e)}" @staticmethod def get_pytorch_install_plan() -> dict: """Detect which PyTorch builds are AVAILABLE on this machine and report each with a bilingual reason β€” the Settings popup shows the user every viable option and lets THEM choose, instead of silently installing the recommended path. Returns { "detected": {gpu_brand, gpu_name, cpu_name, cuda_version, compute_capability, current_device}, "options": [ {"id", "label_key", "reason_key", "params", "available", "recommended"}, ... ], } The option `id` is one of: auto / cpu / cuda / xpu / rocm. `auto` is always available and `recommended` mirrors the acceleration decision tree (the historical auto path). """ status = HardwareManager.get_system_status() brand = status["gpu_brand"] gpus = status.get("gpus") or [] cc = _gpu_compute_capability() try: cc_f = float(cc) if cc else 0.0 except (TypeError, ValueError): cc_f = 0.0 intel_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "intel") amd_names = " ".join(g.get("name", "") for g in gpus if g.get("brand") == "amd") # Viability β€” the same machine signals the decision tree uses. CUDA # wheels bundle their own runtime DLLs, so the ONLY hard requirement # is a modern NVIDIA GPU (no installed-runtime / AVX-512 gate like # llama-cpp-python's CUDA wheels). cuda_available = brand == "nvidia" and cc_f >= 7.0 xpu_available = brand == "intel" and HardwareManager._intel_xpu_likely_supported(intel_names) rocm_available = brand == "amd" and HardwareManager._amd_rocm_likely_supported(amd_names) if cuda_available: recommended = "cuda" elif rocm_available: recommended = "rocm" elif xpu_available: recommended = "xpu" else: recommended = "cpu" # CUDA reason β€” granular per obstacle (mirrors the llama-cpp plan). if cuda_available: cuda_key, cuda_params = "ptch_reason_cuda_ok", {} elif brand != "nvidia": cuda_key, cuda_params = "ptch_reason_cuda_requires_nvidia", {} elif not cc_f: cuda_key, cuda_params = "ptch_reason_cuda_cc_unknown", {} else: # NVIDIA but too old for current CUDA wheels cuda_key, cuda_params = "ptch_reason_cuda_old_gpu", {"cc": cc} # XPU reason. if xpu_available: xpu_key, xpu_params = "ptch_reason_xpu_ok", {} elif brand != "intel": xpu_key, xpu_params = "ptch_reason_xpu_requires_intel", {} else: # Intel but old UHD/HD-class iGPU xpu_key, xpu_params = "ptch_reason_xpu_old_gpu", {} # ROCm reason. if rocm_available: rocm_key, rocm_params = "ptch_reason_rocm_ok", {} elif brand != "amd": rocm_key, rocm_params = "ptch_reason_rocm_requires_amd", {} else: # AMD but not RX 7000-class rocm_key, rocm_params = "ptch_reason_rocm_old_gpu", {} options = [ { "id": "auto", "label_key": "ptch_opt_auto", "reason_key": "ptch_reason_auto", "params": {}, "available": True, "recommended": False, }, { "id": "cpu", "label_key": "ptch_opt_cpu", "reason_key": "ptch_reason_cpu_always", "params": {}, "available": True, "recommended": recommended == "cpu", }, { "id": "cuda", "label_key": "ptch_opt_cuda", "reason_key": cuda_key, "params": cuda_params, "available": cuda_available, "recommended": recommended == "cuda", }, { "id": "xpu", "label_key": "ptch_opt_xpu", "reason_key": xpu_key, "params": xpu_params, "available": xpu_available, "recommended": recommended == "xpu", }, { "id": "rocm", "label_key": "ptch_opt_rocm", "reason_key": rocm_key, "params": rocm_params, "available": rocm_available, "recommended": recommended == "rocm", }, ] detected = { "gpu_brand": brand, "gpu_name": _gpu_name(), "cpu_name": _cpu_name(), "cuda_version": status.get("cuda_version"), "compute_capability": cc, "current_device": status.get("current_device", "cpu"), } return {"detected": detected, "options": options} @staticmethod def get_llama_cpp_install_plan() -> dict: """Detect which llama-cpp-python builds are AVAILABLE on this machine and report each with a bilingual reason β€” the Settings popup shows the user every viable option and lets THEM choose, instead of silently installing the CPU wheel. Returns { "detected": {gpu_brand, gpu_name, cpu_name, cuda_version, runtime_major, compute_capability, avx512}, "options": [ {"id", "label_key", "reason_key", "params", "available", "recommended"}, ... ], } The option `id` is one of: auto / cpu / cuda / vulkan. `reason_key` is an i18n key resolved with `params` (e.g. "{cc}" / "{runtime}"). An option is `available` when it can actually run on this machine and `recommended` when it is the best pick. `auto` is always available. """ status = HardwareManager.get_system_status() brand = status["gpu_brand"] cuda_version = status["cuda_version"] runtime_major = HardwareManager.detect_installed_cuda_runtime_major() cc = _gpu_compute_capability() try: cc_f = float(cc) if cc else 0.0 except (TypeError, ValueError): cc_f = 0.0 avx512 = _cpu_supports_avx512() gpu_name = _gpu_name() cpu_name = _cpu_name() detected = { "gpu_brand": brand, "gpu_name": gpu_name, "cpu_name": cpu_name, "cuda_version": cuda_version, "runtime_major": runtime_major, "compute_capability": cc, "avx512": avx512, } options = [ { "id": "auto", "label_key": "llcpp_opt_auto", "reason_key": "llcpp_reason_auto", "params": {}, "available": True, "recommended": False, }, { "id": "cpu", "label_key": "llcpp_opt_cpu", "reason_key": "llcpp_reason_cpu_always", "params": {}, "available": True, "recommended": False, }, ] # CUDA β€” viable ONLY when every hardware condition holds (same signals # the installer guards on: NVIDIA brand, modern compute capability, a # CUDA runtime DLL family actually installed, AVX-512-capable CPU). cuda_available = ( brand == "nvidia" and cc_f >= 7.0 and runtime_major in (12, 13) and avx512 ) if cuda_available: cuda_key, cuda_params = "llcpp_reason_cuda_ok", {"runtime": runtime_major} cuda_recommended = True elif brand != "nvidia": cuda_key, cuda_params = "llcpp_reason_cuda_requires_nvidia", {} cuda_recommended = False elif not cc_f: cuda_key, cuda_params = "llcpp_reason_cuda_cc_unknown", {} cuda_recommended = False elif cc_f < 7.0: cuda_key, cuda_params = "llcpp_reason_cuda_old_gpu", {"cc": cc} cuda_recommended = False elif runtime_major not in (12, 13): cuda_key, cuda_params = "llcpp_reason_cuda_no_runtime", {} cuda_recommended = False else: # modern GPU + runtime but no AVX-512 β†’ CUDA wheels crash cuda_key, cuda_params = "llcpp_reason_cuda_no_avx512", {"cpu": cpu_name} cuda_recommended = False options.append({ "id": "cuda", "label_key": "llcpp_opt_cuda", "reason_key": cuda_key, "params": cuda_params, "available": cuda_available, "recommended": cuda_recommended, }) # Vulkan β€” viable for AMD/Intel GPUs (built without AVX-512, so it # also loads on the consumer CPUs where the CUDA wheels crash). vulkan_available = brand in ("amd", "intel") options.append({ "id": "vulkan", "label_key": "llcpp_opt_vulkan", "reason_key": "llcpp_reason_vulkan_ok" if vulkan_available else "llcpp_reason_vulkan_no_gpu", "params": {}, "available": vulkan_available, "recommended": vulkan_available and not cuda_available, }) return {"detected": detected, "options": options} @staticmethod def install_llama_cpp_python_gen(choice=None): """Install a matching llama-cpp-python package for this machine. choice ("auto" / "cpu" / "cuda" / "vulkan", or None = auto): the explicit build the user picked in the Settings popup. Auto still decides by hardware; a non-viable explicit pick degrades to CPU with a clear message (never a mismatched GPU wheel). For NVIDIA CUDA GPUs: - Detects CUDA version / compute capability. - Installs from abetlen pre-built CUDA wheel index (e.g. cu124, cu121, cu118). For CPU / unknown: - Installs standard CPU llama-cpp-python package from PyPI. Yields progress messages for UI streaming. """ status = HardwareManager.get_system_status() brand = status["gpu_brand"] cuda_ver = status["cuda_version"] runtime_major = HardwareManager.detect_installed_cuda_runtime_major() yield "πŸš€ Starting llama-cpp-python installation..." yield f"πŸ” Detected Hardware: GPU Brand = {brand.upper()}, CUDA Version = {cuda_ver or 'N/A'}" if runtime_major is not None: yield f"ℹ️ Detected installed CUDA runtime DLL family: cublas64_{runtime_major}.dll" # The ONLY signals that decide whether a CUDA wheel is safe here are # (a) the GPU's compute capability and (b) the CUDA runtime DLLs # actually installed on this PC. The NVIDIA driver's reported CUDA # version is NOT one of them (a modern driver can report CUDA 13 while # only a CUDA-12 runtime exists β€” a CUDA-13 wheel then fails to load), # and neither is torch.cuda.is_available() (a CPU-only torch build # simply cannot see the GPU at all, e.g. the Store package or any # machine whose torch got installed as the CPU build). Compute # capability is resolved independently of torch (torch β†’ nvidia-smi) # so the old-GPU guard below also fires on CPU-only builds. cc = _gpu_compute_capability() try: cc_f = float(cc) if cc else 0.0 except (TypeError, ValueError): cc_f = 0.0 gpu_name = _gpu_name() wheel_url = None # An explicit choice (cpu / cuda / vulkan β€” from the Settings popup) # overrides auto-detection. Every guard below still applies: a choice # the machine cannot actually run NEVER installs a broken wheel β€” it # degrades to the CPU build with a clear message, exactly like the # auto path (never a silent, mismatched GPU wheel). choice = (choice or "auto").lower() if choice not in ("auto", "cpu", "cuda", "vulkan"): yield f"❌ Unknown llama-cpp-python build '{choice}' (expected auto / cpu / cuda / vulkan)." return if choice == "cpu": yield "ℹ️ CPU build selected by the user." elif choice == "cuda": if ( brand == "nvidia" and cc_f >= 7.0 and runtime_major in (12, 13) and _cpu_supports_avx512() ): tag = "v0.3.34-cu130" if runtime_major >= 13 else "v0.3.34-cu124" wheel_url = ( f"https://github.com/abetlen/llama-cpp-python/releases/download/{tag}/" f"llama_cpp_python-0.3.34-py3-none-win_amd64.whl" ) yield f"ℹ️ NVIDIA CUDA build selected by the user ({tag})." else: yield ( "⚠️ The NVIDIA CUDA build is not usable on this machine " "(requires a modern NVIDIA GPU, an installed CUDA 12/13 runtime " "and an AVX-512 CPU). Falling back to the CPU build." ) elif choice == "vulkan": if brand in ("amd", "intel"): vulkan_url = _llama_cpp_vulkan_wheel_url() if vulkan_url: wheel_url = vulkan_url yield "ℹ️ Vulkan build selected by the user (AMD/Intel GPU)." else: yield ( "⚠️ The Vulkan prebuilt wheel is not available on this platform. " "Falling back to the CPU build." ) else: yield ( "⚠️ The Vulkan build needs an AMD or Intel GPU (detected " f"GPU brand: {brand or 'unknown'}). Falling back to the CPU build." ) elif brand == "nvidia": if cc_f and cc_f < 7.0: # Pascal (6.x) and older cannot run the CUDA kernels in any # current llama.cpp build β€” a CUDA wheel would import (if the # runtime DLLs happen to be present) but blow up on the first # real kernel launch. CPU is the only correct choice. yield ( f"⚠️ NVIDIA GPU '{gpu_name or 'unknown'}' (compute capability {cc}, Pascal or older) " "is too old for current llama.cpp CUDA kernels. " "Using CPU llama-cpp-python to keep the app stable." ) elif cc_f and cc_f >= 7.0 and runtime_major in (12, 13): # Modern GPU + a matching installed CUDA runtime: install the # wheel that links against the runtime DLLs actually present # (cublas64_12.dll β†’ cu124, cublas64_13.dll β†’ cu130) β€” BUT only # when the CPU can execute AVX-512. Those CUDA wheels are # compiled with AVX-512 code paths, and on Intel consumer CPUs # (no AVX-512 since Alder Lake, e.g. i7-14700F) EVERY model # load crashes with STATUS_ILLEGAL_INSTRUCTION (0xc000001d). # The CPU wheel below has no AVX-512 and loads fine; GPU # offload on such machines still works via the external # llama-server backend (per-architecture CPU DLL dispatch). if not _cpu_supports_avx512(): yield ( f"⚠️ CPU '{_cpu_name()}' does not support AVX-512, but the " "llama-cpp-python CUDA wheels are compiled with AVX-512 " "code paths and would crash loading any GGUF " "(STATUS_ILLEGAL_INSTRUCTION 0xc000001d). Installing the " "CPU wheel instead β€” GPU offload still works via the " "πŸ–₯️ llama-server backend." ) else: tag = "v0.3.34-cu130" if runtime_major >= 13 else "v0.3.34-cu124" wheel_url = ( f"https://github.com/abetlen/llama-cpp-python/releases/download/{tag}/" f"llama_cpp_python-0.3.34-py3-none-win_amd64.whl" ) elif cc_f and cc_f >= 7.0: # Modern GPU but no supported CUDA runtime DLLs on PATH (e.g. # driver-only gaming rigs β€” very common). A CUDA wheel cannot # load without the runtime it links against. yield ( "⚠️ Your GPU supports CUDA, but no matching CUDA runtime DLLs " "(cublas64_12.dll / cublas64_13.dll) were found on this PC, so a CUDA " "wheel could not load. Using the CPU llama-cpp-python package instead." ) else: # Compute capability could not be determined (torch is a # CPU-only build and nvidia-smi is unavailable). Installing a # CUDA wheel blind is exactly how broken installs happen β€” CPU # is the safe out-of-the-box default. yield ( "⚠️ Could not verify this NVIDIA GPU's compute capability, so a CUDA wheel " "could be mismatched. Using the safe CPU llama-cpp-python package instead " "(install a CUDA wheel manually if your GPU is supported)." ) elif brand in ("amd", "intel"): wheel_url = "https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34-vulkan/llama_cpp_python-0.3.34-py3-none-win_amd64.whl" try: if wheel_url: yield f"πŸ”— Found hardware-matched pre-built wheel: {wheel_url}" cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", wheel_url] else: cpu_url = _llama_cpp_cpu_wheel_url() if cpu_url: yield f"ℹ️ Using prebuilt CPU wheel for llama-cpp-python (avoids a source build): {cpu_url}" cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", cpu_url] else: yield "ℹ️ Using standard CPU/default PyPI package for llama-cpp-python." cmd = _pip_base_args() + ["--force-reinstall", "--no-cache-dir", "llama-cpp-python"] yield f"Running: {' '.join(cmd)}" process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, creationflags=CREATE_NO_WINDOW, ) for line in process.stdout: yield line.strip() process.wait() if process.returncode != 0 and wheel_url: yield f"⚠️ CUDA wheel install exited with code {process.returncode}. Retrying with the CPU wheel..." cpu_url = _llama_cpp_cpu_wheel_url() cmd_fallback = _pip_base_args() + ["--no-cache-dir", cpu_url or "llama-cpp-python"] yield f"Running: {' '.join(cmd_fallback)}" p2 = subprocess.Popen( cmd_fallback, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, creationflags=CREATE_NO_WINDOW, ) for line in p2.stdout: yield line.strip() p2.wait() process = p2 if process.returncode == 0: yield "✨ llama-cpp-python installation finished successfully!" try: import importlib # `sys` is already module-level; importing it here would shadow the global and break getattr(sys, 'frozen') above for mod_name in list(sys.modules.keys()): if mod_name == "llama_cpp" or mod_name.startswith("llama_cpp."): del sys.modules[mod_name] if "backend.llama_backend" in sys.modules: importlib.reload(sys.modules["backend.llama_backend"]) import backend.llama_backend as lb if not lb.LLAMA_CPP_AVAILABLE and wheel_url: yield "⚠️ Installed wheel still cannot import cleanly. Reinstalling the CPU llama-cpp-python package..." cpu_url = _llama_cpp_cpu_wheel_url() cmd_cpu = _pip_base_args() + [ "--force-reinstall", "--no-cache-dir", cpu_url or "llama-cpp-python"] yield f"Running: {' '.join(cmd_cpu)}" process_cpu = subprocess.Popen( cmd_cpu, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, creationflags=CREATE_NO_WINDOW, ) for line in process_cpu.stdout: yield line.strip() process_cpu.wait() if process_cpu.returncode != 0: yield f"❌ CPU fallback install failed with exit code {process_cpu.returncode}." return for mod_name in list(sys.modules.keys()): if mod_name == "llama_cpp" or mod_name.startswith("llama_cpp."): del sys.modules[mod_name] if "backend.llama_backend" in sys.modules: importlib.reload(sys.modules["backend.llama_backend"]) import backend.llama_backend as lb lb.LLAMA_CPP_AVAILABLE = True lb.LLAMA_CPP_GPU_AVAILABLE = lb._detect_llama_cpp_gpu_support() gpu_state = "GPU CUDA offload" if lb.LLAMA_CPP_GPU_AVAILABLE else "CPU mode" yield f"βœ… llama-cpp-python is ready ({gpu_state})!" except Exception as e: yield f"βœ… llama-cpp-python installed! (Note: backend state refresh notice: {e})" else: yield f"❌ llama-cpp-python installation failed with exit code {process.returncode}." except Exception as e: yield f"❌ Error during installation: {e}" # ────────────────────────────────────────────────────────────────── # Real GPU/PyTorch kernel-compatibility check # ────────────────────────────────────────────────────────────────── # `torch.cuda.is_available()` only checks that the CUDA *driver* and # runtime can be initialized β€” it does NOT mean this specific PyTorch # build actually ships compiled kernels for this specific GPU's compute # capability. PyTorch wheels only include kernels ("sm_XX" binaries) for # a fixed list of architectures; older cards (e.g. Pascal/sm_6x, # Maxwell/sm_5x) have been dropped from recent stable releases even # though `torch.cuda.is_available()` still happily reports True and the # model even *loads* onto the device β€” it only blows up the moment a # real CUDA kernel is launched (e.g. during model loading's # tie_weights()), with "CUDA error: no kernel image is available for # execution on the device". # # This is exactly the gap that let a machine with e.g. an NVIDIA GeForce # MX230 (compute capability 6.1) silently get a "cuda-capable" verdict # from is_available(), install a GPU build via SETUP.ps1, and then crash # on first real use. SETUP.ps1 now does a real-kernel smoke test right # after installing torch (mirroring the same pattern already used there # for llama-cpp-python) and falls back to a CPU wheel automatically if it # fails β€” but a user could still end up here via a manual `pip install # torch` re-install, a different Python environment, a driver/GPU swap, # etc. So this same check is repeated here at app-import time as a # runtime safety net: DEVICE only resolves to "cuda" if a real kernel # actually runs successfully, not just because is_available() said so. # ────────────────────────────────────────────────────────────────── def _detect_gpu_kernel_incompatibility() -> Optional[dict]: """Best-effort: if a CUDA GPU is visible but this torch build has no compiled kernels for its compute capability, return a small dict with enough detail for the UI to build a clear, actionable warning (gpu_name, compute capability, and the archs this torch build DOES support). Returns None if the GPU is fully usable (or there's no GPU at all β€” that's a normal CPU-only setup, not a warning-worthy state). """ if not torch.cuda.is_available(): return None try: gpu_name = torch.cuda.get_device_name(0) cc_major, cc_minor = torch.cuda.get_device_capability(0) cc_str = f"{cc_major}.{cc_minor}" try: arch_list = torch.cuda.get_arch_list() except Exception: arch_list = [] archs_str = ", ".join(a.replace("sm_", "") for a in arch_list) if arch_list else "unknown" # The real test: actually launch a kernel, not just check # is_available(). Wrapped so a torch UserWarning about the CC # mismatch (torch itself often prints one on this exact call) # doesn't spam the console a second time here β€” SETUP.ps1 / # the terminal already shows torch's own version of this warning; # this function only needs the pass/fail result. with warnings.catch_warnings(): warnings.simplefilter("ignore") try: x = torch.randn(8, device="cuda") _ = x @ x torch.cuda.synchronize() kernel_ok = True except Exception: kernel_ok = False if kernel_ok: return None return { "gpu_name": gpu_name, "compute_capability": cc_str, "supported_archs": archs_str, } except Exception: # Detection itself failing shouldn't block startup or produce a # false warning β€” treat as "couldn't determine", not "broken". return None def _xpu_kernel_works() -> bool: """Real-kernel check for Intel XPU (torch.xpu). Like the CUDA path, is_available() can report True while this torch build/driver can't actually run kernels (or has no usable device); DEVICE must only resolve to "xpu" after a real kernel launches successfully. """ if not (hasattr(torch, "xpu") and torch.xpu.is_available()): return False try: with warnings.catch_warnings(): warnings.simplefilter("ignore") x = torch.randn(8, device="xpu") _ = x @ x torch.xpu.synchronize() return True except Exception: return False # ── Resolved once at import time ──────────────────────────────────── _GPU_INCOMPATIBILITY_INFO = _detect_gpu_kernel_incompatibility() if torch.cuda.is_available() and _GPU_INCOMPATIBILITY_INFO is None: DEVICE = "cuda" elif _xpu_kernel_works(): DEVICE = "xpu" elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): DEVICE = "mps" else: DEVICE = "cpu" if _GPU_INCOMPATIBILITY_INFO is not None: print( f"[Hardware] WARNING: GPU '{_GPU_INCOMPATIBILITY_INFO['gpu_name']}' " f"(compute capability {_GPU_INCOMPATIBILITY_INFO['compute_capability']}) " f"was detected, but this PyTorch build has no compiled kernels for it " f"(supports: {_GPU_INCOMPATIBILITY_INFO['supported_archs']}). " f"Falling back to CPU β€” see the warning banner in the UI for how to fix this." ) def get_gpu_incompatibility_info() -> Optional[dict]: """Read-only accessor for ui.py: returns the dict built at import time (see _detect_gpu_kernel_incompatibility() above) describing a detected-but-unusable GPU, or None if the GPU is fine / there's no GPU. Used to render a one-time warning banner in the UI so a non-technical user isn't left guessing why everything is "running on CPU" despite clearly having an NVIDIA card β€” the banner explains it and points at the fix. """ return _GPU_INCOMPATIBILITY_INFO TORCH_DTYPE = torch.float16 if DEVICE != "cpu" else torch.float32 def refresh_system_ui(): status = HardwareManager.get_system_status() return ( "πŸ”„ Status Refreshed", # Report the DEVICE this app is ACTUALLY using (resolved once at # import time above, already accounting for the real-kernel # compatibility check) rather than status["current_device"], which # only reflects torch.cuda.is_available() and would misleadingly # say "CUDA" even on a machine that silently fell back to CPU due # to a GPU/PyTorch-build compute-capability mismatch. DEVICE.upper(), status["cuda_version"] or "N/A", "βœ… Yes" if status["torch_cuda_available"] else "❌ No", "" # Clear logs ) def fix_system_ui_generator(): status = HardwareManager.get_system_status() yield ( "πŸš€ Starting fix...", status["current_device"].upper(), status["cuda_version"] or "N/A", "βœ… Yes" if status["torch_cuda_available"] else "❌ No", "Starting..." ) for msg, dev, log in HardwareManager.fix_environment_gen(): yield ( msg, dev.upper(), status["cuda_version"] or "N/A", "βœ… Yes" if status["torch_cuda_available"] else "❌ No", log )
"""
hardware.py β€” GPU/device detection and the "Fix Environment" self-repair
helper (installs a hardware-matched PyTorch build at runtime).
"""
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Optional
import torch
import warnings
# Windows flag to suppress creating a console window for spawned subprocesses
CREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0
# ── Frozen-build pip helpers ───────────────────────────────────────────────
# In the PyInstaller/Store build sys.executable is the app exe (not Python),
# so we ship a minimal bundled Python+pip alongside the app and use it for
# all runtime pip installs (GPU PyTorch, llama-cpp-python, agent packages).
# Packages install into user_data/packages/ (writable, isolated from the
# frozen bundle) and the startup hook (pyi_rth_smolagents_source.py) adds
# that directory to sys.path + torch/lib to os.environ["PATH"].
FROZEN_PYTHON_EXE: Optional[str] = None # resolved once, cached
def _find_frozen_python() -> Optional[str]:
"""Locate the bundled Python interpreter shipped with the frozen app.
The build pipeline (build_standalone.py) downloads the Python embeddable
package, adds pip, and places it in <app>/python/. This function finds
that interpreter so pip-based installs work in the packaged build.
Returns the path to python.exe or None when unavailable.
"""
global FROZEN_PYTHON_EXE
if FROZEN_PYTHON_EXE is not None:
return FROZEN_PYTHON_EXE
if not getattr(sys, "frozen", False):
return None
# APP_ROOT = parent of internal/ (the PyInstaller contents_directory).
app_root = Path(sys._MEIPASS).parent
candidate = app_root / "python" / "python.exe"
if candidate.is_file():
FROZEN_PYTHON_EXE = str(candidate)
return FROZEN_PYTHON_EXE
return None
def _frozen_pip_target() -> str:
"""Return the --target directory for pip installs in the frozen build.
Packages land in user_data/packages/ which the startup hook adds to
sys.path (and torch/lib to os.environ["PATH"]).
"""
from backend.paths import user_data_dir
return str(user_data_dir() / "packages")
def _pip_base_args() -> list:
"""Return the base pip-install command prefix.
In the frozen build the bundled Python+pip is used and every install
targets user_data/packages/ (--target) for isolation. In dev/venv
builds the normal sys.executable is used.
"""
frozen_py = _find_frozen_python()
if frozen_py:
return [frozen_py, "-m", "pip", "install", "--target", _frozen_pip_target()]
return [sys.executable, "-m", "pip", "install"]
# Canonical GPU-detection helpers live in llama_health (which never imports
# backend modules, so there is no import cycle). Reuse them here instead of
# maintaining a second copy β€” the compute-capability signal decides whether
# any CUDA wheel can actually run on this machine.
from backend.llama_health import _gpu_compute_capability, _gpu_name
def _llama_cpp_cpu_wheel_url() -> Optional[str]:
"""Prebuilt CPU wheel for llama-cpp-python on Windows (any Python 3.x).
`pip install llama-cpp-python` without an explicit wheel URL resolves to
the sdist and builds from source β€” which needs a C/C++ toolchain that most
end-user PCs (and always the packaged Microsoft Store build) don't have,
so the install fails out of the box. Every CPU fallback must therefore
install this prebuilt wheel instead. Returns None on non-Windows, where
the plain PyPI package remains the fallback."""
if sys.platform != "win32":
return None
return (
"https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34/"
"llama_cpp_python-0.3.34-py3-none-win_amd64.whl"
)
def _llama_cpp_vulkan_wheel_url() -> Optional[str]:
"""Prebuilt Vulkan wheel for llama-cpp-python on Windows β€” hardware