diff --git a/docs/integrazione_progetti.md b/docs/integrazione_progetti.md index ad5a1240..d652c1e3 100644 --- a/docs/integrazione_progetti.md +++ b/docs/integrazione_progetti.md @@ -200,6 +200,66 @@ curl.exe -s "http://127.0.0.1:1234/sdcpp/v1/capabilities" ` Sono disponibili anche endpoint compatibili OpenAI (`/v1/images/generations`) e AUTOMATIC1111 (`/sdapi/v1/txt2img`). Dettagli di sicurezza in sezione 5. +### 2.6 Windows: preparare un motore CPU + GPU per un'applicazione + +Una build Windows produce eseguibili e librerie Windows, non librerie macOS +(`Darwin`) o Linux. Il nome `win32` usato da Node/Electron indica Windows, +anche se l'eseguibile è a 64 bit; non descrive il backend GPU. Vulkan, CUDA e +Metal sono backend differenti: non si attivano soltanto copiando file in una +cartella chiamata `vulkan` o `darwin`. + +Per scegliere la build con un menu interattivo: `scripts/build-engine.ps1` +su Windows, `scripts/build-engine.sh` su macOS/Linux. Ogni sistema compila +solo i propri binari; per gli altri sistemi gli script rimandano alla build +su quella macchina o al workflow `release-portable.yml` (tag `portable-v*`). + +Per una build Windows con CPU e GPU: + +1. Installare Visual Studio Build Tools con C++ e Windows SDK, CMake e Ninja. +2. Per Vulkan, installare [Vulkan SDK](https://vulkan.lunarg.com/sdk/home) e + riaprire il Developer PowerShell per rendere disponibile `VULKAN_SDK`. + Per CUDA, installare un [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) + compatibile con GPU e compilatore MSVC; `nvidia-smi` da solo non è il + compilatore CUDA. Il Toolkit deve rendere `nvcc` disponibile nel `PATH`. +3. Verificare/aggiornare i driver della GPU. Un SDK serve alla compilazione; + il driver serve all'esecuzione. +4. Chiudere il motore nell'applicazione ospite prima di sostituirlo. +5. Dalla radice del repository, nel Developer PowerShell x64, eseguire: + +```powershell +# CPU con varianti x86 e backend Vulkan dinamico +.\scripts\build-windows-gpu.ps1 -Backend Vulkan -Destination "$HOME\sd-install\bin" + +# In alternativa, per NVIDIA con CUDA Toolkit: +# .\scripts\build-windows-gpu.ps1 -Backend CUDA -BuildDirectory build-windows-cuda -Destination "$HOME\sd-install\bin" + +# Per includere entrambi i backend, servono entrambi gli SDK: +# .\scripts\build-windows-gpu.ps1 -Backend "CUDA,Vulkan" -BuildDirectory build-windows-multi -Destination "$HOME\sd-install\bin" +``` + +Lo script configura una build Ninja Release separata con backend dinamici e +varianti CPU, compila con parallelismo limitato, verifica `--list-devices` e +copia l'intera directory dei binari solo se rileva un acceleratore. Verifica +anche la copia temporanea e conserva la vecchia installazione in una cartella +di backup, evitando di mescolare DLL di revisioni diverse. Senza `Destination` +compila e verifica soltanto. Non scarica gli SDK, non modifica le protezioni +di Windows e non include pesi di modelli. + +La verifica deve mostrare almeno un device di tipo `gpu`, `igpu` o `accel`, +non soltanto `CPU`. Ripetere `--list-devices` nella cartella effettivamente +usata dall'applicazione; un'etichetta di log come "GPU" non prova che quel +backend venga eseguito. Per forzare un device, usare il nome restituito +dall'inventario con `--backend`; aggiungere `--disable-backend-fallback` se +si preferisce un errore esplicito al ripiego sulla CPU. + +CPU, RAM, GPU/VRAM e disco hanno ruoli diversi. Il disco conserva i pesi; +`--params-backend cpu` li colloca in RAM e `--backend` sceglie dove calcolare. +L'auto-fit può scegliere collocazioni diverse per modulo; forzare un +`--params-backend` disattiva l'auto-fit. Non è garantito che tutte le unità +lavorino contemporaneamente o al 90%: trasferimenti, modello e memoria +disponibile determinano il piano di esecuzione. Prima provare una risoluzione +contenuta e verificare nei log i backend effettivamente scelti. + ### Pacchetto portabile (consigliato per la distribuzione) ```shell cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \ @@ -498,6 +558,10 @@ dei pacchetti portabili automatici descritti sopra. a soglia +5 punti la pressione è "critica". È best effort: non fa fallire un grafo che ci sta comunque e non è un limite fisico assoluto, perché le allocazioni dei driver fuori dalla gestione del motore non sono visibili. + Non si applica ai backend CPU: non è un guardiano della RAM di sistema. + Gli avvisi di pressione alta/critica e di recupero sono accessibili tramite + il callback di log; l'applicazione ospite può mostrarli senza interrompere + la generazione. Un monitor RAM nell'applicazione resta un controllo separato. - **Elenco dispositivi** per scegliere la strategia nell'app: tipo `cpu`, `gpu`, `igpu`, `accel`; memoria 0 = non riportata dal backend. - **Altri motori** (MNN, ncnn, ONNX Runtime): non sono integrati in questo diff --git a/scripts/build-engine.ps1 b/scripts/build-engine.ps1 new file mode 100644 index 00000000..0fd90074 --- /dev/null +++ b/scripts/build-engine.ps1 @@ -0,0 +1,58 @@ +param( + [int]$Scelta = 0, + [string]$Destinazione = "" +) + +# Selettore interattivo delle build del motore. Da Windows si possono +# compilare soltanto binari Windows: le voci macOS/Linux spiegano come +# ottenerli senza fingere una cross-compilazione che non esiste. + +$ErrorActionPreference = "Stop" +$gpuScript = Join-Path $PSScriptRoot "build-windows-gpu.ps1" + +$voci = @( + @{ Testo = "Windows - solo CPU (pacchetto portabile, varianti x86)"; Backend = "CPU"; Dir = "build-windows-cpu" }, + @{ Testo = "Windows - CPU + Vulkan (NVIDIA/AMD/Intel con driver Vulkan)"; Backend = "Vulkan"; Dir = "build-windows-vulkan" }, + @{ Testo = "Windows - CPU + CUDA (solo NVIDIA, richiede CUDA Toolkit)"; Backend = "CUDA"; Dir = "build-windows-cuda" }, + @{ Testo = "Windows - CPU + CUDA + Vulkan (richiede entrambi gli SDK)"; Backend = "CUDA,Vulkan"; Dir = "build-windows-multi" }, + @{ Testo = "macOS (Apple Silicon, Metal) - istruzioni"; Backend = $null }, + @{ Testo = "Linux (CPU/Vulkan/CUDA) - istruzioni"; Backend = $null } +) + +if ($Scelta -lt 1 -or $Scelta -gt $voci.Count) { + Write-Host "Quale motore vuoi compilare?" + for ($i = 0; $i -lt $voci.Count; $i++) { + Write-Host (" {0}) {1}" -f ($i + 1), $voci[$i].Testo) + } + $risposta = Read-Host "Scelta [1-$($voci.Count)]" + if (-not [int]::TryParse($risposta, [ref]$Scelta) -or $Scelta -lt 1 -or $Scelta -gt $voci.Count) { + throw "Scelta non valida: '$risposta'." + } +} + +$voce = $voci[$Scelta - 1] + +if ($null -eq $voce.Backend) { + Write-Host "" + Write-Host "I binari per macOS e Linux non si possono compilare da Windows:" + Write-Host "ogni sistema operativo compila soltanto i propri eseguibili." + Write-Host "" + Write-Host "Per ottenerli:" + Write-Host " - sul computer macOS/Linux: ./scripts/build-engine.sh" + Write-Host " - oppure, senza quel computer: push di un tag 'portable-v*' su GitHub." + Write-Host " Il workflow release-portable.yml produce gli zip per" + Write-Host " linux-x86_64, darwin-arm64 e windows-x86_64." + Write-Host "" + Write-Host "Il bilanciamento GPU/CPU/RAM/disco e' identico su ogni piattaforma:" + Write-Host "auto-fit colloca i pesi secondo la memoria disponibile e --memory-guard" + Write-Host "riduce la residenza dei pesi sotto pressione (vedi docs/performance.md)." + exit 0 +} + +if ($env:OS -ne "Windows_NT") { + throw "Questa voce compila binari Windows e richiede Windows." +} + +$parametri = @{ Backend = $voce.Backend; BuildDirectory = $voce.Dir } +if ($Destinazione) { $parametri.Destination = $Destinazione } +& $gpuScript @parametri diff --git a/scripts/build-engine.sh b/scripts/build-engine.sh new file mode 100644 index 00000000..bc69c359 --- /dev/null +++ b/scripts/build-engine.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# Selettore interattivo delle build del motore per macOS e Linux. +# Ogni sistema operativo compila soltanto i propri binari: le voci per gli +# altri sistemi spiegano come ottenerli (build su quel sistema o workflow +# release-portable.yml con un tag portable-v*). +# Uso: scripts/build-engine.sh [scelta] [cartella-destinazione] + +set -euo pipefail + +repo_root="$(cd "$(dirname "$0")/.." && pwd)" +scelta="${1:-}" +destinazione="${2:-}" +host="$(uname -s)" +arch="$(uname -m)" + +case "$host" in + Darwin) host_label="macOS" ;; + Linux) host_label="Linux" ;; + *) echo "Sistema non riconosciuto: $host. Per Windows usare scripts/build-engine.ps1." >&2; exit 1 ;; +esac + +if [[ -z "$scelta" ]]; then + echo "Quale motore vuoi compilare? (sistema attuale: $host_label $arch)" + echo " 1) macOS - CPU + Metal (richiede macOS)" + echo " 2) Linux - solo CPU (pacchetto portabile)" + echo " 3) Linux - CPU + Vulkan (richiede Vulkan SDK/driver)" + echo " 4) Linux - CPU + CUDA (solo NVIDIA, richiede CUDA Toolkit)" + echo " 5) Windows - istruzioni" + read -r -p "Scelta [1-5]: " scelta +fi + +cross_help() { + echo "I binari per $1 non si possono compilare da $host_label:" >&2 + echo "compilare su quel sistema ($2) oppure usare il workflow" >&2 + echo "release-portable.yml con un tag portable-v* (zip per" >&2 + echo "linux-x86_64, darwin-arm64 e windows-x86_64)." >&2 + exit 1 +} + +build_dir="" +cmake_args=(-DCMAKE_BUILD_TYPE=Release -DSD_BUILD_SHARED_GGML_LIB=ON + -DBUILD_SHARED_LIBS=ON -DGGML_BACKEND_DL=ON) +require_accelerator=1 + +case "$scelta" in + 1) + [[ "$host" == "Darwin" ]] || cross_help "macOS" "scripts/build-engine.sh" + build_dir="build-macos" + cmake_args+=(-DSD_METAL=ON) + ;; + 2) + [[ "$host" == "Linux" ]] || cross_help "Linux" "scripts/build-engine.sh" + build_dir="build-linux-cpu" + require_accelerator=0 + ;; + 3) + [[ "$host" == "Linux" ]] || cross_help "Linux" "scripts/build-engine.sh" + build_dir="build-linux-vulkan" + cmake_args+=(-DSD_VULKAN=ON) + ;; + 4) + [[ "$host" == "Linux" ]] || cross_help "Linux" "scripts/build-engine.sh" + command -v nvcc >/dev/null || { echo "CUDA Toolkit mancante (nvcc non trovato)." >&2; exit 1; } + build_dir="build-linux-cuda" + cmake_args+=(-DSD_CUDA=ON) + ;; + 5) + echo "I binari Windows si compilano su Windows con scripts/build-engine.ps1," + echo "oppure con il workflow release-portable.yml (tag portable-v*)." + exit 0 + ;; + *) + echo "Scelta non valida: '$scelta'." >&2 + exit 1 + ;; +esac + +if [[ "$arch" == "x86_64" ]]; then + cmake_args+=(-DGGML_CPU_ALL_VARIANTS=ON -DGGML_NATIVE=OFF) +fi + +cd "$repo_root" +if command -v ninja >/dev/null; then + cmake -S . -B "$build_dir" -G Ninja "${cmake_args[@]}" +else + cmake -S . -B "$build_dir" "${cmake_args[@]}" +fi +cmake --build "$build_dir" --parallel 2 + +cli="$build_dir/bin/sd-cli" +devices="$("$cli" --list-devices)" +echo "$devices" +if ! grep -qE $'\t(cpu|gpu|igpu|accel)\t' <<<"$devices"; then + echo "Enumerazione dispositivi fallita; installazione esistente non toccata." >&2 + exit 1 +fi +if [[ "$require_accelerator" == 1 ]] && ! grep -qE $'\t(gpu|igpu|accel)\t' <<<"$devices"; then + echo "Nessun acceleratore rilevato: controlla driver e backend." >&2 + echo "Installazione esistente non toccata." >&2 + exit 1 +fi + +if [[ -n "$destinazione" ]]; then + case "$(cd "$(dirname "$destinazione")" 2>/dev/null && pwd)/$(basename "$destinazione")" in + "$repo_root/$build_dir/bin") echo "La destinazione deve essere diversa dalla build." >&2; exit 1 ;; + esac + stage="$(mktemp -d)/bin" + mkdir -p "$stage" + cp -R "$build_dir/bin/." "$stage/" + staged="$("$stage/sd-cli" --list-devices)" + if [[ "$require_accelerator" == 1 ]] && ! grep -qE $'\t(gpu|igpu|accel)\t' <<<"$staged"; then + echo "La copia temporanea non supera la verifica; installazione non toccata." >&2 + exit 1 + fi + if [[ -d "$destinazione" ]]; then + backup="${destinazione%/}.backup-$(date +%Y%m%d-%H%M%S)" + mv "$destinazione" "$backup" + echo "Installazione precedente conservata in $backup" + fi + mkdir -p "$(dirname "$destinazione")" + mv "$stage" "$destinazione" + echo "Motore verificato e installato in $destinazione. Riavvia l'applicazione." +fi diff --git a/scripts/build-windows-gpu.ps1 b/scripts/build-windows-gpu.ps1 new file mode 100644 index 00000000..bf517076 --- /dev/null +++ b/scripts/build-windows-gpu.ps1 @@ -0,0 +1,93 @@ +param( + [ValidateSet("CPU", "Vulkan", "CUDA", "CUDA,Vulkan")] + [string]$Backend = "Vulkan", + [string]$BuildDirectory = "build-windows-gpu", + [string]$Destination = "" +) + +# With -Backend CPU the build is CPU-only and deployment does not require an +# accelerator; GPU backends keep requiring a successful accelerator check. +$requireAccelerator = $Backend -ne "CPU" + +$ErrorActionPreference = "Stop" +$root = Split-Path $PSScriptRoot -Parent +$build = [System.IO.Path]::GetFullPath((Join-Path $root $BuildDirectory)) + +function Invoke-Checked([string]$Program, [string[]]$Arguments) { + $ErrorActionPreference = "Continue" + & $Program @Arguments + if (-not $? -or $LASTEXITCODE -ne 0) { + throw "$Program failed with exit code $LASTEXITCODE." + } +} + +function Read-Devices([string]$Program) { + $ErrorActionPreference = "Continue" + $output = @(& $Program --list-devices 2>&1 | ForEach-Object { $_.ToString() }) + $code = $LASTEXITCODE + $output | ForEach-Object { Write-Host $_ } + if ($code -ne 0 -or -not ($output | Select-String "`t(cpu|gpu|igpu|accel)`t")) { + throw "Device enumeration failed in $Program. Existing installation has not been replaced." + } + if ($requireAccelerator -and -not ($output | Select-String "`t(gpu|igpu|accel)`t")) { + throw "No accelerator detected in $Program. Check drivers and backend DLLs. Existing installation has not been replaced." + } +} + +$arguments = @("-S", $root, "-B", $build, "-G", "Ninja", + "-DCMAKE_BUILD_TYPE=Release", "-DSD_BUILD_SHARED_GGML_LIB=ON", + "-DBUILD_SHARED_LIBS=ON", "-DGGML_BACKEND_DL=ON", + "-DGGML_NATIVE=OFF", "-DGGML_CPU_ALL_VARIANTS=ON", + "-DSD_CUDA=OFF", "-DSD_VULKAN=OFF") + +if ($Backend.Contains("CUDA")) { + if (-not (Get-Command nvcc -ErrorAction SilentlyContinue)) { + throw "CUDA Toolkit missing from PATH. Install a Toolkit compatible with your GPU and MSVC, then reopen Developer PowerShell." + } + $arguments += "-DSD_CUDA=ON" +} +if ($Backend.Contains("Vulkan")) { + if (-not $env:VULKAN_SDK -or -not (Test-Path "$env:VULKAN_SDK\Include\vulkan\vulkan.h")) { + throw "Vulkan SDK missing. Install the SDK, then reopen Developer PowerShell so VULKAN_SDK is set." + } + $arguments += "-DSD_VULKAN=ON" +} + +Invoke-Checked "cmake" $arguments +Invoke-Checked "cmake" @("--build", $build, "--parallel", "2") +$cli = Join-Path $build "bin\sd-cli.exe" +Read-Devices $cli + +if ($Destination) { + $target = [System.IO.Path]::GetFullPath($Destination) + if ($target.TrimEnd('\') -eq [System.IO.Path]::GetPathRoot($target).TrimEnd('\') -or + $target.TrimEnd('\') -eq $HOME.TrimEnd('\') -or + $target.TrimEnd('\') -eq $root.TrimEnd('\')) { + throw "Destination must be a dedicated engine directory, not a drive, home or repository root." + } + if ($target -eq (Join-Path $build "bin")) { + throw "Destination must differ from the build output directory." + } + $running = Get-CimInstance Win32_Process | Where-Object { + $_.ExecutablePath -and + [System.IO.Path]::GetDirectoryName($_.ExecutablePath) -eq $target -and + $_.Name -in @("sd-cli.exe", "sd-server.exe") + } + if ($running) { + throw "Engine still running in destination. Close the host application before deployment." + } + $stage = "$target.staging-$([Guid]::NewGuid().ToString('N'))" + $backup = "$target.backup-$(Get-Date -Format 'yyyyMMdd-HHmmss')" + New-Item -ItemType Directory -Path $stage -Force | Out-Null + Copy-Item -Path (Join-Path $build "bin\*") -Destination $stage -Recurse -Force + Read-Devices (Join-Path $stage "sd-cli.exe") + if (Test-Path $target) { Move-Item -Path $target -Destination $backup } + try { + Move-Item -Path $stage -Destination $target + } catch { + if (Test-Path $backup) { Move-Item -Path $backup -Destination $target } + throw + } + Write-Host "Validated engine copied to $target. Restart the host application to use it." + if (Test-Path $backup) { Write-Host "Previous engine preserved in $backup." } +} diff --git a/src/pipeline/diffusion_engine.cpp b/src/pipeline/diffusion_engine.cpp index 568a0444..2ca495db 100644 --- a/src/pipeline/diffusion_engine.cpp +++ b/src/pipeline/diffusion_engine.cpp @@ -1374,7 +1374,12 @@ bool StableDiffusionGGML::build_denoiser() { if (pred_type == PREDICTION_COUNT) { if (sd_version_is_sd2(version)) { - pred_type = is_using_v_parameterization_for_sd2(sd_version_is_inpaint(version)) ? V_PRED : EPS_PRED; + const int v_pred_check = check_v_parameterization_for_sd2(sd_version_is_inpaint(version)); + if (v_pred_check < 0) { + LOG_ERROR("SD2 parameterization probe failed; cannot determine prediction type"); + return false; + } + pred_type = v_pred_check == 1 ? V_PRED : EPS_PRED; } else if (sd_version_is_sdxl(version)) { if (tensor_storage_map.find("edm_vpred.sigma_max") != tensor_storage_map.end()) { // CosXL models @@ -1574,7 +1579,7 @@ bool StableDiffusionGGML::build_runners(const RunnerGroups& groups) { return groups.count(RunnerGroup::Core) == 0 || build_denoiser(); } -bool StableDiffusionGGML::is_using_v_parameterization_for_sd2(bool is_inpaint) { +int StableDiffusionGGML::check_v_parameterization_for_sd2(bool is_inpaint) { struct RunnerEndOnExit { GGMLRunner* runner = nullptr; ~RunnerEndOnExit() { @@ -1604,13 +1609,16 @@ bool StableDiffusionGGML::is_using_v_parameterization_for_sd2(bool is_inpaint) { diffusion_params.c_concat = &concat; } auto out_opt = diffusion_model->compute(n_threads, diffusion_params); - GGML_ASSERT(!out_opt.empty()); + if (out_opt.empty()) { + LOG_ERROR("SD2 parameterization probe compute failed (see previous errors)"); + return -1; + } out = std::move(out_opt); double result = static_cast((out - x_t).mean()); int64_t t1 = ggml_time_ms(); - LOG_VERBOSE("check is_using_v_parameterization_for_sd2, taking %.2fs", (t1 - t0) * 1.0f / 1000); - return result < -1; + LOG_VERBOSE("check_v_parameterization_for_sd2, taking %.2fs", (t1 - t0) * 1.0f / 1000); + return result < -1 ? 1 : 0; } std::string StableDiffusionGGML::lora_log_id(const ModelManager::LoraSpec& lora) { diff --git a/src/pipeline/diffusion_engine.h b/src/pipeline/diffusion_engine.h index 1c1afd08..25b996f4 100644 --- a/src/pipeline/diffusion_engine.h +++ b/src/pipeline/diffusion_engine.h @@ -340,7 +340,8 @@ public: bool build_runners(const RunnerGroups& groups); - bool is_using_v_parameterization_for_sd2(bool is_inpaint = false); + // Returns 1 for v-prediction, 0 for eps, -1 when the probe compute fails. + int check_v_parameterization_for_sd2(bool is_inpaint = false); static std::string lora_log_id(const ModelManager::LoraSpec& lora);