stable-diffusion.cpp/docs/build.md
Claude df766ab54a
Merge upstream/master (leejet/stable-diffusion.cpp 58bb3c1) into fork-pull
Brings in the 73 upstream commits since b13a482 (2026-10-20 to 2026-11-05):
cancellation of running server jobs (#2190), recipe based model management
and idempotent model loading (#2176, #2188, #2217, #2221), ADetailer in the
server (#2164), generation metadata returned with the core results (#2206,
which changes generate_image and generate_video), integrated GPUs in the
automatic memory planning (#2228), discrete GPUs preferred in auto-fit
(#2259), Vulkan capacity checks retried after reclaiming memory (#2256),
the layer split fix across CUDA devices (#2262), RPC devices in
--list-devices (#2182), new models and many speed-ups (FLUX.3, Fibo 2.0,
MiniMax-H3, P-H3-Image, MOSS, Z-Image control-net, INT8 CUDA fusions),
Node 24 and ccache in the workflows, a CUTLASS submodule for the CUDA build,
and the ggml sync to 135ce1e.

Conflicts resolved by hand in 25 files, keeping both sides:

- include/stable-diffusion.h, src/stable-diffusion.cpp,
  src/core/ggml_runner.cpp, src/pipeline/diffusion_engine.cpp,
  src/pipeline/image.cpp: upstream's result API stays (generate_image and
  generate_video fill a result out-parameter, free_sd_image_generation_result
  releases it); the fork's classified errors, exception barrier and busy
  check wrap it, so a failed call still records its reason and clears the
  result. memory_guard, disable_backend_fallback and multi_gpu follow
  upstream's last sd_ctx_params_t field. A stop on request is logged as
  information, not as an error.
- src/core/backend_fit.cpp: integrated GPUs are enumerated as upstream now
  does; which device becomes the main one is still decided by the fork's
  rules (discrete before integrated, a card seen by both CUDA and Vulkan
  counts once), which cover the case of #2259 as well.
- src/core/ggml_extend_backend.cpp, CMakeLists.txt: the NVIDIA driver is
  still loaded at run time (sd::cuda_driver; the toolkit provides headers
  only), so upstream's cuda_compiled_arch asks the compute capability
  through it and not through <cuda.h>; the CUTLASS include of upstream
  stays.
- src/model_manager.cpp: the CPU memory guard and upstream's capacity
  rechecks (#2183, #2256) both apply.
- examples/server (runtime, main, async_jobs, routes_*): the context keeper
  is still the only owner of the context, and ServerRuntime has no context
  or mutex of its own. Upstream's model catalog (--model-dir, the
  /sdcpp/v1/models routes, recipes) asks the keeper to load and unload
  (ContextKeeper::load, unload, has_model), so a model loaded from the
  catalog gets the same recovery ladder as the one given with -m, built from
  the options of the new model. ADetailer runs with the context and the
  options of the profile in use. The server still starts without a model.
- Cancellation: every job has a CancelToken that the keeper registers only
  while the job generates. POST /sdcpp/v1/jobs/{id}/cancel answers at once
  when called without ?wait=, as upstream does (the job can still be
  generating, with cancel_requested true); with ?wait=N it waits for the end
  of the job and answers 200, or 202 if it is still ending, which is what
  the fork's guardian expects. cancel_requested is always in the job JSON.
- examples/common/common.{h,cpp}: upstream's --list-devices with RPC devices
  and --taesd-preview-only next to the fork's --profile, --memory-guard,
  --multi-gpu and --disable-backend-fallback.
- .github/workflows/build.yml: upstream's Node 24, ccache and CUDA header
  triggers next to the fork's CPU Docker variant, lowercase image names,
  combined CUDA and Vulkan Windows zip and Italian release notes.
  examples/cli and examples/server CMakeLists: profile.cpp and recovery.cpp
  are added to upstream's source lists.
- docs/backend.md, docs/build.md, examples/server/api.md: the sections of
  both sides are kept. The paragraph on how a layer split assigns blocks is
  the fork's, which is what layer_split_partition.cpp does (the first device
  takes blocks until its free memory is used up), not upstream's
  "proportional" wording.

The ggml submodule moves from dc99877 to 135ce1e, the frontend submodule to
fa93429 and the new thirdparty/cutlass submodule is added, all at upstream's
pins. A checkout needs git submodule update --init --recursive.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-11-05 14:08:44 +01:00

14 KiB

Build from scratch

Get the Code

git clone --recursive https://github.com/Filve/diffusione-in-tempo-reale
cd diffusione-in-tempo-reale

If you already cloned the repository without submodules, initialize them from the repository root:

git submodule update --init --recursive

To update an existing checkout and its submodules:

cd diffusione-in-tempo-reale
git pull origin master
git submodule update --init --recursive

Selecting a GGML source tree

By default, sd.cpp builds the patched GGML submodule in ggml/. To build with an upstream GGML checkout instead, enable SD_USE_UPSTREAM_GGML and set SD_GGML_SOURCE_DIR:

cmake -S . -B build-upstream -DSD_USE_UPSTREAM_GGML=ON -DSD_GGML_SOURCE_DIR=../ggml-upstream
cmake --build build-upstream --config Release

Upstream compatibility mode uses the selected library and matching private headers. The patched GGML build uses public headers, including ggml-ext.h and ggml-graph.h. Backend options such as -DSD_CUDA=ON apply to the selected tree as usual.

SD_USE_UPSTREAM_GGML defaults to OFF, which enables the patched GGML extensions. Set it to ON when using upstream GGML; it selects the compatibility mode and does not download or replace the GGML source tree. Upstream mode keeps the original FP8 safetensors handling: FP8 tensors are converted to F16 at load time (one byte per element in the file, two in RAM and VRAM). INT8 tensorwise/convrot is disabled and its model files are rejected with an explicit error. FP8 GGUF files, FP8 weight type requests and tensor type rules are also rejected; no automatic conversion is performed.

Upstream GGML may lack some operators and performance optimizations provided by the patched version. A warning is emitted during CMake configuration and when creating an inference context. Ordinary floating-point and shared GGML quantization types remain available, subject to backend operator support.

SD_USE_SYSTEM_GGML=ON instead links an installed GGML CMake package, located with ggml_DIR or CMAKE_PREFIX_PATH. An installed patched package must include the extension and graph APIs; its source tree is not required for private headers. The installed library must use the same ABI settings as sd.cpp, including GGML_MAX_NAME. For an upstream package, also set SD_USE_UPSTREAM_GGML=ON and point SD_GGML_SOURCE_DIR to its matching source tree for the compatibility layer's private headers.

WebP and WebM Support in Examples

The example applications (examples/cli and examples/server) use libwebp to support WebP image I/O, and examples/cli can also use libwebm for .webm video output. Both are enabled by default. WebM output currently reuses libwebp to encode each frame as VP8 before muxing with libwebm.

If you do not want WebP/WebM support, you can disable them at configure time:

mkdir build && cd build
cmake .. -DSD_WEBP=OFF -DSD_WEBM=OFF
cmake --build . --config Release

If the submodules are not available, you can also link against system packages instead:

mkdir build && cd build
cmake .. -DSD_USE_SYSTEM_WEBP=ON -DSD_USE_SYSTEM_WEBM=ON
cmake --build . --config Release

Build (CPU only)

If you don't have a GPU or CUDA installed, you can build a CPU-only version.

mkdir build && cd build
cmake ..
cmake --build . --config Release

Build a portable package (dynamic backends)

Backends can be built as dynamic libraries that are discovered at runtime, so a single package runs on machines with different accelerators: each backend module loads only if its driver/runtime is available, and missing modules simply remove the corresponding devices instead of breaking the binary.

mkdir build && cd build
cmake .. -DSD_BUILD_SHARED_GGML_LIB=ON -DBUILD_SHARED_LIBS=ON -DGGML_BACKEND_DL=ON \
         -DSD_VULKAN=ON   # plus any other SD_* backends to include
cmake --build . --config Release

The build output contains one module per backend (e.g. libggml-cpu.so, libggml-vulkan.so) next to the executables; ship them together. On x86, -DGGML_CPU_ALL_VARIANTS=ON additionally builds one CPU module per microarchitecture level (SSE/AVX/AVX2/AVX-512) and picks the best supported one at runtime, which keeps the same package working on very old CPUs.

scripts/package_portable.sh <build_dir> collects the executables, backend modules, and license files from a portable build into a relocatable zip under dist/. Two environment variables describe a GPU package: PORTABLE_VARIANT=cuda12|vulkan|metal (zip name suffix and README wording) and PORTABLE_REQUIRE_BACKENDS=cuda|vulkan|metal, which makes the script fail when that backend module is not in the build (on Windows, also when the CUDA runtime DLLs cudart64_*, cublas64_* and cublasLt64_* are missing) instead of shipping a package that silently runs on the CPU.

The GitHub Actions workflow .github/workflows/release-portable.yml builds these packages, each with the CPU backend plus one GPU module:

Package GPU backend Notes
linux-x86_64 Vulkan needs the Vulkan loader (libvulkan.so.1) at runtime
darwin-arm64 Metal Apple Silicon
windows-x86_64 Vulkan NVIDIA, AMD and Intel GPUs; vulkan-1.dll comes with the GPU driver
windows-x86_64-cuda12 CUDA 12 NVIDIA only; the CUDA runtime DLLs are bundled, only the NVIDIA driver is needed (without it the package still starts, on the CPU)

On Windows every package also needs the Microsoft Visual C++ Redistributable 2015-2022 (x64), version 14.44 or newer. The executables are built with MSVC 14.44, and Microsoft requires an installed redistributable at least as recent as the build tools that produced the binaries (details). If it is missing or older, Windows cannot load the DLLs and ends the program at once without printing anything: the exit code is 0xC0000135 (3221225781, shown as -1073741515 by PowerShell). Check the installed version with (Get-Item C:\Windows\System32\msvcp140.dll).VersionInfo.FileVersion and install the latest from https://aka.ms/vc14/vc_redist.x64.exe. If you rebuild with a newer Visual Studio, the version of that compiler applies instead.

Start it from the Actions tab ("Run workflow", any branch) or push a tag portable-v*, which also attaches the zips to a release. The manual run takes two inputs: targets (all or a comma-separated list of the package names above) and cuda_architectures (default 61;70;75;80;86;89;90;100;120; a single architecture, e.g. 86 for GeForce RTX 30 series, shortens the CUDA build a lot).

Build with OpenBLAS

mkdir build && cd build
cmake .. -DGGML_OPENBLAS=ON
cmake --build . --config Release

Build with CUDA

The sd.cpp SageAttention extension is included when using CUDA with patched GGML (SD_USE_UPSTREAM_GGML=OFF). See SageAttention for GPU requirements and --sage-attn usage.

This provides GPU acceleration using NVIDIA GPU. Make sure to have the CUDA toolkit installed. You can download it from your Linux distro's package manager (e.g. apt install nvidia-cuda-toolkit) or from here: CUDA Toolkit. Recommended to have at least 4 GB of VRAM.

mkdir build && cd build
cmake .. -DSD_CUDA=ON
cmake --build . --config Release

CUDA extensions use sd.cpp's thirdparty/cutlass submodule by default for eligible INT8 GEMM and CuTe attention operations. If its headers are missing, CMake stops with an initialization hint; it does not download them automatically. Run git submodule update --init --recursive from the repository root before configuring.

To build with the existing CUDA implementations without CUTLASS, configure from the repository root with:

cmake -S . -B build -DSD_CUDA=ON -DSD_CUDA_CUTLASS_PATH:PATH=
cmake --build build --config Release

Alternatively, set SD_CUDA_CUTLASS_PATH to another local CUTLASS source directory (tested with 3.9.2). Existing CMake caches retain their configured path; pass -USD_CUDA_CUTLASS_PATH when reconfiguring to restore the bundled default. Existing GGML_CUDA_CUTLASS_PATH caches are migrated on first configuration: the old bundled path becomes thirdparty/cutlass, while custom paths and an empty disabled value are preserved. An explicitly set SD_CUDA_CUTLASS_PATH takes precedence. Non-CUDA builds do not require CUTLASS.

Build with HipBLAS

This provides GPU acceleration using AMD GPU. Make sure to have the ROCm toolkit installed. To build for another GPU architecture than installed in your system, set $GFX_NAME manually to the desired architecture (replace first command). This is also necessary if your GPU is not officially supported by ROCm, for example you have to set $GFX_NAME manually to gfx1030 for consumer RDNA2 cards.

Windows User Refer to docs/hipBLAS_on_Windows.md for a comprehensive guide.

mkdir build && cd build
if command -v rocminfo; then export GFX_NAME=$(rocminfo | awk '/ *Name: +gfx[1-9]/ {print $2; exit}'); else echo "rocminfo missing!"; fi
if [ -z "${GFX_NAME}" ]; then echo "Error: Couldn't detect GPU!"; else echo "Building for GPU: ${GFX_NAME}"; fi
cmake .. -G "Ninja" -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DSD_HIPBLAS=ON -DCMAKE_BUILD_TYPE=Release -DGPU_TARGETS=$GFX_NAME -DAMDGPU_TARGETS=$GFX_NAME -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DCMAKE_POSITION_INDEPENDENT_CODE=ON
cmake --build . --config Release

Build with MUSA

This provides GPU acceleration using Moore Threads GPUs. The configuration below follows upstream validation with MUSA SDK 5.2.0 and MTT S5000 (PH1, mp_31). Install that toolkit before building. Older SDKs such as 4.2 may lack the CUB headers required by the current backend.

mkdir build && cd build
cmake .. -DCMAKE_C_COMPILER=/usr/local/musa/bin/clang -DCMAKE_CXX_COMPILER=/usr/local/musa/bin/clang++ -DSD_MUSA=ON -DMUSA_ARCHITECTURES=31 -DCMAKE_BUILD_TYPE=Release
cmake --build . --config Release

The MUSA Docker image uses the same SDK 5.2.0 development image as upstream for both build and runtime stages, and targets mp_31 only. It includes the development tools and PyTorch from that base image, so it is larger than a minimal runtime image. Other GPU architectures require separate validation.

Build with Metal

Using Metal makes the computation run on the GPU. Currently, there are some issues with Metal when performing operations on very large matrices, making it highly inefficient at the moment. Performance improvements are expected in the near future.

mkdir build && cd build
cmake .. -DSD_METAL=ON
cmake --build . --config Release

Build with Vulkan

Install Vulkan SDK from https://www.lunarg.com/vulkan-sdk/. On Ubuntu, install the Vulkan development packages and SPIR-V headers:

sudo apt-get install build-essential libvulkan-dev glslc spirv-headers
mkdir build && cd build
cmake .. -DSD_VULKAN=ON
cmake --build . --config Release

Build with OpenCL (for Adreno GPU)

Currently, it supports only Adreno GPUs and is primarily optimized for Q4_0 type

To build for Windows ARM please refers to Windows 11 Arm64

Building for Android:

Android NDK: Download and install the Android NDK from the official Android developer site.

Setup OpenCL Dependencies for NDK:

You need to provide OpenCL headers and the ICD loader library to your NDK sysroot.

  • OpenCL Headers:

    # In a temporary working directory
    git clone https://github.com/KhronosGroup/OpenCL-Headers
    cd OpenCL-Headers
    # Replace <YOUR_NDK_PATH> with your actual NDK installation path
    # e.g., cp -r CL /path/to/android-ndk-r26c/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include
    sudo cp -r CL <YOUR_NDK_PATH>/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include
    cd ..
    
  • OpenCL ICD Loader:

    # In the same temporary working directory
    git clone https://github.com/KhronosGroup/OpenCL-ICD-Loader
    cd OpenCL-ICD-Loader
    mkdir build_ndk && cd build_ndk
    
    # Replace <YOUR_NDK_PATH> in the CMAKE_TOOLCHAIN_FILE and OPENCL_ICD_LOADER_HEADERS_DIR
    cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_TOOLCHAIN_FILE=<YOUR_NDK_PATH>/build/cmake/android.toolchain.cmake \
      -DOPENCL_ICD_LOADER_HEADERS_DIR=<YOUR_NDK_PATH>/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include \
      -DANDROID_ABI=arm64-v8a \
      -DANDROID_PLATFORM=24 \
      -DANDROID_STL=c++_shared
    
    ninja
    # Replace <YOUR_NDK_PATH>
    # e.g., cp libOpenCL.so /path/to/android-ndk-r26c/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android
    sudo cp libOpenCL.so <YOUR_NDK_PATH>/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android
    cd ../..
    

Build stable-diffusion.cpp for Android with OpenCL:

mkdir build-android && cd build-android

# Replace <YOUR_NDK_PATH> with your actual NDK installation path
# e.g., -DCMAKE_TOOLCHAIN_FILE=/path/to/android-ndk-r26c/build/cmake/android.toolchain.cmake
cmake .. -G Ninja \
  -DCMAKE_TOOLCHAIN_FILE=<YOUR_NDK_PATH>/build/cmake/android.toolchain.cmake \
  -DANDROID_ABI=arm64-v8a \
  -DANDROID_PLATFORM=android-28 \
  -DGGML_OPENMP=OFF \
  -DSD_OPENCL=ON

ninja

(Note: Don't forget to include LD_LIBRARY_PATH=/vendor/lib64 in your command line before running the binary)

Build with SYCL

Using SYCL makes the computation run on the Intel GPU. Please make sure you have installed the related driver and Intel® oneAPI Base toolkit before start. More details and steps can refer to llama.cpp SYCL backend.

# Export relevant ENV variables
source /opt/intel/oneapi/setvars.sh

# Option 1: Use FP32 (recommended for better performance in most cases)
cmake .. -DSD_SYCL=ON -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx

# Option 2: Use FP16
cmake .. -DSD_SYCL=ON -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DGGML_SYCL_F16=ON

cmake --build . --config Release