可用于图像和视频生成、编辑等场景。该项目轻量无依赖,支持多种扩散模型及量化,提供多平台 GPU 加速,内存占用低,支持负提示词和多种采样方法。【此简介由AI生成】
| Files | Last commit | Last update |
|---|---|---|
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 2 years ago | ||
| 3 years ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 3 years ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 3 years ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 2 years ago | ||
| 2 years ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 1 year ago | ||
| 2 years ago | ||
| 1 year ago | ||
| 1 year ago |
stable-diffusion.cpp
纯 C/C++ 实现的扩散模型(SD、Flux、Wan 等)推理
请注意,本项目正处于积极开发阶段。
API 和命令行选项可能会频繁变更。
特性
- 基于 ggml 的纯 C/C++ 实现,工作方式与 llama.cpp 相同
- 超轻量级,无外部依赖
- 支持的模型
- 图像模型
- SD1.x、SD2.x、SD-Turbo
- SDXL、SDXL-Turbo
- !!!SDXL 中的 VAE 在 FP16 模式下会遇到 NaN 问题,但遗憾的是,ggml_conv_2d 仅在 FP16 下运行。因此,需要一个参数来指定已修复 FP16 NaN 问题的 VAE。您可以在此处找到:SDXL VAE FP16 Fix。
- SD3/SD3.5
- Flux-dev/Flux-schnell
- Chroma
- 图像编辑模型
- 视频模型
- 支持 PhotoMaker。
- 支持 SD 1.5 的 Control Net
- 支持 LoRA,与 stable-diffusion-webui 相同
- 支持潜在一致性模型(LCM/LCM-LoRA)
- 使用 TAESD 实现更快、内存效率更高的潜空间解码
- 使用 ESRGAN 对生成图像进行放大
- 图像模型
- 支持 16 位、32 位浮点数
- 支持 2 位、3 位、4 位、5 位和 8 位整数量化
- 加速且内存高效的 CPU 推理
- 使用 fp16 精度进行 txt2img 生成 512x512 图像时仅需约 2.3GB 内存,启用 Flash Attention 时仅需约 1.8GB。
- 对 x86 架构支持 AVX、AVX2 和 AVX512
- 完整的 CUDA、Metal、Vulkan、OpenCL 和 SYCL 后端以支持 GPU 加速。
- 可加载 ckpt、safetensors 和 diffusers 模型/检查点。独立的 VAE 模型
- 不再需要转换为
.ggml或.gguf格式!
- 不再需要转换为
- Flash Attention 内存使用优化
- 负面提示
- stable-diffusion-webui 风格的分词器(并非所有功能,目前仅支持 token 权重)
- VAE 分块处理以减少内存使用
- 采样方法
Euler AEulerHeunDPM2DPM++ 2MDPM++ 2M v2DPM++ 2S aLCM
- 跨平台可复现性(
--rng cuda,与stable-diffusion-webui GPU RNG一致) - 将生成参数嵌入 png 输出中,作为与 webui 兼容的文本字符串
- 支持的平台
- Linux
- Mac OS
- Windows
- Android(通过 Termux,Local Diffusion)
使用方法
对于大多数用户,可以从最新的release下载已构建的可执行程序。 如果已构建的产品不符合您的要求,可以选择手动构建。
获取代码
git clone --recursive https://github.com/leejet/stable-diffusion.cpp
cd stable-diffusion.cpp
- 如果你已克隆仓库,可使用以下命令将仓库更新至最新代码。
cd stable-diffusion.cpp
git pull origin master
git submodule init
git submodule update
下载权重
-
下载原始权重文件(.ckpt 或 .safetensors 格式)。例如:
- Stable Diffusion v1.4 可从 https://huggingface.co/CompVis/stable-diffusion-v-1-4-original 获取
- Stable Diffusion v1.5 可从 https://huggingface.co/runwayml/stable-diffusion-v1-5 获取
- Stable Diffusion v2.1 可从 https://huggingface.co/stabilityai/stable-diffusion-2-1 获取
- Stable Diffusion 3 2B 可从 https://huggingface.co/stabilityai/stable-diffusion-3-medium 获取
curl -L -O https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/resolve/main/sd-v1-4.ckpt # curl -L -O https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors # curl -L -O https://huggingface.co/stabilityai/stable-diffusion-2-1/resolve/main/v2-1_768-nonema-pruned.safetensors # curl -L -O https://huggingface.co/stabilityai/stable-diffusion-3-medium/resolve/main/sd3_medium_incl_clips_t5xxlfp16.safetensors
构建
从头开始构建
mkdir build
cd build
cmake ..
cmake --build . --config Release
使用 OpenBLAS
cmake .. -DGGML_OPENBLAS=ON
cmake --build . --config Release
使用 CUDA
这会利用您 Nvidia GPU 的 CUDA 核心提供 BLAS 加速。请确保已安装 CUDA 工具包。您可以通过 Linux 发行版的包管理器(例如 apt install nvidia-cuda-toolkit)或从以下链接下载:CUDA Toolkit。建议至少拥有 4 GB 显存。
cmake .. -DSD_CUDA=ON
cmake --build . --config Release
使用 HipBLAS
此功能利用 AMD GPU 的 ROCm 核心提供 BLAS 加速。请确保已安装 ROCm 工具包。
Windows 用户请参考 docs/hipBLAS_on_Windows.md 获取详细指南。
export GFX_NAME=$(rocminfo | grep -m 1 -E "gfx[^0]{1}" | sed -e 's/ *Name: *//' | awk '{$1=$1; print}' || echo "rocminfo missing")
echo $GFX_NAME
cmake .. -G "Ninja" -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DSD_HIPBLAS=ON -DCMAKE_BUILD_TYPE=Release -DGPU_TARGETS=$GFX_NAME -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON
cmake --build . --config Release
使用 MUSA
这将利用您摩尔线程 GPU 的 MUSA 核心提供 BLAS 加速。请确保已安装 MUSA 工具包。
cmake .. -DCMAKE_C_COMPILER=/usr/local/musa/bin/clang -DCMAKE_CXX_COMPILER=/usr/local/musa/bin/clang++ -DSD_MUSA=ON -DCMAKE_BUILD_TYPE=Release
cmake --build . --config Release
使用 Metal
使用 Metal 可让计算在 GPU 上运行。目前,Metal 在处理超大型矩阵运算时存在一些问题,导致其当前效率极低。预计在不久的将来会有性能改进。
cmake .. -DSD_METAL=ON
cmake --build . --config Release
使用 Vulkan
从 https://www.lunarg.com/vulkan-sdk/ 安装 Vulkan SDK。
cmake .. -DSD_VULKAN=ON
cmake --build . --config Release
使用 OpenCL(适用于 Adreno GPU)
目前,它仅支持 Adreno GPU,并且主要针对 Q4_0 类型进行了优化
如需为 Windows ARM 构建,请参考 Windows 11 Arm64
为 Android 构建:
Android NDK: 从 Android 开发者官方网站 下载并安装 Android NDK。
为 NDK 设置 OpenCL 依赖项:
您需要将 OpenCL 头文件和 ICD 加载器库提供给 NDK 系统根目录。
-
OpenCL 头文件:
# 在临时工作目录中 git clone https://github.com/KhronosGroup/OpenCL-Headers cd OpenCL-Headers # 将 <YOUR_NDK_PATH> 替换为您实际的 NDK 安装路径 # 例如: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 加载器:
# 在同一个临时工作目录中 git clone https://github.com/KhronosGroup/OpenCL-ICD-Loader cd OpenCL-ICD-Loader mkdir build_ndk && cd build_ndk # 在 CMAKE_TOOLCHAIN_FILE 和 OPENCL_ICD_LOADER_HEADERS_DIR 中替换 <YOUR_NDK_PATH> 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 # 替换 <YOUR_NDK_PATH> # 例如: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 ../..
使用 OpenCL 为 Android 构建 stable-diffusion.cpp:
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
(注意:运行二进制文件前,不要忘记在命令行中加入 LD_LIBRARY_PATH=/vendor/lib64)
使用 SYCL
使用 SYCL 可让计算在 Intel GPU 上运行。开始前,请确保已安装相关驱动程序和 Intel® oneAPI Base toolkit。更多详细信息和步骤可参考 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
使用 SYCL 后端进行 text2img 的示例:
-
下载
stable-diffusion模型权重,参考 download-weight。 -
运行
./bin/sd -m ../models/sd3_medium_incl_clips_t5xxlfp16.safetensors --cfg-scale 5 --steps 30 --sampling-method euler -H 1024 -W 1024 --seed 42 -p "fantasy medieval village world inside a glass sphere , high detail, fantasy, realistic, light effect, hyper detail, volumetric lighting, cinematic, macro, depth of field, blur, red light and clouds from the back, highly detailed epic cinematic concept art cg render made in maya, blender and photoshop, octane render, excellent composition, dynamic dramatic cinematic lighting, aesthetic, very inspirational, world inside a glass sphere by james gurney by artgerm with james jean, joe fenton and tristan eaton by ross tran, fine details, 4k resolution"
使用 Flash Attention
为扩散模型启用 flash attention 可减少不同程度的内存占用(以 MB 为单位)。 例如:
- flux 768x768 ~600MB
- SD2 768x768 ~1400MB
对于大多数后端,这会降低速度,但对于 CUDA 而言,通常也会加快速度。 目前,它仅支持部分模型和部分后端(如 CPU、CUDA/ROCm、Metal)。
通过在参数中添加 --diffusion-fa 来运行,并留意:
[INFO ] stable-diffusion.cpp:312 - Using flash attention in the diffusion model
以及调试日志中的计算缓冲区收缩:
[DEBUG] ggml_extend.hpp:1004 - flux compute buffer size: 650.00 MB(VRAM)
运行
usage: ./bin/sd [arguments]
arguments:
-h, --help show this help message and exit
-M, --mode [MODE] run mode, one of: [img_gen, vid_gen, convert], default: img_gen
-t, --threads N number of threads to use during computation (default: -1)
If threads <= 0, then threads will be set to the number of CPU physical cores
--offload-to-cpu place the weights in RAM to save VRAM, and automatically load them into VRAM when needed
-m, --model [MODEL] path to full model
--diffusion-model path to the standalone diffusion model
--high-noise-diffusion-model path to the standalone high noise diffusion model
--clip_l path to the clip-l text encoder
--clip_g path to the clip-g text encoder
--clip_vision path to the clip-vision encoder
--t5xxl path to the t5xxl text encoder
--vae [VAE] path to vae
--taesd [TAESD_PATH] path to taesd. Using Tiny AutoEncoder for fast decoding (low quality)
--control-net [CONTROL_PATH] path to control net model
--embd-dir [EMBEDDING_PATH] path to embeddings
--upscale-model [ESRGAN_PATH] path to esrgan model. Upscale images after generate, just RealESRGAN_x4plus_anime_6B supported by now
--upscale-repeats Run the ESRGAN upscaler this many times (default 1)
--type [TYPE] weight type (examples: f32, f16, q4_0, q4_1, q5_0, q5_1, q8_0, q2_K, q3_K, q4_K)
If not specified, the default is the type of the weight file
--tensor-type-rules [EXPRESSION] weight type per tensor pattern (example: "^vae\.=f16,model\.=q8_0")
--lora-model-dir [DIR] lora model directory
-i, --init-img [IMAGE] path to the init image, required by img2img
--mask [MASK] path to the mask image, required by img2img with mask
-i, --end-img [IMAGE] path to the end image, required by flf2v
--control-image [IMAGE] path to image condition, control net
-r, --ref-image [PATH] reference image for Flux Kontext models (can be used multiple times)
--control-video [PATH] path to control video frames, It must be a directory path.
The video frames inside should be stored as images in lexicographical (character) order
For example, if the control video path is `frames`, the directory contain images such as 00.png, 01.png, 鈥?etc.
--increase-ref-index automatically increase the indices of references images based on the order they are listed (starting with 1).
-o, --output OUTPUT path to write result image to (default: ./output.png)
-p, --prompt [PROMPT] the prompt to render
-n, --negative-prompt PROMPT the negative prompt (default: "")
--cfg-scale SCALE unconditional guidance scale: (default: 7.0)
--img-cfg-scale SCALE image guidance scale for inpaint or instruct-pix2pix models: (default: same as --cfg-scale)
--guidance SCALE distilled guidance scale for models with guidance input (default: 3.5)
--slg-scale SCALE skip layer guidance (SLG) scale, only for DiT models: (default: 0)
0 means disabled, a value of 2.5 is nice for sd3.5 medium
--eta SCALE eta in DDIM, only for DDIM and TCD: (default: 0)
--skip-layers LAYERS Layers to skip for SLG steps: (default: [7,8,9])
--skip-layer-start START SLG enabling point: (default: 0.01)
--skip-layer-end END SLG disabling point: (default: 0.2)
--scheduler {discrete, karras, exponential, ays, gits, smoothstep, sgm_uniform, simple} Denoiser sigma scheduler (default: discrete)
--sampling-method {euler, euler_a, heun, dpm2, dpm++2s_a, dpm++2m, dpm++2mv2, ipndm, ipndm_v, lcm, ddim_trailing, tcd}
sampling method (default: "euler" for Flux/SD3/Wan, "euler_a" otherwise)
--timestep-shift N shift timestep for NitroFusion models, default: 0, recommended N for NitroSD-Realism around 250 and 500 for NitroSD-Vibrant
--steps STEPS number of sample steps (default: 20)
--high-noise-cfg-scale SCALE (high noise) unconditional guidance scale: (default: 7.0)
--high-noise-img-cfg-scale SCALE (high noise) image guidance scale for inpaint or instruct-pix2pix models: (default: same as --cfg-scale)
--high-noise-guidance SCALE (high noise) distilled guidance scale for models with guidance input (default: 3.5)
--high-noise-slg-scale SCALE (high noise) skip layer guidance (SLG) scale, only for DiT models: (default: 0)
0 means disabled, a value of 2.5 is nice for sd3.5 medium
--high-noise-eta SCALE (high noise) eta in DDIM, only for DDIM and TCD: (default: 0)
--high-noise-skip-layers LAYERS (high noise) Layers to skip for SLG steps: (default: [7,8,9])
--high-noise-skip-layer-start (high noise) SLG enabling point: (default: 0.01)
--high-noise-skip-layer-end END (high noise) SLG disabling point: (default: 0.2)
--high-noise-scheduler {discrete, karras, exponential, ays, gits, smoothstep, sgm_uniform, simple} Denoiser sigma scheduler (default: discrete)
--high-noise-sampling-method {euler, euler_a, heun, dpm2, dpm++2s_a, dpm++2m, dpm++2mv2, ipndm, ipndm_v, lcm, ddim_trailing, tcd}
(high noise) sampling method (default: "euler_a")
--high-noise-steps STEPS (high noise) number of sample steps (default: -1 = auto)
SLG will be enabled at step int([STEPS]*[START]) and disabled at int([STEPS]*[END])
--strength STRENGTH strength for noising/unnoising (default: 0.75)
--control-strength STRENGTH strength to apply Control Net (default: 0.9)
1.0 corresponds to full destruction of information in init image
-H, --height H image height, in pixel space (default: 512)
-W, --width W image width, in pixel space (default: 512)
--rng {std_default, cuda} RNG (default: cuda)
-s SEED, --seed SEED RNG seed (default: 42, use random seed for < 0)
-b, --batch-count COUNT number of images to generate
--clip-skip N ignore last layers of CLIP network; 1 ignores none, 2 ignores one layer (default: -1)
<= 0 represents unspecified, will be 1 for SD1.x, 2 for SD2.x
--vae-tiling process vae in tiles to reduce memory usage
--vae-tile-size [X]x[Y] tile size for vae tiling (default: 32x32)
--vae-relative-tile-size [X]x[Y] relative tile size for vae tiling, in fraction of image size if < 1, in number of tiles per dim if >=1 (overrides --vae-tile-size)
--vae-tile-overlap OVERLAP tile overlap for vae tiling, in fraction of tile size (default: 0.5)
--vae-on-cpu keep vae in cpu (for low vram)
--clip-on-cpu keep clip in cpu (for low vram)
--diffusion-fa use flash attention in the diffusion model (for low vram)
Might lower quality, since it implies converting k and v to f16.
This might crash if it is not supported by the backend.
--diffusion-conv-direct use Conv2d direct in the diffusion model
This might crash if it is not supported by the backend.
--vae-conv-direct use Conv2d direct in the vae model (should improve the performance)
This might crash if it is not supported by the backend.
--control-net-cpu keep controlnet in cpu (for low vram)
--canny apply canny preprocessor (edge detection)
--color colors the logging tags according to level
--chroma-disable-dit-mask disable dit mask for chroma
--chroma-enable-t5-mask enable t5 mask for chroma
--chroma-t5-mask-pad PAD_SIZE t5 mask pad size of chroma
--video-frames video frames (default: 1)
--fps fps (default: 24)
--moe-boundary BOUNDARY timestep boundary for Wan2.2 MoE model. (default: 0.875)
only enabled if `--high-noise-steps` is set to -1
--flow-shift SHIFT shift value for Flow models like SD3.x or WAN (default: auto)
--vace-strength wan vace strength
--photo-maker path to PHOTOMAKER model
--pm-id-images-dir [DIR] path to PHOTOMAKER input id images dir
--pm-id-embed-path [PATH] path to PHOTOMAKER v2 id embed
--pm-style-strength strength for keeping PHOTOMAKER input identity (default: 20)
-v, --verbose print extra info
文本转图像示例
./bin/sd -m ../models/sd-v1-4.ckpt -p "a lovely cat"
# ./bin/sd -m ../models/v1-5-pruned-emaonly.safetensors -p "a lovely cat"
# ./bin/sd -m ../models/sd_xl_base_1.0.safetensors --vae ../models/sdxl_vae-fp16-fix.safetensors -H 1024 -W 1024 -p "a lovely cat" -v
# ./bin/sd -m ../models/sd3_medium_incl_clips_t5xxlfp16.safetensors -H 1024 -W 1024 -p 'a lovely cat holding a sign says \"Stable Diffusion CPP\"' --cfg-scale 4.5 --sampling-method euler -v --clip-on-cpu
# ./bin/sd --diffusion-model ../models/flux1-dev-q3_k.gguf --vae ../models/ae.sft --clip_l ../models/clip_l.safetensors --t5xxl ../models/t5xxl_fp16.safetensors -p "a lovely cat holding a sign says 'flux.cpp'" --cfg-scale 1.0 --sampling-method euler -v --clip-on-cpu
# ./bin/sd -m ..\models\sd3.5_large.safetensors --clip_l ..\models\clip_l.safetensors --clip_g ..\models\clip_g.safetensors --t5xxl ..\models\t5xxl_fp16.safetensors -H 1024 -W 1024 -p 'a lovely cat holding a sign says \"Stable diffusion 3.5 Large\"' --cfg-scale 4.5 --sampling-method euler -v --clip-on-cpu
使用不同精度的格式将产生质量各异的结果。
| f32 | f16 | q8_0 | q5_0 | q5_1 | q4_0 | q4_1 |
|---|---|---|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
图像到图像示例
./output.png是通过上述文本到图像流程生成的图像
./bin/sd -m ../models/sd-v1-4.ckpt -p "cat with blue eyes" -i ./output.png -o ./img2img_output.png --strength 0.4
更多指南
绑定
以下项目对 stable-diffusion.cpp 进行了封装,以便在其他语言/框架中更轻松地使用。
- Golang(非 cgo):seasonjs/stable-diffusion
- Golang(cgo):Binozo/GoStableDiffusion
- C#:DarthAffe/StableDiffusion.NET
- Python:william-murray1204/stable-diffusion-cpp-python
- Rust:newfla/diffusion-rs
- Flutter/Dart:rmatif/Local-Diffusion
用户界面
以下项目使用 stable-diffusion.cpp 作为其图像生成的后端。
贡献者
感谢所有已为 stable-diffusion.cpp 做出贡献的人们!
星标历史
参考资料
Introduction
可用于图像和视频生成、编辑等场景。该项目轻量无依赖,支持多种扩散模型及量化,提供多平台 GPU 加速,内存占用低,支持负提示词和多种采样方法。【此简介由AI生成】
Customize your domain





