AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
◐Image Generation
  1. Generative Models: The Big Picture
  2. Generative Adversarial Networks (GANs)
  3. Diffusion Models: From Noise to Image
  4. Stable Diffusion in Practice
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Image Generation

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.

Advanced~40 min·6 references
Key terms
Latent diffusionText-to-imageCLIPClassifier-free guidance (CFG)Guidance scale (CFG scale)Sampling steps (inference steps)Scheduler / samplerSeed (random seed)Negative promptInpaintingControlNetLoRA (Low-Rank Adaptation)Diffusion Transformer (DiT)Flow matching (rectified flow)

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.

≈
Work on the blueprint, not the building
An architect doesn't move bricks around to try out ideas; she edits a compact blueprint, then the builders turn it into a building. Latent diffusion does the same: the diffusion model 'sketches' in a small latent blueprint (64×64×4 numbers), and a VAE decoder 'builds' the full 512×512 image from it. Far less work per step, nearly the same result.

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.

ComponentRoleIn SD 1.x / SDXL / SD3
VAEEncodes 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 encoderTurns 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.
DenoiserPredicts 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 / samplerAlgorithm that turns noise predictions into the next latent (DDIM, Euler, DPM++…). No weights.Swappable at inference time.
image 512×512×3 = 786,432 values → VAE encoder (f = 8) → latent 64×64×4 = 16,384 values (48× fewer)
Why latent diffusion is cheap: each denoising step works on a 48× smaller tensor.
In words: The VAE shrinks each side of the image by a factor f = 8 and keeps 4 channels, so a 512×512 RGB image becomes a 64×64×4 latent. Every denoising step then processes 48 times fewer numbers.
Symbols(hover a symbol in the formula)
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
Image: 512 · 512 · 3 = 786,432 values Latent: (512/8) · (512/8) · 4 = 64 · 64 · 4 = 16,384 values Ratio: 786,432 / 16,384 = 48 SDXL at 1024×1024: latent 128 · 128 · 4 = 65,536 values vs. 3,145,728 pixel values (also 48×).
Attention(Q, K, V) = softmax(Q·Kᵀ / √d) · V, Q = W_Q · φ(zₜ), K = W_K · τ(prompt), V = W_V · τ(prompt)
Cross-attention: image features φ(zₜ) ask the questions (queries); the text embeddings τ(prompt) provide keys and values. This is how each region of the image 'looks up' the relevant words.
In words: Each latent position forms a query, each prompt token a key and a value. A query's similarity to every key, scaled and softmaxed, gives weights saying which words this position should listen to, and the output is the weighted average of those words' values.
Symbols(hover a symbol in the formula)
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
Shapes at the 64×64 level of SD 1.5: φ(zₜ) has 64 · 64 = 4,096 positions; τ(prompt) is 77 × 768 Per head (8 heads, d = 40): Q is 4,096 × 40, K and V are 77 × 40 → Q·Kᵀ is a 4,096 × 77 attention map Tiny case with d = 2: query q = (1, 0); keys 'fox' = (2, 0), 'snow' = (0, 2) scores = (2, 0)/√2 = (1.414, 0) → softmax = (4.113, 1)/5.113 = (0.804, 0.196) values v_fox = (1, 0), v_snow = (0, 1) → output (0.804, 0.196): this position mostly 'reads' the word fox.
Loading interactive…
Walk through one image generation, then tap the CFG circle and the scheduler. Notice that everything inside the × T loop works on a small 64×64×4 latent, the text enters only through cross-attention, and the VAE decoder runs just once at the end.

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

Loading interactive…
Walk through a DiT from latent patches to the predicted noise, then tap the Scale α boxes and the adaLN MLP. Notice that the timestep and class never enter as tokens: they only scale and shift the activations, and α starts at zero so every block begins as an identity.

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.

ε̂ = ε_θ(zₜ, ∅) + s · ( ε_θ(zₜ, prompt) − ε_θ(zₜ, ∅) )
s = guidance_scale. s = 1 → plain conditional model (no guidance); s > 1 → exaggerate what the prompt adds. ∅ is the empty prompt, or the negative prompt if you give one. Cost: two forward passes per step (batched together).
In words: Start from the prediction without the prompt and move s times as far as the prompt pushes it. s = 1 is just the conditional prediction; s > 1 extrapolates beyond it, exaggerating whatever the prompt adds.
Symbols(hover a symbol in the formula)
ε̂
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
One latent value: ε_θ(zₜ, ∅) = 0.20, ε_θ(zₜ, prompt) = 0.30 → difference 0.10 s = 7.5: ε̂ = 0.20 + 7.5 · 0.10 = 0.95 s = 1: ε̂ = 0.20 + 1 · 0.10 = 0.30 (no guidance) s = 0: ε̂ = 0.20 (prompt ignored) Every step needs both predictions: 2 U-Net passes, run together as a batch.
knobguidance_scale (CFG scale)
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).
knobnegative_prompt
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)TypeTypical stepsNotes
DDPM (DDPMScheduler)Stochastic250–1000Original; slow.
DDIM (DDIMScheduler)Deterministic (η = 0)25–50Good for inversion/editing.
Euler (EulerDiscreteScheduler)Deterministic ODE20–40Simple, reliable.
Euler a (EulerAncestralDiscreteScheduler)Stochastic (ancestral)20–40More variety; does not converge with more steps.
DPM++ 2M Karras (DPMSolverMultistepScheduler, use_karras_sigmas=True)Deterministic multistep15–30Popular quality/speed default.
UniPC (UniPCMultistepScheduler)Deterministic multistep10–25Very fast convergence.
LCM (LCMScheduler)Consistency-distilled2–8Needs an LCM model or LCM-LoRA; CFG ≈ 1–2.
Flow Euler (FlowMatchEulerDiscreteScheduler)Flow ODE~28Default for SD3 and FLUX.
knobnum_inference_steps
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.
knobscheduler / sampler
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.
knobseed
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.
knobheight / width (resolution)
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).
python
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")
Text-to-image with SDXL in diffusers, setting every knob explicitly.

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.

