diff --git a/electron/pysetup.cjs b/electron/pysetup.cjs index a9d8537..75414f5 100644 --- a/electron/pysetup.cjs +++ b/electron/pysetup.cjs @@ -10,7 +10,10 @@ // - Mesh Tools (python-server): always provisioned. CPU only. // - Rigging (skintokens): opt-in. Heavy (torch + flash-attn + model) and needs // an NVIDIA GPU; the setup reuses the service's own Python helpers -// (select_flash_attn.py / download_wheel.py / download.py). +// (select_flash_attn.py / download_wheel.py / download.py). Windows and Linux +// only — flash-attn comes from a prebuilt wheel curated PER PLATFORM +// (flash_attention_windows.txt / flash_attention_linux.txt) because building +// it from source takes ~an hour either way. macOS has no CUDA and is refused. // // Everything is async and streams output to an onProgress callback; nothing // blocks the Electron main-process event loop. @@ -21,6 +24,7 @@ const os = require('node:os'); const { spawn, spawnSync } = require('node:child_process'); const IS_WIN = process.platform === 'win32'; +const IS_MAC = process.platform === 'darwin'; const PYVER = '3.13'; const UV_EXE = IS_WIN ? 'uv.exe' : 'uv'; @@ -192,6 +196,11 @@ async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) { // downloaded there; rig_server.py chdirs to this same dir at launch (via // RIGTOOLS_DATA_DIR) so its relative weight lookups resolve here. async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress }) { + // Rigging needs an NVIDIA GPU. Say so up front rather than failing several GB + // into a torch install that has no macOS CUDA build to find. + if (IS_MAC) { + throw new Error('Rigging (Auto Rig) needs an NVIDIA GPU (CUDA), which macOS does not provide. The rest of the app works normally.'); + } const vp = venvPython(venvDir); const env = process.env; const modelDir = dataDir || serviceDir; @@ -214,6 +223,9 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress }) ], (e) => onProgress(scaled(e, 0, 0.4))); // Select the flash-attn wheel + matching torch for this machine's CUDA. + // select_flash_attn.py picks the table for THIS platform (win_amd64 wheels from + // flash_attention_windows.txt, linux_x86_64 from flash_attention_linux.txt) — + // a wheel from the wrong table is rejected outright by uv at install time. onProgress({ kind: 'phase', phase: 'Selecting CUDA build', pct: 0.4 }); const sel = await runStream(vp, ['select_flash_attn.py'], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); let wheel = null, torchArgs = null; @@ -222,29 +234,39 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress }) else if (line.startsWith('TORCHARGS=')) torchArgs = line.slice(10).trim(); } - // Install torch (curated per-wheel command, or a sane default). + // No match -> no rigging. Bail BEFORE the torch download: flash-attn is a hard + // requirement (src/model/tokenrig.py imports it unguarded, so the service cannot + // even load without it), and building it from source takes ~an hour on every + // platform. Pulling multi-GB of torch on the way to a certain failure is waste. + if (!wheel || !torchArgs) { + throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA (see details). Rigging is unavailable on this machine.'); + } + + // Install torch with the curated per-wheel command, ABI-matched to the wheel. onProgress({ kind: 'phase', phase: 'Installing PyTorch', pct: 0.45 }); - const torchInstall = torchArgs - ? torchArgs.split(/\s+/) - : ['torch==2.7.0', 'torchvision==0.22.0', 'torchaudio==2.7.0', '--index-url', 'https://download.pytorch.org/whl/cu128']; { - const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchInstall], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchArgs.split(/\s+/)], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); if (r.code !== 0) throw new Error(`PyTorch install failed (exit ${r.code}).`); } - // flash-attn — download the prebuilt wheel via the HF client, then install it. - if (wheel) { - onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.65 }); + // flash-attn — download the prebuilt wheel first (Hugging Face Xet URLs 403 for + // pip and need the HF client; GitHub release assets are plain URLs), install it, + // then PROVE it loads: a wheel built against a different torch ABI installs + // cleanly and only dies at `import flash_attn` with `undefined symbol: _ZN3c10…`. + // Catching that here beats surfacing it after the multi-GB checkpoint download. + onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.6 }); + { const dl = await runStream(vp, ['download_wheel.py', wheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); const localWheel = dl.stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop(); - if (dl.code === 0 && localWheel) { - const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); - if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.'); - } else { - throw new Error('flash-attn download failed. Rigging cannot start without it.'); - } - } else { - throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA. Rigging is unavailable.'); + if (dl.code !== 0 || !localWheel) throw new Error('flash-attn download failed. Rigging cannot start without it.'); + const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.'); + } + onProgress({ kind: 'phase', phase: 'Verifying flash-attn', pct: 0.72 }); + { + const probe = 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)'; + const r = await runStream(vp, ['-c', probe], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) }); + if (r.code !== 0) throw new Error('flash-attn installed but will not import — most likely a torch ABI mismatch with the selected wheel (see details). Rigging cannot start.'); } // Model checkpoints (large; downloaded into the WRITABLE data dir). diff --git a/electron/setup.html b/electron/setup.html index bc2f27a..ee1182e 100644 --- a/electron/setup.html +++ b/electron/setup.html @@ -83,7 +83,7 @@ Rigging (Auto Rig) optional · NVIDIA GPU, large download - + @@ -109,6 +109,13 @@ const logEl = $('#log'); const errEl = $('#err'); + // Rigging needs CUDA, so it exists on Windows and Linux only. Hide the option on + // macOS rather than offering an install that cannot succeed. (An unchecked box + // reads as false in runInstall, so nothing else needs to know.) + if ((window.genStudioDesktop && window.genStudioDesktop.platform) === 'darwin') { + $('#svc-rigging').style.display = 'none'; + } + function setRow(service, { state, phase, pct }) { const row = rows[service]; if (!row) return; diff --git a/thirdparty/skintokens/flash_attention_linux.txt b/thirdparty/skintokens/flash_attention_linux.txt new file mode 100644 index 0000000..99fb0d0 --- /dev/null +++ b/thirdparty/skintokens/flash_attention_linux.txt @@ -0,0 +1,3 @@ +Torch;Cuda;Link;PyTorchLink +2.13.0;12.6.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu126torch2.13-cp313-cp313-linux_x86_64.whl;pip3 install torch~=2.13.0 torchvision --index-url https://download.pytorch.org/whl/cu126 +2.13.0;13.0.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp313-cp313-linux_x86_64.whl;pip3 install torch~=2.13.0 torchvision diff --git a/thirdparty/skintokens/run_server.sh b/thirdparty/skintokens/run_server.sh index b51506e..795c6ec 100644 --- a/thirdparty/skintokens/run_server.sh +++ b/thirdparty/skintokens/run_server.sh @@ -6,12 +6,18 @@ # # On first run it uses `uv` to provision a pinned standalone Python (see # .python-version -> 3.13) and installs the SkinTokens requirements, torch, a -# flash-attn wheel, and the model checkpoints. Unlike Windows (which needs the -# curated flash_attention_windows.txt wheels), Linux gets flash-attn straight -# from pip, which resolves a prebuilt wheel for the installed torch/CUDA/Python -# (or builds it — needs the CUDA toolkit + ninja). uv is auto-installed if absent. +# flash-attn wheel, and the model checkpoints. Like Windows, Linux installs +# flash-attn from a curated prebuilt wheel (flash_attention_linux.txt) rather than +# `pip install flash-attn`, which compiles from source and takes about an hour. +# uv is auto-installed if absent. # -# Env overrides: RIGTOOLS_PORT/HOST, RIGTOOLS_SKIP_FLASH=1, RIGTOOLS_SKIP_MODEL=1. +# Env overrides: +# RIGTOOLS_PORT / RIGTOOLS_HOST bind address +# RIGTOOLS_CUDA=12.6 force the CUDA build to target (skip nvidia-smi) +# RIGTOOLS_SKIP_FLASH=1 don't install flash-attn +# RIGTOOLS_BUILD_FLASH=1 if no curated wheel matches, build from source +# instead of giving up (~1 hour, needs nvcc+ninja) +# RIGTOOLS_SKIP_MODEL=1 don't download the model checkpoints set -euo pipefail cd "$(dirname "$0")" PYVER=3.13 @@ -42,22 +48,70 @@ if [ ! -x ".venv/bin/python" ]; then # shellcheck disable=SC1091 source .venv/bin/activate + # --- Pick a prebuilt flash-attn wheel + its matching torch install ---------- + # select_flash_attn.py picks the table for this platform (flash_attention_linux.txt + # here) and, on a CUDA match, prints: + # WHEEL= + # TORCHARGS= + # Prints nothing on no match. Python is pinned to 3.13 by uv, so the wheels (all + # cp313) always fit; only CUDA has to be matched. + echo + echo "Detecting CUDA to select a flash-attn wheel..." + WHEEL="" + TORCHARGS="" + while IFS= read -r line; do + case "$line" in + WHEEL=*) WHEEL="${line#WHEEL=}" ;; + TORCHARGS=*) TORCHARGS="${line#TORCHARGS=}" ;; + esac + done < <(python select_flash_attn.py) + echo echo "Installing SkinTokens requirements..." "$UV" pip install -r requirements.txt - # torch AFTER requirements so it overrides the torch `lightning` pulls in. On - # Linux the default PyPI torch wheels bundle CUDA, so no custom index is needed. + # torch AFTER requirements so it overrides the torch `lightning` pulls in. The + # curated TORCHARGS pins torch to the version the flash-attn wheel was built + # against, so the ABI matches. On Linux the PyPI torch wheels bundle CUDA, so a + # row may legitimately carry no --index-url. echo - echo "Installing torch (CUDA build)..." - "$UV" pip install torch torchvision torchaudio + if [ -n "$TORCHARGS" ]; then + echo "Installing torch: $TORCHARGS" + # shellcheck disable=SC2086 -- curated arg list; word-splitting is intended + "$UV" pip install $TORCHARGS + else + echo "No matching prebuilt flash-attn wheel -- installing default torch (CUDA build from PyPI)..." + "$UV" pip install torch torchvision + fi + # --- flash-attn ------------------------------------------------------------- echo if [ -n "${RIGTOOLS_SKIP_FLASH:-}" ]; then echo "RIGTOOLS_SKIP_FLASH set -- skipping flash-attn." + elif [ -n "$WHEEL" ]; then + echo "Downloading + installing prebuilt flash-attn wheel..." + # Fetch to a local path first: `pip install ` 403s on Hugging Face + # Xet-backed files. GitHub release assets go over plain urllib. + if FA_WHEEL="$(python download_wheel.py "$WHEEL" | tail -n 1)" && [ -n "$FA_WHEEL" ]; then + "$UV" pip install "$FA_WHEEL" || echo "[warn] flash-attn install failed; continuing without it." + else + echo "[warn] flash-attn download failed; continuing without it." + fi + elif [ -n "${RIGTOOLS_BUILD_FLASH:-}" ]; then + echo "No curated wheel matched -- building flash-attn from source (this takes ~an hour)..." + "$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn build failed; continuing without it." else - echo "Installing flash-attn (prebuilt wheel if available, else builds from source)..." - "$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn install failed; continuing without it." + echo "[warn] No prebuilt flash-attn wheel matched this CUDA; flash-attn was NOT installed." + echo " rig_server.py cannot import without it. Either add a row for your" + echo " CUDA/torch to flash_attention_linux.txt, or build from source with:" + echo " RIGTOOLS_BUILD_FLASH=1 ./run_server.sh # ~1 hour, needs nvcc + ninja" + fi + + # A wheel built against a different torch ABI installs cleanly and only fails at + # import ("undefined symbol: _ZN3c10..."), so check now rather than mid-rig. + if [ -z "${RIGTOOLS_SKIP_FLASH:-}" ]; then + python -c 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)' \ + || echo "[warn] flash-attn does not import -- likely a torch ABI mismatch with the selected wheel." fi echo diff --git a/thirdparty/skintokens/select_flash_attn.py b/thirdparty/skintokens/select_flash_attn.py index f58488e..0e89638 100644 --- a/thirdparty/skintokens/select_flash_attn.py +++ b/thirdparty/skintokens/select_flash_attn.py @@ -1,50 +1,63 @@ """Pick the prebuilt flash-attn wheel + matching torch install for this machine. -Building flash-attn from source on Windows takes ages, so we prefer a -precompiled wheel. ``flash_attention_windows.txt`` lists, per row: +Building flash-attn from source takes ~an hour on BOTH Windows and Linux, so we +always prefer a precompiled wheel. There is one curated table per platform — +``flash_attention_windows.txt`` (win_amd64 wheels) and +``flash_attention_linux.txt`` (linux_x86_64 wheels) — and this script picks the +table matching the host. Each lists, per row: Torch;Cuda;Link;PyTorchLink - │ │ │ └ the exact `pip install torch... --index-url ...` command + │ │ │ └ the exact `pip install torch... [--index-url ...]` command │ │ │ that pairs with this flash-attn wheel (ABI-matched) │ │ └ flash-attn wheel URL - │ └ CUDA build the wheel targets (match key against the driver) + │ └ CUDA build the wheel targets (match key against the driver; + │ "13.0" and "13.0.0" both work — only major.minor is compared) └ torch version (informational; also encoded in the wheel + PyTorchLink) Python is pinned to 3.13 by uv (see .python-version) so it is no longer a match -key — every wheel here is cp313. We just pick the newest CUDA build the driver -can run and hand the caller both pieces to install. +key — every wheel in both tables is cp313. We just pick the newest CUDA build +the driver can run and hand the caller both pieces to install. On a match it prints two `KEY=value` lines to stdout: WHEEL=https://.../flash_attn-...cp313-win_amd64.whl TORCHARGS=torch==2.12.0 torchvision==0.27.0 --index-url https://download.pytorch.org/whl/cu130 -(``TORCHARGS`` is column 4 with the leading ``pip install`` stripped, so the -caller can run it with ``uv pip install``.) On no match it prints nothing. +(``TORCHARGS`` is column 4 with the leading ``pip install`` / ``pip3 install`` +stripped, so the caller can run it with ``uv pip install``.) On no match — no +NVIDIA driver, an unsupported platform/arch, or a driver older than every listed +CUDA build — it prints nothing and exits 0; the caller decides what that means. Diagnostics go to stderr. Standard library + nvidia-smi only. +macOS has no CUDA, so rigging is unavailable there and this prints nothing. + Override CUDA detection with RIGTOOLS_CUDA (e.g. "12.8"). """ from __future__ import annotations import os +import platform import re import shutil import subprocess import sys from pathlib import Path -WHEELS_FILE = Path(__file__).resolve().parent / "flash_attention_windows.txt" +_HERE = Path(__file__).resolve().parent +# Wheels are platform-tagged: a win_amd64 wheel is rejected outright by pip/uv on +# Linux ("wheel is compatible with Windows, but you're on Linux"), so the table +# MUST follow the host rather than being a single shared list. +WHEELS_FILE = _HERE / ("flash_attention_windows.txt" if sys.platform == "win32" + else "flash_attention_linux.txt") def driver_cuda() -> float | None: """Max CUDA version the NVIDIA driver supports (from nvidia-smi), or None.""" override = os.environ.get("RIGTOOLS_CUDA") if override: - try: - return float(override) - except ValueError: - pass + forced = cuda_key(override) + if forced is not None: + return forced exe = shutil.which("nvidia-smi") if not exe: return None @@ -56,6 +69,17 @@ def driver_cuda() -> float | None: return float(f"{m.group(1)}.{m.group(2)}") if m else None +def cuda_key(text: str) -> float | None: + """Normalise a CUDA column to a comparable major.minor float. + + Accepts "13", "13.0" and "13.0.0" — the Linux table quotes three-part CUDA + versions, and a bare float() on those raises, which would silently drop the + row and look identical to "no GPU". + """ + m = re.match(r"\s*(\d+)(?:\.(\d+))?", text) + return float(f"{m.group(1)}.{m.group(2) or 0}") if m else None + + def parse_rows(): """Yield (torch_ver, cuda: float, wheel_url, torch_args) from the wheels file.""" rows = [] @@ -67,19 +91,37 @@ def parse_rows(): if len(parts) < 4: continue torch_ver, cuda, link, pytorch_cmd = parts[0], parts[1], parts[2], parts[3] - try: - cuda_f = float(cuda) - except ValueError: + cuda_f = cuda_key(cuda) + if cuda_f is None: continue - # Strip the leading "pip install" (or "uv pip install") so the caller can - # run it via `uv pip install `. - args = re.sub(r"^\s*(uv\s+)?pip\s+install\s+", "", pytorch_cmd).strip() + # Strip the leading "pip install" / "pip3 install" (or the "uv "-prefixed + # forms) so the caller can run it via `uv pip install `. + args = re.sub(r"^\s*(uv\s+)?pip3?\s+install\s+", "", pytorch_cmd).strip() rows.append((torch_ver, cuda_f, link, args)) return rows def main() -> None: py = f"{sys.version_info.major}.{sys.version_info.minor}" + + # Platform/arch gates first: both tables ship x86_64 wheels for a CUDA GPU, so + # anywhere else there is nothing to pick and saying so beats letting the caller + # download multi-GB of torch on the way to an unavoidable failure. + if sys.platform == "darwin": + print("[flash-attn] macOS has no CUDA; rigging is unavailable here.", file=sys.stderr) + return + if sys.platform not in ("win32", "linux"): + print(f"[flash-attn] Unsupported platform {sys.platform!r}; no prebuilt wheels listed.", file=sys.stderr) + return + arch = platform.machine().lower() + if arch not in ("x86_64", "amd64"): + print(f"[flash-attn] Unsupported CPU architecture {arch!r} — the listed wheels are " + f"x86_64 only.", file=sys.stderr) + return + if not WHEELS_FILE.exists(): + print(f"[flash-attn] Missing wheel table {WHEELS_FILE.name}.", file=sys.stderr) + return + cuda = driver_cuda() if cuda is None: print("[flash-attn] No NVIDIA GPU / CUDA detected; skipping prebuilt wheel.", file=sys.stderr) @@ -87,7 +129,7 @@ def main() -> None: rows = parse_rows() if not rows: - print("[flash-attn] No usable rows in flash_attention_windows.txt.", file=sys.stderr) + print(f"[flash-attn] No usable rows in {WHEELS_FILE.name}.", file=sys.stderr) return # Rows whose CUDA build the driver can run (wheel_cuda <= driver_cuda), @@ -103,8 +145,8 @@ def main() -> None: if py != "3.13": print(f"[flash-attn] WARNING: running Python {py}, but the wheels are cp313. " f"Expect an install failure unless the venv is Python 3.13.", file=sys.stderr) - print(f"[flash-attn] driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, torch {torch_ver}.", - file=sys.stderr) + print(f"[flash-attn] {WHEELS_FILE.name}: driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, " + f"torch {torch_ver}.", file=sys.stderr) print(f"WHEEL={link}") print(f"TORCHARGS={torch_args}")