Skip to content

Latest commit

 

History

History
441 lines (350 loc) · 24.6 KB

AGENTS.md

File metadata and controls

441 lines (350 loc) · 24.6 KB

AGENTS.md

Project Overview

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 args

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).

Instructions

  • 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.

Tool Usage

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.

Model Download (aria2c)

Models are downloaded via aria2c with an input file listing all 3 URLs:

  • -c (continue): resumes partial downloads via a .aria2 control 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 explicit out= 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; -c ensures no wasted bandwidth.
  • aria2 is installed via apt-get (Debian package aria2).

HF Download (hf download)

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-dir disables 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_TOKEN is picked up natively by the CLI for gated repos.

Progress reporting for hf download

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; aria2c keeps its own native progress output.

hf CLI and uv (available globally)

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/bin pins the uv binary location.
  • hf: installed via uv tool install huggingface_hub (the hf CLI ships with the core huggingface_hub package). UV_TOOL_BIN_DIR=/usr/local/bin puts the hf shim on PATH. hf update self-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 clean runs after the install in the Dockerfile to drop the downloaded CPython/wheel caches (the tool venv lives outside the cache in ~/.local/share/uv/tools and is unaffected). No runtime uv cache cleaning is needed.

Project Structure

.
├── .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

CI/CD (GitHub Actions)

The .github/workflows/docker-publish.yml workflow builds and pushes the image to the GitHub Container Registry (GHCR).

  • Trigger: push to main (when Dockerfile, entrypoint.sh, or the workflow itself changes), plus manual workflow_dispatch, plus a weekly schedule (Monday 03:00 UTC) to pick up upstream master changes.
  • Registry: ghcr.io/dontdrinkandroot/stable-diffusion-cpp.docker
  • Tags produced: latest and sha-<short> (e.g. sha-ea0fba2).
  • Platform: linux/amd64 only (all target hosts are x86_64 NVIDIA GPUs).
  • Auth: uses the auto-provisioned GITHUB_TOKEN with packages: write.
  • No GPU needed for build — CUDA cross-compilation works without a GPU.

Smart skip (scheduled runs)

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.

Build caching

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.

Image retention (automatic cleanup)

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.

One-time: make the GHCR package public

After the first workflow run, the package defaults to private. Since Vast.ai and anonymous pulls need access, flip it to public:

  1. Go to https://github.com/users/dontdrinkandroot/packages/container/stable-diffusion-cpp.docker
  2. 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=public

One-time: grant the repository Admin role on the package

The 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):

  1. Go to the package page → Package settings → Manage Actions access
  2. Add the repository dontdrinkandroot/stable-diffusion-cpp.docker
  3. Set its role to Admin

This step can only be done after the first build creates the package.

Environment Variables

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 Files (Example: FLUX.2-klein-9B)

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-dev is a gated repo. Requires accepting the FLUX Non-Commercial License and providing HF_TOKEN.

Model Files (Example: Krea 2 + turbo distill LoRA)

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_DIR and is referenced via the sd-server API at request time.
  • Krea 2 weights are under the Krea 2 Community License (HF_TOKEN required).

Model Files (Example: MiniMax-H3)

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. Omitting AUDIO_VAE_URL still runs the joint diffusion model but produces video without a decoded audio track.

Healthcheck

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.
  • curl is installed alongside aria2 in the Dockerfile.
  • The healthcheck respects the PORT env var (default 1234).

SSH StrictModes Fix (for vast.ai)

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/*.conf directive in Ubuntu 24.04's sshd_config
  • Is not a conffile, so it survives vast.ai's openssh-server installation
  • Pre-creates /root/.ssh with 700 permissions as belt-and-suspenders

This was verified by simulating the full vast.ai overlay build process and confirming sshd -T reports strictmodes no.

Reference

Upstream stable-diffusion.cpp

Upstream Dockerfiles (for reference)

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).

Model Downloads (HuggingFace)

FLUX.2-klein Model Card

Server CLI Flags (sd-server)

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)

LoRA Directory

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.

aria2c

Self-Update Instruction

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.