start step ≈ strength · T steps actually run ≈ ⌊num_inference_steps × strength⌋
strength 0.6 with 30 steps: noise the image to 60% and run only about 18 denoising steps.
In words: Strength says which fraction of the noise schedule to go back. Your image is noised to that level and only that fraction of the denoising steps is run, so low strength keeps the original and high strength repaints it.
Symbols(hover a symbol in the formula)
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
strength = 0.6, num_inference_steps = 30, T = 1000 start step ≈ 0.6 · 1000 = 600: the image is noised to t ≈ 600 steps run = ⌊30 × 0.6⌋ = 18 strength = 0.75 with 30 steps: ⌊22.5⌋ = 22 steps strength = 1.0: start from pure noise and run all 30 steps; the original image no longer matters.
knobstrength (denoising strength)
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.
python
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]
img2img (reusing the loaded SDXL weights) and inpainting with a dedicated SDXL inpainting model.

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.

Loading interactive…
Walk through the steps, then tap a zero conv box. Notice that the locked Stable Diffusion columns are untouched: the trainable copy on the right only adds its features into the decoder's skip connections, and at the start of training those additions are exactly zero.
knobcontrolnet_conditioning_scale
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.
python
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]
SDXL + Canny-edge ControlNet.

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.

knobLoRA weight (adapter scale)
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.
python
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 model
Loading a LoRA into the SDXL pipeline and setting its weight (requires the peft 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ₜ = (1 − t) · x₀ + t · ε, t ∈ [0, 1] L = E ‖ v_θ(xₜ, t) − (ε − x₀) ‖² sample: x_{t−Δt} = xₜ − Δt · v_θ(xₜ, t)
Rectified flow: the noising path, the training loss and the Euler sampling step.
In words: Noisy samples lie on the straight line between a data point x₀ (t = 0) and its noise ε (t = 1); the network learns the constant velocity ε − x₀ along that line; sampling walks back from noise to data in small Euler steps against that velocity.
Symbols(hover a symbol in the formula)
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
x₀ = 0.8, ε = −1.0, t = 0.25: xₜ = 0.75 · 0.8 + 0.25 · (−1.0) = 0.60 − 0.25 = 0.35 Target velocity: ε − x₀ = −1.0 − 0.8 = −1.8 (the same at every t) One Euler step with a perfect model, Δt = 0.25: x₀ = 0.35 − 0.25 · (−1.8) = 0.35 + 0.45 = 0.80 ✓ On a straight path even a big step lands exactly; curved paths (classic diffusion) need many small ones.
!
Common pitfalls and fixes
Long prompts silently truncated: CLIP sees only 77 tokens; put key ideas first (T5-based models like SD3/FLUX accept far longer prompts). Wrong resolution for the model: SD 1.5 at 1024² duplicates subjects; SDXL at 512² looks broken. Fried images: lower CFG or LoRA weight. Bad hands/text: older models struggle; use inpainting on the region, a better base model, or ControlNet pose. 'Seed doesn't reproduce': check generator device (CPU vs. CUDA), scheduler, dtype and library version. NSFW/rights: respect model licenses, and don't generate real people's likeness without consent.
▸Go deeper: running SD3, and a practical workflow
python
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]
SD3 Medium (gated on the Hub: accept the license first). Note the flow-matching scheduler is set by default.
  1. Explore: fix steps (~25) and CFG (model default), generate 8–16 seeds for your prompt.
  2. Refine: keep the best seed; change one thing at a time (a prompt phrase, CFG ±1, sampler).
  3. Control: add a ControlNet or LoRA if layout or style is still off.
  4. Fix: inpaint faulty regions (hands, faces, text) with strength 0.5–0.9.
  5. 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

1.
Why does Stable Diffusion run the diffusion process in a VAE latent space instead of on pixels?
2.
You raise guidance_scale from 7 to 20 on SD 1.5. What do you most likely see?
3.
In img2img you set strength = 0.2 with 50 steps. What happens?
4.
Why are ControlNet's connections initialized as zero convolutions?
5.
What makes rectified-flow models such as SD3 and FLUX able to sample well in relatively few steps?
Score: 0/5

References

  1. [1]
    High-Resolution Image Synthesis with Latent Diffusion Models
    PaperRombach et al.2021arxiv.org
  2. [2]
    Classifier-Free Diffusion Guidance
    PaperHo & Salimans2022arxiv.org
  3. [3]
    Adding Conditional Control to Text-to-Image Diffusion Models (ControlNet)
    PaperZhang et al.2023arxiv.org
  4. [4]
    Scalable Diffusion Models with Transformers (DiT)
    PaperPeebles & Xie2022arxiv.org
  5. [5]
    Scaling Rectified Flow Transformers for High-Resolution Image Synthesis (Stable Diffusion 3)
    PaperEsser et al.2024arxiv.org
  6. [6]
    Diffusers documentation
    DocsHugging Facehuggingface.co
← Previous
Diffusion Models: From Noise to Image
Next → · Audio & Speech AI
Audio Basics: From Sound Waves to Spectrograms