DGL versions of the generation examples are linked below. Edit each script's
var block and follow the DGL run instructions.
stable-diffusion.cpp has two backend assignments:
--backendselects the runtime backend used to execute model graphs.--params-backendselects where model parameters are kept.
If --params-backend is not set, parameters are kept on their module runtime
backend and move to RAM or disk when it runs out of memory. Auto-fit can move
components to another GPU.
A backend assignment can be a single backend name:
sd-cli -m model.safetensors -p "a cat" --backend cpuThis applies to every module that does not have a more specific assignment.
Assignments can also target individual modules:
sd-cli -m model.safetensors -p "a cat" --backend te=cpu,vae=cuda0,diffusion=vulkan0The same syntax is used for parameter placement:
sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend te=cpu,vae=cpu--params-backend also accepts the special value disk:
sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend disk--max-vram can target resolved backend/device names:
sd-cli -m model.safetensors -p "a cat" --backend diffusion=cuda0,vae=vulkan0 --max-vram cuda0=6,vulkan0=2The value is a shared per-device budget for managed weights, registered runner compute and cache buffers, and idle buffers retained for reuse by ggml. The runner trims the idle pool to make room for allocations. If a prefetch already requires weight eviction, it can reuse a matching weight buffer directly. Live free memory and a safety reserve also constrain allocations. Device-wide VRAM usage can include driver contexts, unregistered backend scratch allocations, and other processes.
Module names are case-insensitive. Hyphens and underscores in module names are ignored, so clip_vision, clip-vision, and clipvision are equivalent.
all=, default=, and *= can be used to set the default backend inside a mixed assignment:
sd-cli -m model.safetensors -p "a cat" --backend all=cuda0,te=cpuA --backend module assignment can list several devices separated by &:
sd-cli -m model.safetensors -p "a cat" --backend "diffusion=cuda0&cuda1"The module's transformer blocks are then distributed across the listed devices
in contiguous ranges sized proportionally to each device's free memory (minus a
compute-buffer headroom of about 2 GiB per device), and the
module's graphs are executed with a ggml_backend_sched that runs each block
on the device holding its weights, copying the residual stream at the range
boundaries. The first device in the list is the module's main device: it also
holds the non-block tensors (embeddings, final norms, small sub-runners such as
CLIP models or projectors) and the graph inputs/outputs.
Layer split is supported for the diffusion and te modules. For te it
applies to the dominant text encoder (t5xxl or the LLM); other modules accept
only a single device. If the module has no recognizable transformer blocks, the
assignment falls back to the first listed device.
--params-backend accepts no device lists. Each block range's parameters load
directly to its own device. A params assignment such as te=cpu or
diffusion=disk sets where the ranges move when device memory is needed, as
described in weight residency.
Layer split uses the fixed graph-cut plan to assign blocks across devices, but
single-device segmented execution and next-segment prefetch are disabled for
the split module. --max-vram can still provide the per-device limits used by
layer split and auto-fit.
Use --list-devices to see the device names available on the system.
--split-mode selects how a multi-device module distributes its weights:
layer (the default, described above) or row. It accepts a single mode or
per-module assignments:
sd-cli -m model.safetensors -p "a cat" --backend "diffusion=cuda0&cuda1" --split-mode row
sd-cli -m model.safetensors -p "a cat" --backend "diffusion=cuda0&cuda1,te=cuda0&cuda1" --split-mode diffusion=row,te=layerIn row mode the module keeps executing on its main (first listed) device, but its transformer-block matmul weights are allocated in the backend's row-split buffer type, which slices each weight's rows across the listed devices in proportion to free memory and runs those matmuls on all devices in parallel. Compared to a layer split this uses all GPUs within every layer (instead of sequentially device by device) at the cost of a cross-device reduction per matmul - usually the faster option when the devices have fast interconnect.
Row split requires a compatible split-buffer export from the linked GGML backend. If it is unavailable (or the listed devices belong to different backend registries), the module falls back to a layer split. Embeddings, normalization weights, biases and other non-block tensors stay in regular buffers on the main device.
Row-split execution can use graph segments, but split weights are loaded synchronously instead of using the normal single-device prefetch path. Because GGML does not expose exact shard allocation sizes, the managed budget currently counts a split buffer's full size on each participating device. This is a conservative bound and can reject otherwise feasible layouts.
Direct ("immediately") LoRA application cannot patch row-split tensors; with
--split-mode row the automatic LoRA mode selects runtime application, and an
explicit --lora-apply-mode immediately skips the split tensors with a
warning.
--auto-fit requires on or off and defaults to on when omitted.
Explicit --params-backend assignments disable auto-fit,
regardless of argument order, even with --auto-fit on.
Auto-fit preserves explicit --backend assignments, including per-module
assignments and device lists. For modules without a runtime assignment, it chooses
the discrete GPU with the largest positive memory budget (the first device on a
tie), falling back to integrated GPUs when no discrete GPU has a positive budget.
An integrated GPU's shared system memory does not give it priority over a discrete
GPU. Explicit assignments such as --backend Vulkan1 still select that device.
It then checks whether the weights fit the remaining memory budgets and moves
components to other GPUs when they do not. The plan is printed with -v.
sd-cli -m model.safetensors -p "a cat" --auto-fit on
sd-cli -m model.safetensors -p "a cat" --auto-fit on --max-vram cuda0=8,cuda1=14
sd-cli -m model.safetensors -p "a cat" --backend cuda0
sd-cli -m model.safetensors -p "a cat" --backend diffusion=cuda0,te=cpu,vae=cuda1
sd-cli -m model.safetensors -p "a cat" --auto-fit offBudgets reuse --max-vram: a positive per-device value caps what auto-fit
plans with on that device, a negative value means "free memory minus that many
GiB", and with no budget set each device's free memory minus a 512 MiB margin
is used. These resolved GPU budgets, including the safety margin, also drive
the runner's graph-cut capacity checks.
Runtime capacity checks also leave 512 MiB of currently free device memory for
backend scratch buffers and pipelines, including with explicit backend assignments.
They cap free-memory reports by the device's total memory minus tracked
resident allocations. Vulkan reports exceeding total memory are rejected on
discrete GPUs because its heap-budget subtraction can underflow. On integrated
GPUs, a wrapped report triggers reclamation before the tracked estimate can be
accepted, subject to the byte checks and configured budgets. Other backends use
the cap instead of treating such reports as zero free memory. Failed checks log
the reported free and total memory alongside tracked weight and runtime allocations.
With --mmap, device-backed mappings count toward these budgets at their full
mapped-file size, once per device buffer even when multiple parameter blocks
share it. Mappings retained in the loader cache continue to count.
Auto-fit plans with whole-component weight sizes and a compute reserve of
2 GiB for diffusion and te and 1 GiB for other components. Components keep
their runtime backend as their params backend; weights that do not fit move to
RAM, then disk, as described in weight residency. When the
main GPU and the RAM available for weights cannot hold all weights, components
other than diffusion move to another GPU, starting from the lowest priority in
diffusion, te, vae order. A component moves only to a GPU whose remaining
budget holds all of its weights and compute reserve, and it then runs there and
keeps its weights there. Components with an explicit --backend assignment are
not moved. A GPU exposed by several backends, such as CUDA and Vulkan, counts
once.
Hires model upscaling shares the runtime budget and can reclaim idle weight copies from other components. Weights used by active computation or pending transfers stay protected.
Auto-fit does not select multi-GPU layer/row computation itself. Explicit device
lists and --split-mode still control that computation. Before the runners have
built their split plans, auto-fit conservatively counts the full component size
on each listed GPU when checking whether weights fit. This can move other
components to another GPU even when a split layout would fit; use
--auto-fit off to keep every component on its selected backend.
For example, a diffusion model whose full weights exceed the main GPU's budget
keeps the weights that fit on the GPU and stores the rest in RAM. Automatic graph
segmentation then loads the required weights for each segment.
--disable-segmented-compute still disables segmentation. Compute reserves are
estimates. Actual segment weights, compute buffers and caches must still fit the
runner's capacity checks, so not every resolution or frame count is guaranteed to
fit, and auto-fit does not change a component to CPU computation solely because
its full weights exceed VRAM.
If a VAE decode fails, decoding retries with spatial tiling even when --auto-fit
is off; supported video decoders try temporal tiling first and can then add
spatial tiling. Spatial retries use half-size tiles along each latent dimension.
--conv-direct defaults to auto and accepts module assignments for
diffusion, vae (including preview VAE), and controlnet, using the same
aliases and precedence rules as --flash-attn:
sd-cli -m model.safetensors -p "a cat" --conv-direct auto,vae=off
sd-cli -m model.safetensors -p "a cat" --conv-direct off,diffusion=ononrequests direct 2D and 3D convolution.offuses the existing im2col-based convolution paths.autofirst checks support for a representative F16-weight/F32-input direct convolution graph. Vulkan then benchmarks direct convolution against im2col using two small shapes per dimension, with warmup, output validation, and five interleaved measurements per shape. Direct convolution must improve the sum of median times by at least 5%; a failed probe defaults tooff. Other backends retain their implicit GEMM checks without benchmarking: CUDA 2D requires a compiled Turing-or-newer MMA architecture; HIP 2D requires the supported CDNA MFMA or RDNA WMMA architectures described below for flash attention. MUSA 2D has a SIMT implementation. CUDA, HIP, and MUSA 3D also have a SIMT implementation, so they do not require MMA. Other backends default tooff. Results and decision logs are cached per compute backend and dimension in the context, as with flash attention. Each dimension is selected independently, and all compute devices in a module must qualify. Parameter-storage devices do not affect this choice.
These are backend-level defaults. GGML still chooses the actual kernel based on weight type, shape, and hardware; enabling direct convolution does not guarantee that every operation uses implicit GEMM. The CUDA-family implicit GEMM paths require F16 weights and can use ordinary direct kernels for other cases. For 3D convolution, a supported direct kernel is also used as a fallback when the im2col decomposition is unsupported for the actual tensor sizes, including when an intermediate reshape or matrix multiplication exceeds backend limits. This option does not change the separately created image upscaler context.
Repeating --conv-direct replaces the previous assignment string. Existing
--diffusion-conv-direct (diffusion and ControlNet) and --vae-conv-direct
flags are deprecated and emit a warning, but remain supported when
--conv-direct is omitted. Use --conv-direct auto,diffusion=on,controlnet=on
and --conv-direct auto,vae=on, respectively. An explicit
--conv-direct takes precedence over both legacy flags regardless of order.
Library callers can set the conv_direct_mode context-option key with
sd_opt_set_string() to the same string; unset or empty selects auto while honoring legacy true
flags. The context copies the string.
--flash-attn defaults to auto. Selection happens while creating the model
context, before inference, and is cached once per compute backend in that context.
Parameter-storage backends are not benchmarked.
The option also accepts module assignments, using the same module aliases as
--backend:
sd-cli -m model.safetensors -p "a cat" --flash-attn auto,te=off,vae=on
sd-cli -m model.safetensors -p "a cat" --flash-attn off,diffusion=autoSupported modules are diffusion, te, clip_vision, vae, controlnet, and
audio_encoder. Modules without an assignment use the default (auto if no
default is supplied). A bare mode or all=, default=, or *= sets the default;
module-specific settings take precedence regardless of their position. Within
one assignment string, the last setting for the same module or default wins.
Repeating --flash-attn replaces the entire previous string.
Only modules set to auto need backend probing. An explicit on or off for
one module does not change another module's decision, even when they share a
backend. Modules without configurable attention are rejected instead of silently
ignoring their settings.
onrequests flash attention for all models. Unsupported attention operations still fall back to ordinary attention.offdisables flash attention, including the flash-attention fallback from SageAttention. SageAttention itself remains controlled by--sage-attn.autoenables CPU and supported CUDA MMA configurations without timing a benchmark. CUDA uses both the device's capability and the compiled GGML architectures. HIP also skips timing on known CDNA MFMA architectures (gfx908,gfx90a,gfx940/gfx941/gfx942,gfx950) and RDNA 3/3.5/4 WMMA architectures (gfx11xx/gfx12xx). The CDNA shortcut requiresGGML_HIP_MMQ_MFMAto be enabled at build time. All shortcuts still check support for the FA probe graph. Vulkan devices whose description identifies NVIDIA RTX hardware (GeForce RTX, TITAN RTX, Quadro RTX and professional RTX) also skip timing. This is a device-name heuristic and needs no CUDA runtime. Unsupported graphs are disabled; other configurations, including older or unknown HIP architectures and other Vulkan devices, are benchmarked.
The probe compares ordinary and flash attention through the same attention
builder used by models, including layout conversion and F16 conversion. It uses
two small self-attention graphs (512 tokens with head size 64, and 1024 tokens
with head size 128, both with four heads), checks their outputs, warms up each
path, then alternates five synchronized measurements. Flash attention is enabled
when the sum of its median times is at least 5% lower. These representative
shapes are a startup heuristic, not a guarantee for every model or resolution.
Allocation/execution failures and inconclusive probes select off. Timing stops
starting new measurement pairs after one second of measured computation;
backend initialization, warmup and an in-flight pair can take longer.
Different modules can select different results. A multi-device model enables
flash attention only if all of its compute devices select on, preserving the
model's existing single boolean setting. This conservative rule also covers
row-split configurations, which can fall back to layer split during initialization.
--fa and --diffusion-fa are deprecated and emit a warning when used.
Use --flash-attn on and --flash-attn off,diffusion=on, respectively.
Both aliases write the same mode string as --flash-attn; the last occurrence
of any of these options wins. Library callers
can set the flash_attn_mode context-option key with sd_opt_set_string()
to the same string, including
"on", "off", "auto", or "auto,te=off,vae=on".
An unset or empty string uses automatic selection unless a
legacy flash_attn or diffusion_flash_attn boolean is set. The context copies
the string; no new enum is required.
sd-cli -m model.safetensors -p "a cat" --flash-attn auto
sd-cli -m model.safetensors -p "a cat" --flash-attn off| Module | Purpose | Accepted names |
|---|---|---|
diffusion |
UNet, DiT, MMDiT, Flux, Wan, Qwen Image, and other diffusion models | diffusion, model, unet, dit |
te |
Text encoders and conditioners | te, clip, text, textencoder, textencoders, conditioner, cond, llm, t5, t5xxl |
clip_vision |
CLIP vision encoder | clip_vision, clipvision, clip-vision, vision |
vae |
VAE and TAE | vae, firststage, autoencoder, tae |
controlnet |
ControlNet | controlnet, control |
photomaker |
PhotoMaker ID encoder and PhotoMaker LoRA | photomaker, photomakerid, pmid, photo |
upscaler |
ESRGAN upscaler | upscaler, esrgan, hires |
detector |
ADetailer YOLOv8 detector | detector, adetailer, yolo |
te is the preferred module name for text encoders. clip is kept as an accepted alias because many existing commands and model names use CLIP terminology.
Backend names are resolved against the GGML backend device list. Matching is case-insensitive and accepts exact names or unique prefixes, so common values include names such as:
cpucuda0vulkan0metal
The special values auto, default, and an empty backend name select the default backend. The default preference is GPU, then integrated GPU, then CPU.
The special value gpu selects the first GPU backend, falling back to the first integrated GPU backend.
The special value disk is accepted only by --params-backend. --backend disk is invalid because disk is a parameter residency mode, not a runtime compute backend.
The runtime backend controls where graph execution runs. The parameter backend controls where model weights are allocated or whether they are reloaded from disk on demand.
For example:
sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend cpuThis runs all modules on cuda0 and keeps parameters in CPU RAM. Each module copies the parameters it needs to cuda0 while it runs.
For example:
sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend diskThis runs all modules on cuda0 and reloads parameters from the model file instead of keeping them in RAM.
disk is never selected implicitly. If --params-backend is not set, parameters are kept on the runtime backend.
Weights load into their params backend on first use. When a location runs out of memory, weights move down a residency chain:
--params-backend |
Residency chain |
|---|---|
| Not set, or the runtime backend | runtime device, RAM, disk |
| Another GPU | that GPU, RAM, disk |
cpu |
RAM, disk |
disk |
disk |
With --mmap, weights read from the mapped model file skip RAM because
reloads come from the page cache. Weights used by an operation that the compute
device cannot run, such as INT8 tensorwise embeddings, are stored in RAM.
A first load does not displace weights already resident in the params backend unless they belong to another component that is needed no sooner. Otherwise the new weights start at the next location on the chain. With CPU params and GPU compute, weights that do not fit in RAM can load directly from the model file into their compute buffers. Weights that need host storage still require RAM.
When a weight leaves a location, it is released if the next location already holds a copy, and copied there otherwise. If the next location lacks capacity, weights there with a lower priority are released to make room; they are not copied further. If room still cannot be made, the weight moves on to the following location. Reaching disk releases the weight without writing to the model file. Weights needed sooner by the current plan, then more recently used weights, have priority.
Weights stored away from the compute device are copied to it while a component
runs. These copies are released when the component finishes, so cpu,
another GPU, or disk keeps device memory free between components. Copies of
weights whose params backend is the compute device, made after those weights
moved to RAM or disk, stay until device memory is needed. When device memory is
needed, GPU originals of weights with a separate merged LoRA copy move first,
then copies that can be dropped, then resident weights that must be copied to
the next location, then idle compute buffers. The capacity check that decides
whether a graph needs segmentation counts the same actions.
--eager-load reads weights when a model loads instead of on first use. Each
weight takes the highest location on its chain with free capacity, leaving a
2 GiB compute reserve on GPUs, without releasing resident weights. Weights that
do not fit load on first use.
Weights with an immediately applied LoRA follow the same chain. Releasing a merged weight to disk discards the merge, and the next use merges again. When immediate LoRA application stages a separate compute copy of shared weights, the unmerged originals also follow the chain; if no location can hold them, compute copies load from the model file. Later LoRA variants reuse cached originals when available. When merged copies are released from the GPU, available RAM can cache them for later use unless the weights prefer disk. During a batched immediate merge, disk-resident weights can use temporary RAM to retain their merged values until the graph's weights are ready.
Per-module assignments can be mixed:
sd-cli -m model.safetensors -p "a cat" --backend diffusion=cuda0,te=cpu,vae=cpu --params-backend diffusion=cuda0,te=cpu,vae=cpuThis keeps text encoding and VAE execution on CPU while the diffusion model runs on GPU.
Backends are managed by SDBackendManager.
Within one manager, backend instances are cached by resolved backend device name. If multiple modules request the same backend, they share the same ggml_backend_t.
For example:
--backend te=cpu,vae=cpuuses one shared CPU backend for both te and vae runtime execution.
Runtime and parameter assignments also share the same backend cache. If --backend diffusion=cuda0 and --params-backend diffusion=cuda0 resolve to the same device, both use the same backend instance.
--params-backend disk does not create a separate backend instance. Parameters are loaded on use with the module runtime backend.
SDBackendManager owns the backend instances and frees them when the context or upscaler is destroyed. Model runners receive non-owning runtime and parameter backend pointers and do not free them.
The example CLI/server still accepts these older CPU placement flags as compatibility aliases:
--clip-on-cpu--vae-on-cpu--control-net-cpu--offload-to-cpu
--clip-on-cpu, --vae-on-cpu, and --control-net-cpu are deprecated. The example argument layer prepends te=cpu, vae=cpu, and controlnet=cpu to --backend before creating the context.
--offload-to-cpu prepends a CPU default to the parameter assignment in the caller before creating the context:
--params-backend '*=cpu'Because this default is inserted first, later explicit --params-backend entries can still override it, for example --offload-to-cpu --params-backend te=disk makes non-TE parameters prefer CPU RAM and TE parameters prefer disk.
Library callers should set backend and params_backend directly. sd_ctx_params_init()
enables auto_fit by default; a nonempty params_backend assignment disables it.
The backend assignment constrains auto-fit's compute placement.
The old CPU/offload fields are no longer part of the C API. Explicit --backend and
--params-backend assignments are preferred for new commands.