mirror of
https://github.com/IgorAherne/Spellcast3d.git
synced 2026-12-01 08:06:27 -10:00
269 lines
12 KiB
Python
269 lines
12 KiB
Python
"""NVIDIA GPU detection through nvidia-smi. STDLIB ONLY (used by the installer).
|
|
|
|
Facts this module encodes (verified while designing Spellcast3D):
|
|
- torch 2.8.0+cu128 on Windows ships kernels for sm_61..sm_120, so Forge runs
|
|
on everything from a GTX 1080 to an RTX 50xx with that single build.
|
|
- Pixal3D runs from compute capability 6.1 (GTX 10xx): on sm_80+ (RTX 30xx and newer) as it was made (bf16 flows,
|
|
flash_attn, SageAttention, natten, Triton); below that the fork's precision profile (pixal3d/modules/precision.py,
|
|
round L) runs the flows in fp16 (Turing: sm_70-sm_79) or fp32 (Pascal), its attention on torch's SDPA,
|
|
its int8 GEMMs through cuBLASLt, NAF in plain torch and the decoders on spconv - every compiled piece those cards
|
|
need (cumesh, flex_gemm's CUDA part, o_voxel, nvdiffrast, spconv, torch itself) ships with sm_61+ kernels.
|
|
Measured on an RTX 2060 Super and a GTX 1080 (Linux pods); Windows on those cards follows the same wheels.
|
|
- The retopology tools LATO.2 and TriFlow are allowed from compute capability 6.1 (GTX 10xx):
|
|
their compiled parts (spconv, torchsparse, o_voxel, nvdiffrast) have sm_61 kernels, and their
|
|
launchers fall back where the attention wheels have none (flash_attn is sm_80+, xformers sm_75+):
|
|
torch's SDPA through a flash_attn shim, xformers on 7.5, torchsparse's GatherScatter dataflow
|
|
below 7.5, fp16 / fp32 instead of bf16. Only sm_86 was tried; below sm_80 it is untested.
|
|
- Qwen-Image 2.1 runs on Spellcast3D's own CUDA 12.8 build of stable-diffusion.cpp (no PyTorch; install/sdcpp.py),
|
|
made for the official release's list of compute capabilities, 6.1..12.0 (sm_61;70;75;80;86;89;90;100;120, each
|
|
with its PTX): GTX 10xx and newer. Only sm_86 (an RTX 3060) was run; the other generations compile.
|
|
- cu128 wheels need an NVIDIA driver >= 570.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
from dataclasses import asdict, dataclass
|
|
from pathlib import Path
|
|
|
|
PIXAL3D_MIN_CC = 6.1
|
|
LATO2_MIN_CC = 6.1
|
|
TRIFLOW_MIN_CC = 6.1
|
|
QWEN_MIN_CC = 6.1
|
|
MIN_DRIVER = 570.0
|
|
MIN_CC = min(PIXAL3D_MIN_CC, LATO2_MIN_CC, TRIFLOW_MIN_CC, QWEN_MIN_CC) # below it no tool runs
|
|
# What an "8 GB" card reports: Spellcast3D is made for that much video memory and more.
|
|
MADE_FOR_VRAM_MB = 7900
|
|
# Below this compute capability (GTX 10xx) every stage computes in fp32, several times slower than on any RTX.
|
|
RTX_FROM_CC = 7.0
|
|
|
|
|
|
@dataclass
|
|
class GpuInfo:
|
|
index: int
|
|
name: str
|
|
compute_cap: float # e.g. 8.6
|
|
vram_total_mb: int
|
|
vram_used_mb: int
|
|
driver_version: str # e.g. "596.36"
|
|
uuid: str = "" # e.g. "GPU-5b2e...": the card itself, whatever its index (empty when unknown)
|
|
|
|
@property
|
|
def sm(self) -> str:
|
|
major, _, minor = f"{self.compute_cap:.1f}".partition(".")
|
|
return f"sm_{major}{minor}"
|
|
|
|
@property
|
|
def driver_major(self) -> float:
|
|
try:
|
|
return float(".".join(self.driver_version.split(".")[:2]))
|
|
except ValueError:
|
|
return 0.0
|
|
|
|
def to_dict(self) -> dict:
|
|
d = asdict(self)
|
|
d["sm"] = self.sm
|
|
return d
|
|
|
|
|
|
def _nvidia_smi() -> str | None:
|
|
found = shutil.which("nvidia-smi")
|
|
if found:
|
|
return found
|
|
for candidate in (Path(r"C:\Windows\System32\nvidia-smi.exe"),
|
|
Path(r"C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi.exe")):
|
|
if candidate.exists():
|
|
return str(candidate)
|
|
return None
|
|
|
|
|
|
def query_gpus(timeout: float = 10.0) -> list[GpuInfo]:
|
|
"""All NVIDIA GPUs, or [] when there is no driver / no nvidia-smi."""
|
|
exe = _nvidia_smi()
|
|
if exe is None:
|
|
return []
|
|
fields = "index,name,compute_cap,memory.total,memory.used,driver_version,uuid"
|
|
try:
|
|
out = subprocess.run(
|
|
[exe, f"--query-gpu={fields}", "--format=csv,noheader,nounits"],
|
|
capture_output=True, text=True, timeout=timeout,
|
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return []
|
|
if out.returncode != 0:
|
|
return []
|
|
gpus: list[GpuInfo] = []
|
|
for line in out.stdout.splitlines():
|
|
parts = [p.strip() for p in line.split(",")]
|
|
if len(parts) not in (6, 7):
|
|
continue
|
|
try:
|
|
gpus.append(GpuInfo(
|
|
index=int(parts[0]), name=parts[1], compute_cap=float(parts[2]),
|
|
vram_total_mb=int(float(parts[3])), vram_used_mb=int(float(parts[4])),
|
|
driver_version=parts[5], uuid=parts[6] if len(parts) == 7 else "",
|
|
))
|
|
except ValueError:
|
|
continue
|
|
return gpus
|
|
|
|
|
|
AUTO = "auto"
|
|
# Under this name a pick goes to the programs Spellcast3D starts, beside CUDA_VISIBLE_DEVICES: one that finds the two
|
|
# alike (the installer the hub starts) knows the card is Spellcast3D's pick and not a setting of the artist's own,
|
|
# and keeps it - the hub and what it starts are on one card.
|
|
HANDED_DOWN = "SPELLCAST_GRAPHICS_CARD"
|
|
|
|
|
|
def _handed_down() -> str:
|
|
"""The card the program that started this one picked ("" when none did)."""
|
|
handed = os.environ.get(HANDED_DOWN, "").strip()
|
|
return handed if handed and handed == os.environ.get("CUDA_VISIBLE_DEVICES", "").strip() else ""
|
|
|
|
|
|
def own_devices() -> str:
|
|
"""The artist's own CUDA_VISIBLE_DEVICES ("" without one): it decides, and the tools get it as it is."""
|
|
return "" if _handed_down() else os.environ.get("CUDA_VISIBLE_DEVICES", "").strip()
|
|
|
|
|
|
def wanted_card() -> str:
|
|
"""Which of a PC's cards is asked for: the one handed down by the program that started this one, else the first
|
|
the artist's own CUDA_VISIBLE_DEVICES names (the tools' cuda:0; an nvidia-smi number or a card's UUID), else
|
|
spellcast3d-config.ini's graphics_card (AUTO or a number)."""
|
|
own = _handed_down() or own_devices()
|
|
if own:
|
|
return own.split(",")[0].strip()
|
|
from . import config # (it imports the installer's model lists: only when a card is asked for)
|
|
|
|
return config.graphics_card()
|
|
|
|
|
|
def _rank(card: GpuInfo) -> tuple[bool, bool, bool, int, float]:
|
|
"""AUTO's order among a PC's cards, the best last: one the tools support at all; one with the video memory
|
|
Spellcast3D is made for; an RTX before a GTX 10xx; then the most video memory, then the newer card."""
|
|
return (card.compute_cap >= MIN_CC, card.vram_total_mb >= MADE_FOR_VRAM_MB, card.compute_cap >= RTX_FROM_CC,
|
|
card.vram_total_mb, card.compute_cap)
|
|
|
|
|
|
def pick(gpus: list[GpuInfo], wanted: str = AUTO) -> GpuInfo | None:
|
|
"""The card the tools use among a PC's: the one `wanted` names (nvidia-smi's number, or a UUID as CUDA takes
|
|
it: any case, or its beginning) when it is there, else the best by _rank - the first of equals, so a PC with one
|
|
card, or with twins, keeps card 0."""
|
|
asked = wanted.strip().lower()
|
|
for card in gpus:
|
|
if asked == str(card.index) or (asked.startswith("gpu-") and card.uuid.lower().startswith(asked)):
|
|
return card
|
|
return max(gpus, key=_rank, default=None)
|
|
|
|
|
|
# The card picked for this process, once nvidia-smi has answered: (what tells it among the PC's cards, whether the PC
|
|
# has several). Decided ONCE and kept: the card a tool was started on, the page's card, the adapters' and the
|
|
# installer's memory rules must be one card, whatever the config file says later (the page then asks for a new
|
|
# start: server.ConfigWatch).
|
|
_decided: tuple[str, bool] | None = None
|
|
|
|
|
|
def _identity(card: GpuInfo) -> str:
|
|
return card.uuid or f"#{card.index}"
|
|
|
|
|
|
def _decide(gpus: list[GpuInfo]) -> tuple[str, bool] | None:
|
|
global _decided
|
|
if _decided is None and gpus:
|
|
card = pick(gpus, wanted_card())
|
|
assert card is not None
|
|
_decided = (_identity(card), len(gpus) > 1)
|
|
return _decided
|
|
|
|
|
|
def primary_gpu() -> GpuInfo | None:
|
|
"""The GPU the tools use, as it is now (its free memory): the process's one picked card (tools_env shows the
|
|
tools that card alone). None: no card answers, or the picked one is gone."""
|
|
gpus = query_gpus()
|
|
decided = _decide(gpus)
|
|
return next((card for card in gpus if decided is not None and _identity(card) == decided[0]), None)
|
|
|
|
|
|
def tools_env() -> dict[str, str]:
|
|
"""What tells a tool's process which card to use, for its environment: nothing on a PC with one card. With
|
|
several, CUDA is shown the picked card alone, by its UUID - CUDA numbers cards by speed, nvidia-smi by slot, so
|
|
a number would not do. An artist's own CUDA_VISIBLE_DEVICES stands, read in nvidia-smi's order."""
|
|
if own_devices():
|
|
return {"CUDA_DEVICE_ORDER": "PCI_BUS_ID"}
|
|
decided = _decided or _decide(query_gpus())
|
|
if decided is None or not decided[1] or decided[0].startswith("#"):
|
|
return {}
|
|
return {"CUDA_VISIBLE_DEVICES": decided[0], HANDED_DOWN: decided[0]}
|
|
|
|
|
|
def pixal3d_supported(gpu: GpuInfo | None) -> tuple[bool, str]:
|
|
if gpu is None:
|
|
return False, "No NVIDIA GPU was found. Pixal3D needs an NVIDIA GTX 1060 or newer."
|
|
if gpu.compute_cap < PIXAL3D_MIN_CC:
|
|
return False, (f"{gpu.name} ({gpu.sm}) is not supported by Pixal3D: it needs a "
|
|
f"GTX 1060 or newer (compute capability 6.1+).")
|
|
return True, ""
|
|
|
|
|
|
def pixal3d_card_env(gpu: GpuInfo | None) -> dict[str, str]:
|
|
"""What Pixal3D's processes are told about the card: PIXAL3D_CARD_SM (its compute capability as two digits), so
|
|
that a process which cannot see the card (the installer's copies of the flow models, made with the card hidden)
|
|
still takes the card's precision profile (pixal3d/modules/precision.py); below sm_70, DISABLE_ADDMM_CUDA_LT=1,
|
|
which keeps torch's fused linear-with-bias off cuBLASLt, whose fp32 SGEMM reads out of bounds on a GTX 1080 (an
|
|
illegal memory access a few seconds into the first flow; the fork's precision profile sets it as well)."""
|
|
if gpu is None:
|
|
return {}
|
|
env = {"PIXAL3D_CARD_SM": gpu.sm[3:]}
|
|
if gpu.compute_cap < 7.0:
|
|
env["DISABLE_ADDMM_CUDA_LT"] = "1"
|
|
return env
|
|
|
|
|
|
def lato2_supported(gpu: GpuInfo | None) -> tuple[bool, str]:
|
|
return _retopo_supported(gpu, "LATO.2", LATO2_MIN_CC)
|
|
|
|
|
|
def triflow_supported(gpu: GpuInfo | None) -> tuple[bool, str]:
|
|
return _retopo_supported(gpu, "TriFlow", TRIFLOW_MIN_CC)
|
|
|
|
|
|
def _retopo_supported(gpu: GpuInfo | None, name: str, min_cc: float) -> tuple[bool, str]:
|
|
if gpu is None:
|
|
return False, (f"No NVIDIA GPU was found. {name} needs an NVIDIA GTX 1060 or newer; Instant Meshes "
|
|
f"(on the CPU) still makes clean meshes.")
|
|
if gpu.compute_cap < min_cc:
|
|
# plain words for the artist (the page shows it on the method's button); the log has gpu.sm
|
|
return False, (f"Your graphics card ({gpu.name}) is too old for {name}: it needs a GTX 1060 or newer. "
|
|
f"Instant Meshes still makes clean meshes.")
|
|
return True, ""
|
|
|
|
|
|
def qwen_supported(gpu: GpuInfo | None) -> tuple[bool, str]:
|
|
# No NVIDIA GPU is final for this PC (recorded as unsupported, re-checked at each start), as for Forge.
|
|
if gpu is None:
|
|
return False, ("No NVIDIA graphics card was found (or its driver is not installed). Qwen-Image 2.1 needs "
|
|
"one to make images; you can still bring your own images. If this PC has an NVIDIA card, "
|
|
"install its latest driver from https://www.nvidia.com/drivers and start Spellcast3D again: "
|
|
"Qwen-Image 2.1 is then installed by itself.")
|
|
if gpu.compute_cap < QWEN_MIN_CC:
|
|
return False, (f"Your graphics card ({gpu.name}) is too old for Qwen-Image 2.1: it needs a GTX 1060 or newer. "
|
|
f"You can still bring your own images.")
|
|
return True, ""
|
|
|
|
|
|
def driver_ok(gpu: GpuInfo | None) -> tuple[bool, str]:
|
|
if gpu is None:
|
|
return False, "No NVIDIA GPU / driver detected."
|
|
if gpu.driver_major < MIN_DRIVER:
|
|
return False, (f"NVIDIA driver {gpu.driver_version} is too old; version {MIN_DRIVER:.0f} "
|
|
f"or newer is required. Please update your GPU driver.")
|
|
return True, ""
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import json
|
|
print(json.dumps([g.to_dict() for g in query_gpus()], indent=2))
|