Generic Docker image for running stable-diffusion.cpp (CUDA variant).
stable-diffusion.cpp is built from source in a multi-stage Dockerfile
(nvidia/cuda:12.8.2-devel build stage, nvidia/cuda:12.8.2-runtime runtime
stage) so CUDA kernel architectures can be controlled via the
CUDA_ARCHITECTURES build arg (default 75;80;86;89;90;100;120, including
sm_120/Blackwell — required for SageAttention on RTX 5090-class GPUs; the
upstream pre-built image lacks sm_120). The image adds an entrypoint that
downloads model weights on startup using aria2c (URL-based) or
hf download (HuggingFace spec-based).
Models are configured via environment variables — there are no hardcoded defaults.
| Build arg | Default | Description |
|---|---|---|
SDCPP_REF |
master |
Upstream leejet/stable-diffusion.cpp ref to build (branch, tag, or SHA). CI resolves master HEAD to a SHA and passes it (also recorded as the sd.cpp.revision image label). |
CUDA_ARCHITECTURES |
75;80;86;89;90;100;120 |
CMAKE_CUDA_ARCHITECTURES for the CUDA kernels. |
The web frontend is not built (-DSD_SERVER_BUILD_FRONTEND=OFF, no
Node/pnpm in the build) — sd-server is API-only. The CMake flag set mirrors
upstream docker/Dockerfile.cuda with GGML_CUDA_ENABLE_DYNAMIC_CPU_BACKENDS=ON
(shared libs, GGML_BACKEND_DL=ON, GGML_CPU_ALL_VARIANTS=ON,
GGML_NATIVE=OFF, rpath $ORIGIN).
- Get back to the user: When seemingly stuck, when an approach does not work as expected, or when new decisions have to be taken, the LLM Agent MUST stop and get back to the user with the situation and options instead of continuing with assumptions. Do not silently pivot to a different approach.
Use the dedicated tools; the bash tool is ONLY for actually executing
commands (docker/docker compose builds, git, running scripts such as
entrypoint.sh with bash -n syntax checks). Never use bash for reading,
searching, or listing — use the dedicated tools:
- Find files by pattern -> glob (never find / ls)
- Search file contents -> grep (never shell grep/rg, except rg -c for counts)
- Read a file OR list a directory's entries -> read (it accepts directories; never cat/head/ls)
- Edit files -> edit / write (never sed / awk / echo)
For several independent lookups, fire parallel dedicated-tool calls in one message
instead of chaining shell commands.
If the dedicated tools seem stuck (e.g. glob finds nothing in an unfamiliar tree),
read the directory itself or widen the glob — do NOT fall back to find/ls.
If an exploration still cannot be done, ask the user instead of guessing with bash.
Models are downloaded via aria2c with an input file listing all 3 URLs:
-c(continue): resumes partial downloads via a.aria2control file + HTTP Range requests. An interrupted run continues where it left off on next start.-x16 -s16: 16 parallel connections per file (chunked download).-j3: downloads all 3 model files concurrently.--header "Authorization: Bearer $HF_TOKEN": auth header sent on all requests (required for the gated FLUX.2-dev VAE repo). Passed as a bash array element so the header value stays a single argument regardless of spaces.-i(input file): each URL is paired with an explicitout=filename so the output name is controlled regardless of CDN redirects.- Retry loop: the download is wrapped in a retry loop (default 3 attempts, configurable
via
MAX_ATTEMPTS). On failure, aria2c is re-invoked;-censures no wasted bandwidth. - aria2 is installed via
apt-get(Debian packagearia2).
Each component can alternatively be specified as an HF spec org/repo/file via
HF_DIFFUSION_MODEL, HF_VAE, HF_AUDIO_VAE, HF_LLM, and HF_LORAS (comma-separated
list for loras). Setting both a *_URL and its HF_* counterpart for the same component
is a hard error (mutually exclusive). Download runs in a separate retry loop from aria2c
(same MAX_ATTEMPTS), one hf download REPO FILE --local-dir $MODEL_DIR (or $LORA_DIR)
per component, sequential:
- No central cache:
--local-dirdisables the HF cache entirely; the file lives only at the target path. A.cache/huggingface/metadata folder (etag/commit, a few bytes) is created inside the local dir so re-runs skip already-current files and resume interrupted ones — it must be kept, not deleted. HF_TOKENis picked up natively by the CLI for gated repos.
huggingface_hub's own tqdm progress bar is auto-disabled on non-TTY output (docker logs),
so download_hf_with_progress in entrypoint.sh reports progress itself: it fetches the
remote file size via a one-shot HEAD to https://huggingface.co/{repo}/resolve/main/{file}
(X-Linked-Size, falling back to the final response's Content-Length — redirects
followed so the redirect body's length is never misread, cf. huggingface_hub#4699), runs
hf download in the background and samples the *.incomplete temp file under
$LOCAL_DIR/.cache/huggingface/download/ every 10 seconds, logging lines like:
[download] 42% (3.3 GiB / 7.9 GiB) 45.2 MiB/s ETA 1m40s
- A size fetch failure (gated repo without
HF_TOKEN, offline) degrades gracefully to bytes+rate only ([download] 3.3 GiB downloaded 45.2 MiB/s). - If the incomplete file's path changes mid-download (new etag/revision), the counter is
reset and a
--- download restarted (prior partial download: ...) ---line is logged; resumed downloads (same etag) show the partial file's size directly, so percent starts where the previous run left off. - The function's exit code plugs into the existing retry loop unchanged;
aria2ckeeps its own native progress output.
The image ships the HuggingFace hf CLI plus uv at /usr/local/bin (on PATH
globally — root shells, docker exec, sshd sessions):
uv/uvx: installed with the standalone installer (curl -LsSf https://astral.sh/uv/install.sh | sh);UV_INSTALL_DIR=/usr/local/binpins the uv binary location.hf: installed viauv tool install huggingface_hub(thehfCLI ships with the corehuggingface_hubpackage).UV_TOOL_BIN_DIR=/usr/local/binputs thehfshim on PATH.hf updateself-updates to the latest version.- Managed CPython for the tool environment is auto-downloaded by uv at build time (no system Python required on the CUDA runtime base).
- Cache hygiene:
uv cache cleanruns after the install in the Dockerfile to drop the downloaded CPython/wheel caches (the tool venv lives outside the cache in~/.local/share/uv/toolsand is unaffected). No runtime uv cache cleaning is needed.
.
├── .github/
│ └── workflows/
│ └── docker-publish.yml # CI: build sd.cpp from source & push image to GHCR
├── Dockerfile # Multi-stage: nvidia/cuda:12.8.2-devel builds sd.cpp from source; runtime adds aria2/uv/entrypoint; HEALTHCHECK
├── build-and-push.sh # Local build + push to GHCR (mirrors CI: resolves upstream master SHA, sets sd.cpp.revision label)
├── entrypoint.sh # Downloads models via aria2c, then execs sd-server
├── docker-compose.yml # Port 1234, GPU, models + loras volumes, HF_TOKEN
├── docs/
│ └── vastai.md # Guide for running on vast.ai GPU marketplace
├── .dockerignore
└── AGENTS.md
The .github/workflows/docker-publish.yml workflow builds and pushes the
image to the GitHub Container Registry (GHCR).
- Trigger: push to
main(whenDockerfile,entrypoint.sh, or the workflow itself changes), plus manualworkflow_dispatch, plus a weeklyschedule(Monday 03:00 UTC) to pick up upstreammasterchanges. - Registry:
ghcr.io/dontdrinkandroot/stable-diffusion-cpp.docker - Tags produced:
latestandsha-<short>(e.g.sha-ea0fba2). - Platform:
linux/amd64only (all target hosts are x86_64 NVIDIA GPUs). - Auth: uses the auto-provisioned
GITHUB_TOKENwithpackages: write. - No GPU needed for build — CUDA cross-compilation works without a GPU.
A check job resolves upstream master HEAD (git ls-remote) and compares it
to the sd.cpp.revision label on the published :latest image
(docker buildx imagetools inspect --format '{{json .Image}}'). If unchanged,
the scheduled build is skipped. Push and workflow_dispatch events always
build. When building, the resolved SHA is passed as the SDCPP_REF build-arg
(reproducible, cache-invalidating) and recorded as the sd.cpp.revision label.
Locally, build-and-push.sh mirrors this flow (SHA resolution, label, latest
sha-<short>tags) so manual pushes don't fight the smart-skip.
The workflow uses the GHA cache backend (cache-from/to: type=gha) — the
CUDA compile step (~1-2 h cold on ubuntu-latest, 7 architectures + all CPU
kernel variants) is cached across runs; only upstream source changes force a
recompile.
After each successful build, a cleanup job runs
snok/container-retention-policy@v3.1.0 to prune old GHCR image versions,
keeping only the 5 newest tagged versions (cut-off: 0s +
keep-n-most-recent: 5). This prevents the registry from accumulating stale
sha-<short> versions over time. Deleted versions remain restorable for 30
days via GitHub's grace period.
After the first workflow run, the package defaults to private. Since Vast.ai and anonymous pulls need access, flip it to public:
- Go to
https://github.com/users/dontdrinkandroot/packages/container/stable-diffusion-cpp.docker - Package settings → Danger Zone → Change visibility → Public
Alternatively use the CLI:
gh api --method PATCH /user/packages/container/stable-diffusion-cpp.docker/visibility \
-f visibility=publicThe cleanup job uses the auto-provisioned GITHUB_TOKEN to delete old image
versions. For this to work, the repository must have the Admin role on the
GHCR package (write permission alone is not sufficient for deletion):
- Go to the package page → Package settings → Manage Actions access
- Add the repository
dontdrinkandroot/stable-diffusion-cpp.docker - Set its role to Admin
This step can only be done after the first build creates the package.
| Variable | Default | Description |
|---|---|---|
HF_TOKEN |
(empty) | HuggingFace token; required for gated repos. Optional if all URLs point to public repos. |
MODEL_DIR |
/models |
Directory for model files (mapped to a volume) |
LORA_DIR |
/loras |
Directory for LoRA files (mapped to a volume; upload via SSH/docker cp) |
PORT |
1234 |
sd-server HTTP port |
MAX_ATTEMPTS |
3 |
Max download retry attempts before failing |
DIFFUSION_MODEL_URL |
(none — must be set) | URL for the diffusion model file |
VAE_URL |
(none — must be set) | URL for the VAE file |
AUDIO_VAE_URL |
(none) | URL for the audio VAE file (passed via --audio-vae; required for audio-generating video models like MiniMax-H3) |
LLM_URL |
(none — must be set) | URL for the text encoder / LLM file |
HF_DIFFUSION_MODEL |
(none) | HuggingFace spec org/repo/file for the diffusion model (downloaded via hf download instead of aria2c). Mutually exclusive with DIFFUSION_MODEL_URL. |
HF_VAE |
(none) | HuggingFace spec org/repo/file for the VAE. Mutually exclusive with VAE_URL. |
HF_AUDIO_VAE |
(none) | HuggingFace spec org/repo/file for the audio VAE. Mutually exclusive with AUDIO_VAE_URL. |
HF_LLM |
(none) | HuggingFace spec org/repo/file for the text encoder / LLM. Mutually exclusive with LLM_URL. |
HF_LORAS |
(none) | Comma-separated (no spaces) list of HuggingFace specs org/repo/file downloaded via hf download into $LORA_DIR. |
DIFFUSION_FA |
(empty) | Set to 1 to enable --diffusion-fa (Flash Attention for diffusion model) |
SAGE_ATTN |
(empty) | Set to 1 to enable --sage-attn (native CUDA SageAttention in the diffusion model; requires SM80+ GPU and a compatible build — unsupported setups are rejected at startup) |
OFFLOAD_TO_CPU |
(empty) | Set to 1 to enable --offload-to-cpu (offload to CPU when VRAM is insufficient) |
CFG_SCALE |
(empty) | Sets --cfg-scale value (classifier-free guidance scale) |
STEPS |
(empty) | Sets --steps value (number of sampling steps) |
REF_IMAGE_ARGS |
(empty) | Sets --ref-image-args value (comma-separated key=value list configuring reference-image processing, e.g. preset=qwen_layered; see upstream docs/edit.md). Value is forwarded verbatim to sd-server; no validation. |
SAMPLING_METHOD |
(empty) | Sets --sampling-method value (e.g. euler, dpm++2m, res_multistep). Value is forwarded verbatim to sd-server; no validation. |
SCHEDULER |
(empty) | Sets --scheduler value (e.g. simple, karras, discrete). Value is forwarded verbatim to sd-server; no validation. |
FLOW_SHIFT |
(empty) | Sets --flow-shift value (numeric, for Flow models like SD3.x/WAN). Value is forwarded verbatim to sd-server; no validation. |
FPS |
(empty) | Sets --fps value (video framerate). Value is forwarded verbatim to sd-server; no validation. |
VIDEO_FRAMES |
(empty) | Sets --video-frames value (number of frames for video generation). Value is forwarded verbatim to sd-server; no validation. |
WIDTH |
(empty) | Sets --width value (image width in pixels). Value is forwarded verbatim to sd-server; no validation. |
HEIGHT |
(empty) | Sets --height value (image height in pixels). Value is forwarded verbatim to sd-server; no validation. |
MAX_VRAM |
(empty) | Sets --max-vram value (e.g. 6 or cuda0=6; -1 auto-detects free VRAM). Value is forwarded verbatim to sd-server; no validation. |
PARAMS_BACKEND |
(empty) | Sets --params-backend value (where model parameters are kept: disk, cpu, or per-module assignments like diffusion=disk,clip=cpu; see upstream docs/performance.md). Value is forwarded verbatim to sd-server; no validation. |
VERBOSE |
(empty) | Set to 1 to enable -v (verbose logging). |
AUTO_FIT |
(empty) | Set to 1 to enable --auto-fit (auto pick device placements from model size and per-device memory budgets). |
Local filenames are derived from the URL via basename (e.g. .../foo.gguf → $MODEL_DIR/foo.gguf).
HF specs are resolved via hf download REPO FILE --local-dir $MODEL_DIR, preserving subdirectories
in the file path (e.g. org/repo/split_files/vae/foo.safetensors → $MODEL_DIR/split_files/vae/foo.safetensors).
| Model | Repo | File | Size |
|---|---|---|---|
| Diffusion model (Q6_K) | unsloth/FLUX.2-klein-9B-GGUF |
flux-2-klein-9b-Q6_K.gguf |
7.87 GB |
| VAE | black-forest-labs/FLUX.2-dev |
ae.safetensors |
336 MB |
| Text encoder / LLM (Q6_K) | unsloth/Qwen3-8B-GGUF |
Qwen3-8B-Q6_K.gguf |
6.73 GB |
Note:
black-forest-labs/FLUX.2-devis a gated repo. Requires accepting the FLUX Non-Commercial License and providingHF_TOKEN.
Krea 2 uses the Krea2 diffusion transformer, the Wan2.1 VAE, and Qwen3-VL-4B as
the text encoder. The upstream doc is docs/krea2.md. The turbo-distill LoRA
extracts the Raw→Turbo weight delta, so it is applied on the Raw checkpoint.
Example HF_* specs (used via hf download):
HF_DIFFUSION_MODEL=realrebelai/KREA-2_GGUFs/BASE/Krea-2-Base-Q4_K_M.gguf
HF_VAE=Comfy-Org/Wan_2.1_ComfyUI_repackaged/split_files/vae/wan_2.1_vae.safetensors
HF_LLM=Qwen/Qwen3-VL-4B-Instruct-GGUF/Qwen3VL-4B-Instruct-Q4_K_M.gguf
HF_LORAS=TheDivergentAI/krea2-turbo-distill-lora/krea2_turbo_distill_r128.safetensors
STEPS=8
CFG_SCALE=0- Turbo-style sampling: 8 steps, CFG disabled (
CFG_SCALE=0). - The LoRA lands in
$LORA_DIRand is referenced via the sd-server API at request time. - Krea 2 weights are under the Krea 2 Community License (
HF_TOKENrequired).
MiniMax-H3 jointly generates video and stereo audio. The server needs FOUR
components wired separately via --diffusion-model, --vae, --audio-vae,
and --llm. The upstream doc is docs/minimax_h3.md.
| Component | Repo | File | Size |
|---|---|---|---|
| Diffusion model (Q4_K_M) | leejet/MiniMax-H3-GGUF |
minimax_h3_fl2va-Q4_K_M.gguf |
~18.8 GB |
| Video VAE | Comfy-Org/MiniMax-H3 |
minimax_h3_video_vae_fp16.safetensors |
~5.2 GB |
| Audio VAE | Comfy-Org/MiniMax-H3 |
minimax_h3_audio_vae_fp32.safetensors |
~605 MB |
| Text encoder (Q4_K_M) | leejet/MiniMax-H3-GGUF |
qwen3vl_32b_minimax_h3-Q4_K_M.gguf |
~11.4 GB |
Note: The text encoder must be the MiniMax-H3 variant of Qwen3-VL-32B (truncated to 50 language layers, exported without the final language-model normalization). The H3 repos require accepting the MiniMax H3 Community License and providing
HF_TOKEN. OmittingAUDIO_VAE_URLstill runs the joint diffusion model but produces video without a decoded audio track.
The Dockerfile defines a HEALTHCHECK that probes the sd-server's
/sdcpp/v1/capabilities endpoint via curl --fail:
HEALTHCHECK --interval=30s --timeout=10s --start-period=1800s --retries=3 \
CMD curl --fail http://localhost:${PORT:-1234}/sdcpp/v1/capabilities || exit 1
start-period=1800s(30 min): gives the container a grace period that covers the one-time ~15 GB model download on first start. During this window, healthcheck failures do not count against the container. On subsequent starts (models already in the volume), the server is ready much faster.curlis installed alongsidearia2in the Dockerfile.- The healthcheck respects the
PORTenv var (default1234).
When using --ssh mode on vast.ai, the platform builds an overlay image that
installs openssh-server and configures sshd. Vast.ai's provisioning includes:
sed -i "s/StrictModes yes/StrictModes no/g" /etc/ssh/sshd_config
However, Ubuntu 24.04's default sshd_config ships with #StrictModes yes
(commented out). The sed only changes it to #StrictModes no — still
commented — so StrictModes falls back to its default of yes. This causes
sshd to reject /root/.ssh/authorized_keys with:
Authentication refused: bad ownership or modes for file /root/.ssh/authorized_keys.
Fix: The Dockerfile creates a drop-in config at
/etc/ssh/sshd_config.d/99-strictmodes-no.conf with StrictModes no. This
file:
- Is loaded via the
Include /etc/ssh/sshd_config.d/*.confdirective in Ubuntu 24.04'ssshd_config - Is not a conffile, so it survives vast.ai's
openssh-serverinstallation - Pre-creates
/root/.sshwith700permissions as belt-and-suspenders
This was verified by simulating the full vast.ai overlay build process and
confirming sshd -T reports strictmodes no.
- Repository: https://github.com/leejet/stable-diffusion.cpp
- Build docs: https://github.com/leejet/stable-diffusion.cpp/blob/master/docs/build.md
- Docker docs: https://github.com/leejet/stable-diffusion.cpp/blob/master/docs/docker.md
- MiniMax-H3 guide: https://github.com/leejet/stable-diffusion.cpp/blob/master/docs/minimax_h3.md
- FLUX.2 usage guide: https://github.com/leejet/stable-diffusion.cpp/blob/master/docs/flux2.md
- Performance guide: https://github.com/leejet/stable-diffusion.cpp/blob/master/docs/performance.md
- CPU: https://github.com/leejet/stable-diffusion.cpp/blob/master/docker/Dockerfile
- CUDA: https://github.com/leejet/stable-diffusion.cpp/blob/master/docker/Dockerfile.cuda (our Dockerfile mirrors its build flags; the flag set in this repo's Dockerfile must be kept in sync with it)
The upstream pre-built images (ghcr.io/leejet/stable-diffusion.cpp:master-cuda)
are no longer used — we build from source so we control
CMAKE_CUDA_ARCHITECTURES (the upstream pre-built image lacks sm_120, so
SageAttention was unavailable on RTX 5090 / Blackwell GPUs).
- FLUX.2-klein-9B GGUF (all quantizations): https://huggingface.co/unsloth/FLUX.2-klein-9B-GGUF
- FLUX.2-klein-9B GGUF (leejet, smaller set): https://huggingface.co/leejet/FLUX.2-klein-9B-GGUF
- FLUX.2-dev (VAE source, gated): https://huggingface.co/black-forest-labs/FLUX.2-dev
- Qwen3-8B GGUF (text encoder): https://huggingface.co/unsloth/Qwen3-8B-GGUF
- FLUX.2-small-decoder (alternative VAE): https://huggingface.co/black-forest-labs/FLUX.2-small-decoder
- MiniMax-H3 GGUF (all quantizations): https://huggingface.co/leejet/MiniMax-H3-GGUF
- MiniMax-H3 weights (VAE sources, license required): https://huggingface.co/Comfy-Org/MiniMax-H3
- MiniMax-H3 (official, gated): https://huggingface.co/MiniMaxAI/MiniMax-H3
- Official announcement: https://huggingface.co/black-forest-labs/FLUX.2-klein-9B
- License:
flux-non-commercial-license - Variants: klein-4B (Apache 2.0), klein-9B (non-commercial), klein-base-4B, klein-base-9B
Key flags used in this project:
--diffusion-model <path> # Diffusion model GGUF file
--vae <path> # VAE file
--audio-vae <path> # Audio VAE file (conditional: AUDIO_VAE_URL; e.g. MiniMax-H3)
--llm <path> # Text encoder / LLM GGUF file
--port <port> # HTTP server port (default: 1234)
--diffusion-fa # Flash Attention for diffusion model (conditional: DIFFUSION_FA=1)
--sage-attn # Native CUDA SageAttention in the diffusion model (conditional: SAGE_ATTN=1)
--offload-to-cpu # Offload to CPU when VRAM is insufficient (conditional: OFFLOAD_TO_CPU=1)
--cfg-scale <value> # Classifier-free guidance scale (conditional: CFG_SCALE)
--steps <value> # Number of sampling steps (conditional: STEPS)
--ref-image-args <value> # Reference-image processing args, comma-separated key=value list (conditional: REF_IMAGE_ARGS)
--sampling-method <value> # Sampling method (conditional: SAMPLING_METHOD)
--scheduler <value> # Denoiser sigma scheduler (conditional: SCHEDULER)
--flow-shift <value> # Shift value for Flow models like SD3.x/WAN (conditional: FLOW_SHIFT)
--params-backend <value> # Parameter backend assignment: disk, cpu, or per-module e.g. diffusion=disk,clip=cpu (conditional: PARAMS_BACKEND)
--lora-model-dir <path> # LoRA directory (default: /loras; upload LoRAs here via SSH)
The entrypoint creates /loras (configurable via LORA_DIR) and passes it to
sd-server via --lora-model-dir. Upload LoRA files (.gguf / .safetensors)
into this directory at runtime — no restart needed:
# Via docker cp
docker cp my-lora.gguf sd-server:/loras/
# Via SSH (Vast.ai)
scp -P SSH_PORT my-lora.gguf root@SSH_HOST:/loras/The directory is backed by a named volume (loras) in docker-compose.yml so
files persist across container restarts. On Vast.ai, link a persistent volume at
/loras to preserve LoRAs across instance recreations.
- Install:
apt-get install aria2(Debian packagearia2) - aria2 docs: https://aria2.github.io/manual/en/html/aria2c.html
- Key flags:
-c(continue),-x(max connections per server),-s(split),-j(concurrent downloads),-i(input file),--header,-d(dir),-k(min split size) - Downloads page: https://aria2.github.io/
This guidelines file is a living document and MUST be actively maintained by the LLM Agent.
- Trigger: Whenever significant changes are made to the tech stack, project structure, coding guidelines, or key features, the LLM Agent MUST immediately update this file (
AGENTS.md) to reflect the current state of the project. - Content:
- Add any information that could have helped the agent to solve the task more efficiently or in fewer steps.
- Remove outdated, obsolete, or incorrect information.
- Ensure all tech stack versions and library names are accurate.
- Make sure the most important features are clearly documented.
- Keep the project structure up to date so that the most important files and directories are visible at a glance.
- Proactivity: Do not wait for explicit instructions to update these guidelines if you identify a discrepancy between the guidelines and the actual codebase.