Stable Diffusion in Practice
How latent diffusion works (VAE + CLIP text encoder + U-Net/DiT), and every knob you meet in real tools: guidance scale, steps, schedulers, seeds, resolution, negative prompts, img2img strength, inpainting, ControlNet, LoRA, plus the flow-matching models SD3 and FLUX.
Stable Diffusion (released 2022) made high-quality Text-to-image generation run on a consumer GPU, and its open weights created an ecosystem of tools (diffusers, ComfyUI, AUTOMATIC1111, Fooocus) that all expose the same knobs. This lesson explains what is inside, then goes through each setting so that you know why an image changes when you move a slider, and how to fix the usual problems.
Inside latent diffusion
Rombach et al.[1] observed that most bits of an image are imperceptible high-frequency detail, so running diffusion on raw pixels wastes compute. Latent diffusion first trains an autoencoder (Variational autoencoder (VAE)) that compresses images 8× per side, then runs the whole diffusion process from the previous lesson in that latent space. Text conditioning enters through cross-attention.
| Component | Role | In SD 1.x / SDXL / SD3 |
|---|---|---|
| VAE | Encodes images to latents (for img2img/training) and decodes the final latent to pixels. | 4-channel latent at 1/8 resolution; SD3 uses 16 channels. |
| Text encoder | Turns the prompt into a sequence of embeddings the denoiser attends to. | CLIP ViT-L/14 (77 tokens) / CLIP ViT-L + OpenCLIP ViT-bigG / two CLIPs + T5-XXL. |
| Denoiser | Predicts noise (or velocity) for the latent at each step, conditioned on text and timestep. | U-Net ≈ 0.86B params / U-Net ≈ 2.6B / MMDiT transformer. |
| Scheduler / sampler | Algorithm that turns noise predictions into the next latent (DDIM, Euler, DPM++…). No weights. | Swappable at inference time. |
- 512×512×3
- image height × width × 3 colour channels (RGB)
- f = 8
- downsampling factor per side
- 64×64×4
- latent: 512/8 = 64 per side, 4 channels
- 48×
- how many times fewer numbers the latent has
- →
- 'is mapped to'
▸Worked example
- Q
- queries: one per latent position, from the image features
- K
- keys: one per prompt token
- V
- values: one per prompt token, the information that gets mixed in
- softmax
- turns each row of scores into positive weights that sum to 1
- Kᵀ
- K transposed, so Q·Kᵀ holds every query–key dot product
- √d
- square root of the key dimension; keeps the scores from growing with d
- W_Q
- learned projection for queries
- W_K
- learned projection for keys
- W_V
- learned projection for values
- φ(zₜ)
- the U-Net's intermediate features of the noisy latent, flattened into a sequence
- τ(prompt)
- the text encoder's output: 77 × 768 for SD 1.x
▸Worked example
U-Net vs. DiT. Newer models replace the U-Net with a Diffusion Transformer (Diffusion Transformer (DiT), Peebles & Xie[4]): the latent is cut into patches (e.g. 2×2), each patch becomes a token, and a plain Transformer processes them, with the timestep injected via adaptive layer norm. DiTs scale predictably: more compute gives better FID. SD3's MMDiT keeps separate weights for text and image tokens but lets them attend to each other jointly, which improves prompt following and text rendering[5].
Classifier-free guidance (CFG)
A conditional model trained only on (image, caption) pairs follows prompts weakly. Classifier-free guidance (CFG) (Ho & Salimans)[2] fixes this with a trick: during training, the caption is dropped (replaced by an empty prompt) about 10% of the time, so the same network learns both a conditional and an unconditional prediction. At sampling time you run both and extrapolate away from the unconditional one, in the direction the prompt points.
- ε̂
- epsilon-hat: the final, guided noise estimate passed to the scheduler
- ε_θ(zₜ, ∅)
- the network's prediction with the empty (or negative) prompt
- ε_θ(zₜ, prompt)
- the network's prediction with your prompt
- s
- the guidance scale (guidance_scale)
- ∅
- the empty prompt ""
- zₜ
- the current noisy latent
▸Worked example
- What it is
- How strongly each denoising step is pushed towards the prompt (s in the formula above).
- ↑ If you increase it
- Closer prompt adherence and more contrast, but less diversity; too high (≳ 12–15 for SD 1.5) gives oversaturated colours, harsh contrast, 'fried' artifacts and repetitive compositions.
- ↓ If you decrease it
- More natural and varied images but looser prompt following; near 1 images get muddy and incoherent. In diffusers, any value ≤ 1 disables CFG entirely (and halves the compute).
- Typical values
- SD 1.5: 7–7.5 (diffusers default 7.5). SDXL: 5–8. SD3: 4.5–7. Distilled turbo/LCM/'schnell' models: 0–2 (guidance is baked in).
- What it is
- Text describing what you do NOT want. It replaces the empty prompt ∅ in the CFG formula, so guidance pushes away from it.
- ↑ If you increase it
- A longer or more specific negative prompt removes more unwanted features (blur, watermarks, extra fingers), but long generic lists can also dull the image or fight the main prompt.
- ↓ If you decrease it
- Empty negative prompt = standard CFG. Fine for modern models (SDXL, SD3) that need it less than SD 1.5 did.
- Typical values
- Short and targeted: 'blurry, low quality, watermark, text'. Has no effect when guidance is disabled (scale ≤ 1).
Steps, schedulers and seeds
The same trained model can be sampled with many numerical solvers (schedulers or samplers), which trade speed for accuracy differently. Deterministic ODE solvers (DDIM, Euler, DPM++ 2M) converge to a fixed image as you add steps. Ancestral samplers (names ending in 'a', like 'Euler a') inject fresh noise every step, so the image keeps changing with the step count and never fully converges, which some users like for variety.
| Sampler (diffusers class) | Type | Typical steps | Notes |
|---|---|---|---|
DDPM (DDPMScheduler) | Stochastic | 250–1000 | Original; slow. |
DDIM (DDIMScheduler) | Deterministic (η = 0) | 25–50 | Good for inversion/editing. |
Euler (EulerDiscreteScheduler) | Deterministic ODE | 20–40 | Simple, reliable. |
Euler a (EulerAncestralDiscreteScheduler) | Stochastic (ancestral) | 20–40 | More variety; does not converge with more steps. |
DPM++ 2M Karras (DPMSolverMultistepScheduler, use_karras_sigmas=True) | Deterministic multistep | 15–30 | Popular quality/speed default. |
UniPC (UniPCMultistepScheduler) | Deterministic multistep | 10–25 | Very fast convergence. |
LCM (LCMScheduler) | Consistency-distilled | 2–8 | Needs an LCM model or LCM-LoRA; CFG ≈ 1–2. |
Flow Euler (FlowMatchEulerDiscreteScheduler) | Flow ODE | ~28 | Default for SD3 and FLUX. |
- What it is
- Number of denoising steps (network calls, ×2 with CFG) used to produce one image.
- ↑ If you increase it
- More detail and fewer artifacts up to a plateau (≈ 30–50 for most solvers); beyond that you mostly pay time. With ancestral samplers the image keeps changing.
- ↓ If you decrease it
- Faster; below ≈ 15 (non-distilled models) images look smeary, noisy or unfinished.
- Typical values
- 20–30 with DPM++/UniPC; 28 for SD3; 1–4 for SDXL-Turbo/FLUX-schnell; 4–8 for LCM.
- What it is
- The numerical algorithm that turns the model's noise predictions into the next latent.
- ↑ If you increase it
- Higher-order / multistep solvers (DPM++ 2M, UniPC) reach good quality in fewer steps. Karras sigma spacing spends more steps at low noise, sharpening details.
- ↓ If you decrease it
- Simpler first-order solvers (Euler, DDIM) need more steps for the same quality but are robust and predictable; ancestral variants add variety.
- Typical values
- DPM++ 2M Karras or Euler for SD 1.5/SDXL; the model's default flow-matching Euler for SD3/FLUX.
- What it is
- Integer that initializes the random generator for the starting noise latent (and any noise added during sampling).
- ↑ If you increase it
- There is no 'bigger is better': different seeds are simply different starting points, giving different compositions. Generate a batch of seeds to explore, then keep the best.
- ↓ If you decrease it
- Keeping the seed fixed while changing one other knob (prompt word, CFG, steps) is the cleanest way to see that knob's effect.
- Typical values
- Any integer. Same seed + same model + same settings + same software/hardware → same image (GPU kernels can cause tiny differences). A CPU generator and a CUDA generator with the same seed produce different noise.
- What it is
- Output size in pixels; the latent is 1/8 of it per side.
- ↑ If you increase it
- More detail, but memory and time grow roughly with pixel count (attention even faster). Going well beyond the training resolution causes duplicated subjects, extra limbs and tiled compositions.
- ↓ If you decrease it
- Faster, but far below the training size the model produces cropped, low-detail or broken images.
- Typical values
- Multiples of 8 (64 is safest). SD 1.5: 512×512. SDXL/SD3: about 1 megapixel, e.g. 1024×1024, 896×1152, 1216×832. For bigger images, generate at native size and upscale (hires fix / img2img).
import torch
from diffusers import AutoPipelineForText2Image, DPMSolverMultistepScheduler
pipe = AutoPipelineForText2Image.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16, variant="fp16",
).to("cuda")
# Swap the sampler: DPM++ 2M with Karras sigmas
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
pipe.scheduler.config, use_karras_sigmas=True
)
image = pipe(
prompt="a cozy reading nook by a rainy window, warm lamp light, watercolor",
negative_prompt="blurry, low quality, watermark, text",
guidance_scale=6.0, # CFG scale
num_inference_steps=30, # sampling steps
height=1024, width=1024, # SDXL's native resolution
generator=torch.Generator("cuda").manual_seed(42), # reproducible
).images[0]
image.save("nook.png")img2img and inpainting
[[img2img]] (the SDEdit idea, Meng et al., 2021) starts from your image instead of pure noise: encode it with the VAE, add noise up to an intermediate step, then denoise from there with your prompt. How far you go back is the Denoising strength. [[inpainting]] does the same only inside a mask: pixels outside the mask are kept. Dedicated inpainting checkpoints take extra input channels (the masked image latent and the mask itself) so they blend edges much better than a regular model.
- strength
- fraction of the schedule to re-noise, between 0 and 1
- T
- number of training timesteps (1000)
- num_inference_steps
- the step count you set in the pipeline
- ⌊
- floor brackets ⌊…⌋: round down to a whole number
- ⌋
- closing floor bracket
- ≈
- approximately
▸Worked example
- What it is
- In img2img/inpainting: how much noise is added to your input before denoising, from 0 (none) to 1 (pure noise).
- ↑ If you increase it
- More freedom for the model: composition, colours and shapes drift further from your input; at 1.0 the input is basically ignored (only its size is kept). More steps actually run.
- ↓ If you decrease it
- Output stays close to the input: only textures/style change; at very low values (≲ 0.2) changes are barely visible and few steps run.
- Typical values
- 0.3–0.5 for style/detail touch-ups; 0.6–0.8 to turn a rough sketch into a finished image; 0.9–1.0 for inpainting with a dedicated model.
from diffusers import AutoPipelineForImage2Image, AutoPipelineForInpainting
from diffusers.utils import load_image
# img2img: from_pipe shares the components already in memory
img2img = AutoPipelineForImage2Image.from_pipe(pipe)
init = load_image("my_sketch.png").resize((1024, 1024))
out = img2img(
prompt="a detailed oil painting of a lighthouse at dusk",
image=init,
strength=0.6, # 0 = keep input, 1 = ignore it
guidance_scale=6.0,
num_inference_steps=30, # only ~18 steps actually run
generator=torch.Generator("cuda").manual_seed(7),
).images[0]
# Inpainting: white mask pixels are regenerated, black ones are kept
inpaint = AutoPipelineForInpainting.from_pretrained(
"diffusers/stable-diffusion-xl-1.0-inpainting-0.1",
torch_dtype=torch.float16, variant="fp16",
).to("cuda")
mask = load_image("mask.png").resize((1024, 1024))
fixed = inpaint(
prompt="a red vintage bicycle leaning against the wall",
image=init, mask_image=mask,
strength=0.99, guidance_scale=7.0, num_inference_steps=30,
).images[0]ControlNet: spatial control
Prompts are bad at describing exact poses and layouts. ControlNet (Zhang et al., 2023)[3] adds a trainable copy of the denoiser's encoder that reads a control image (Canny edges, depth map, human pose skeleton, scribble, segmentation map) and adds its features into the frozen base model through zero convolutions: 1×1 convolutions initialized to zero, so at the start of training the ControlNet changes nothing and cannot damage the base model. One base model can be combined with many ControlNets.
- What it is
- Multiplier on the ControlNet features added to the base model: how strictly the control image is obeyed.
- ↑ If you increase it
- The output follows edges/pose/depth exactly; above ~1.2 images can look stiff, over-traced or artifacty, and the prompt matters less.
- ↓ If you decrease it
- The control becomes a loose suggestion: more natural results but the layout may drift; 0 disables ControlNet.
- Typical values
- 0.5–1.0. Combine with
control_guidance_end≈ 0.6–0.8 so the control shapes the layout early and lets the model finish details freely.
import cv2
import numpy as np
from PIL import Image
from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline
controlnet = ControlNetModel.from_pretrained(
"diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
)
cn_pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
controlnet=controlnet, torch_dtype=torch.float16,
)
cn_pipe.enable_model_cpu_offload()
edges = cv2.Canny(np.array(load_image("room.jpg")), 100, 200) # control image
canny = Image.fromarray(np.stack([edges] * 3, axis=-1))
image = cn_pipe(
prompt="a scandinavian living room, morning light, photorealistic",
image=canny,
controlnet_conditioning_scale=0.7,
control_guidance_end=0.8,
num_inference_steps=30, guidance_scale=6.0,
).images[0]Personalization: LoRA, DreamBooth, textual inversion
To teach a model a new style, character or product without retraining it, the community mostly uses LoRA (Low-Rank Adaptation) (Hu et al., 2021): small low-rank matrices added to the attention weights, typically 10–200 MB instead of several GB. DreamBooth fine-tunes on 3–20 photos of a subject bound to a rare token; textual inversion learns only a new word embedding. LoRAs can be stacked and their strength adjusted at load time.
- What it is
- Multiplier on the LoRA's low-rank update ΔW = B·A when merged into the base weights: W′ = W + scale · ΔW.
- ↑ If you increase it
- Stronger style/subject; above ~1.0 the LoRA 'overcooks': distorted anatomy, burnt colours, and it ignores parts of the prompt.
- ↓ If you decrease it
- Subtler influence, blends better with the base model and other LoRAs; 0 turns it off.
- Typical values
- 0.6–1.0 for one LoRA; lower each (e.g. 0.5–0.7) when stacking several.
pipe.load_lora_weights(
"nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel"
)
pipe.set_adapters(["pixel"], adapter_weights=[0.8]) # LoRA weight
image = pipe(
"pixel art, a knight resting by a campfire",
num_inference_steps=30, guidance_scale=6.0,
generator=torch.Generator("cuda").manual_seed(1),
).images[0]
pipe.unload_lora_weights() # back to the plain base modelpeft package).Flow matching: SD3 and FLUX
Flow matching (rectified flow) (Lipman et al., 2022) reframes generation as following a velocity field that transports noise to data. The rectified flow variant used by Stable Diffusion 3 (Esser et al., 2024)[5] and FLUX simply connects each data point and its noise with a straight line and trains the network to predict the direction along it. Straighter paths can be integrated accurately with fewer steps. SD3 also samples timesteps from a logit-normal distribution to focus training on the hard middle noise levels.
- xₜ
- the point on the line at time t
- x₀
- a data point (a clean latent)
- ε
- Gaussian noise
- t ∈ [0, 1]
- time: 0 = data, 1 = pure noise
- E
- average over data, noise and t
- ‖
- the bars ‖ … ‖² mean squared error summed over all entries
- v_θ(xₜ, t)
- the network's predicted velocity
- (ε − x₀)
- the target velocity, constant along the line
- Δt
- step size, e.g. 1/28 for 28 steps
- x_{t−Δt}
- the next point, a bit closer to the data
▸Worked example
▸Go deeper: running SD3, and a practical workflow
import torch
from diffusers import StableDiffusion3Pipeline
sd3 = StableDiffusion3Pipeline.from_pretrained(
"stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
).to("cuda")
image = sd3(
"a hand-painted sign that says 'OPEN LATE' above a noodle stall at night",
negative_prompt="",
num_inference_steps=28,
guidance_scale=7.0,
).images[0]- Explore: fix steps (~25) and CFG (model default), generate 8–16 seeds for your prompt.
- Refine: keep the best seed; change one thing at a time (a prompt phrase, CFG ±1, sampler).
- Control: add a ControlNet or LoRA if layout or style is still off.
- Fix: inpaint faulty regions (hands, faces, text) with strength 0.5–0.9.
- Finish: upscale (img2img at strength 0.2–0.4 on a larger canvas, or a dedicated upscaler).
The diffusers documentation[6] covers every pipeline used here, plus memory tricks (enable_model_cpu_offload, attention slicing, fp16/bf16, quantized transformers) for running large models on smaller GPUs.
Quiz
References
- [1]High-Resolution Image Synthesis with Latent Diffusion ModelsPaperRombach et al.2021arxiv.org
- [2]Classifier-Free Diffusion GuidancePaperHo & Salimans2022arxiv.org
- [3]Adding Conditional Control to Text-to-Image Diffusion Models (ControlNet)PaperZhang et al.2023arxiv.org
- [4]Scalable Diffusion Models with Transformers (DiT)PaperPeebles & Xie2022arxiv.org
- [5]Scaling Rectified Flow Transformers for High-Resolution Image Synthesis (Stable Diffusion 3)PaperEsser et al.2024arxiv.org
- [6]Diffusers documentationDocsHugging Facehuggingface.co