Conditional & Controllable Generation
Three tools do this: ControlNet, IP-Adapter and LoRA. Each one is explained below, and they can be used together.
After this lesson, you will be able to:
- Understand how ControlNet's zero-init trick lets you condition a frozen Stable Diffusion on edges, depth maps, poses, and scribbles without breaking the base model
- Use IP-Adapter to drop in a reference image and generate variations in its style — no fine-tuning, no DreamBooth, just decoupled cross-attention
- Pick between LoRA-Dreambooth, Textual Inversion, and full DreamBooth for personalizing a model to a specific concept based on data size, compute, and how cleanly you need to compose with other adapters
- Stack ControlNet + IP-Adapter + LoRA in a real production workflow (ComfyUI-style), and avoid the common pitfalls of conditioning_scale fights and overfitting
Before you start
An extra input that tells the model what you want, such as a text prompt, a sketch or a reference picture.
An add-on that lets a sketch, a pose or an edge map decide where things go in the picture.
A small extra part bolted onto a frozen model so it can take a new kind of input without being retrained.
A small trained patch that changes how a big model behaves for one subject or style. The big model itself stays untouched.
How many independent directions a patch is allowed to change. A small rank means a small, cheap patch.
A way to teach the model one new subject, such as your dog, from a handful of photos.
Redrawing only a masked part of a picture and leaving the rest as it was.
A number from 0 to 1 that says how strongly an add-on is obeyed. 0 switches it off.
Controllable generation is really three separate tools used together. Learn each one on its own, and the combined workflows follow.
#Beyond Text Prompts
#Guidance as a tilted distribution
Here y is the label and the score is the direction in which an image becomes more likely. The two derivations below show where classifier guidance comes from and what the guidance scale does.
Try it on bell curves. One curve stands for any image, another for images that match the prompt, and the guided curve mixes the two.
Do: Drag the guidance scale s from 0 to 1, then push it past 1.Notice: At 1 the guided curve lands on the prompt curve. Past 1 it overshoots and its samples bunch together.Why: Guidance exaggerates the prompt direction. These are exact one-dimensional curves, not images and not a trained model.
#ControlNet: The Zero-Init Trick
Picture a finished painting you do not want to damage. ControlNet leaves it alone and puts a trainable tracing copy beside it. The copy looks at your sketch. A connecting layer that starts at zero passes the copy's hints to the original. On day one nothing changes, and the hints grow as training goes on.
Two claims hide in this block: the base is untouched at step 0, and yet the new branch can still learn. Open the derivation for both.
- Canny edges — preserve composition while changing colors/textures
- Depth maps — enforce 3D structure
- OpenPose skeletons — precise pose control for figures
- Scribbles / sketches — low-effort layout from a doodle
- Normal maps — surface orientation
- Segmentation masks — semantic regions
- Line art — anime/illustration workflows
Each ControlNet has its own checkpoint and is loaded as a sidecar to the base SD.
Try it! Open a notebook and run:from diffusers import StableDiffusionControlNetPipeline; from diffusers.utils import load_image; image = load_image('https://example.com/photo.jpg'); ...and watch how the same prompt produces wildly different layouts depending on which ControlNet you use.
#Conditioning Scale: The Knob That Matters
conditioning_scale parameter. At 1.0, the conditioning dominates — the output strictly matches your control input. At 0.0, the ControlNet is bypassed entirely. Real production workflows use 0.5-0.8 to keep the prompt's creative freedom while honoring the structural constraint.Slide the knob yourself. The tool below uses small drawn maps, so you can see how the layout trades the prompt for the control map.
Do: Pick Pose, then drag Strength from 0 up to 1.5. Then set Guidance start to 50 percent and watch the lit sampler steps.Notice: At 0 the output is the layout the prompt alone would give. As strength rises the output follows the control map more and the prompt less, and at 1.5 it is a copy of the map. Switching the control on only for the second half of the steps barely moves the layout.Why: Strength is how loudly the side-network speaks relative to the prompt, and too loud drowns the prompt. Early steps decide the big shapes, so a late start misses them. Drawn stand-in, not a trained model: the output is a plain blend of two small maps.
You want to generate a portrait that matches a specific pose AND a specific art style. ControlNet alone, IP-Adapter alone, or both stacked?
#IP-Adapter: Image as a Second Prompt
Why a sum, and why alpha = 0 gives back the original model, is derived below.
Variants
- IP-Adapter Plus. Multi-scale image features for better detail
- IP-Adapter FaceID — specialized for portrait identity preservation
- IP-Adapter SDXL — adapted to SDXL's two text encoders
The big advantage over fine-tuning is that it needs no training. You drop in a reference image at inference time and the model generates variations of its style.
#Personalization: LoRA, Textual Inversion, DreamBooth
LoRA is the one to learn first. Picture a huge table of numbers that you must not edit. LoRA leaves it alone and adds a thin correction made by multiplying two small tables together. Only the two small tables are trained, so the result is a tiny file.
Recap: LoRA is taught from the start in Fine-Tuning LLMsLoRALoRA (Low-Rank Adaptation) fine-tunes large language models by decomposing weight updates into two small low-rank matrices, training only 0.1-1% of parameters while matching full fine-tuning performance.Learn more (track 5,fine-tuning-llms). Here you only need the picture above, plus why the patch is small, starts at zero and can be stacked.
LoRA itself is introduced in Transfer Learning. What is specific here is why the update is small, why it can start at zero, and why several can be stacked.
| Method | Data needed | Disk size | Compose with others | Quality |
|---|---|---|---|---|
| LoRA-Dreambooth | 5-30 images | 10-200 MB | ✓ Excellent (sum ΔW) | Very good |
| Textual Inversion | 5-30 images | <10 KB (one embedding) | ✓ Excellent (just adds a token) | Good for styles, weak for identity |
| DreamBooth (full FT) | 5-30 images | ~6 GB (full U-Net) | ✗ Hard (whole model swap) | Highest fidelity, prone to overfit |
Picture showing the model five photos of your dog and giving the dog a nickname. You must also remind it what ordinary dogs look like, or every dog becomes yours.
[V]. The crucial detail is the prior preservation loss — without it, fine-tuning on 5 photos of "my dog" rapidly makes every "a dog" prompt produce that specific dog. Prior preservation jointly trains on generic class images so the model retains its general knowledge.The second term is what keeps generic class prompts generic. A one-parameter toy shows the role of lambda.
Picture teaching the model one new word instead of new skills.
v* so the model treats it as "this concept I just showed you 5 photos of." Storage is 768 floats per concept (about 3 KB) — you can ship hundreds in megabytes. The loss is just the standard LDM loss with the embedding as the only trainable parameter.The objective is the ordinary noise-prediction loss with only v free. Open the derivation to see where its gradient comes from.
#Image Editing: img2img, Inpainting, Outpainting
Editing a real image is a different job from generating one from scratch.
- img2img: encode an existing image to latents, add noise to some intermediate timestep, denoise back guided by a new prompt. The
strengthparameter controls how much you destroy the original (0 = no change, 1 = pure prompt). - Inpainting: provide an image + a mask. Diffusion runs only on the masked region; outside is clamped to the original encoded latents at every step. Powers the "remove that person from my photo" workflow.
- Outpainting: same as inpainting but the mask is the outside of the original image. Extends a photo beyond its borders.
- Prompt-to-Prompt (Hertz 2022): edit a generated image by re-running with a slightly modified prompt and keeping cross-attention maps from the original at the unchanged tokens. "A bicycle" → "A red bicycle" while preserving everything else.
- Null-Text Inversion (Mokady 2022): invert a real image into the diffusion trajectory by optimizing the null-text embedding, then apply Prompt-to-Prompt edits. Used for editing real photographs.
#Image editing math: the canonical algorithms
The image-editing literature looks like a zoo of named tricks: SDEdit, Null-Text Inversion and Imagic. Underneath, each one is a small change to the standard diffusion loop. Each method below starts with a one-line picture, then gives the equation.
Picture smudging a photo with rain, then repainting it by following a new description.
The noised image on the left is the closed-form diffusion marginal, derived in Noise, Scores & Diffusion Models. SDEdit only chooses which t to start from.
Picture working out the exact recipe that would cook the dish you already have, so you can then change one ingredient.
∅_t per timestep so the CFG-guided trajectory exactly reproduces the source image. After inversion you change the conditional prompt while keeping the optimized null embeddings.The objective is a plain least-squares problem. What needs a reason is why the null embedding is the right thing to optimise.
Picture sliding a dial between "this exact dog" and "the dog doing what I asked".
e_opt so reconstructing the source image with e_opt minimizes the diffusion loss. (2) Fine-tune the U-Net briefly with e_opt to lock in the reconstruction. (3) Interpolate at inference between e_opt (preserves the subject) and the user's target text embedding e_tgt (drives the edit) with mixing weight η.You want users to upload a photo of their pet and generate 50 portraits of it in different art styles, served via a single shared model. Which approach is the best fit?
# Copy to Colab (needs a GPU, torch and diffusers; it cannot run in the browser)
# ControlNet + Stable Diffusion: generate from a Canny edge map
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
from diffusers.utils import load_image
from PIL import Image
import torch
import cv2
import numpy as np
# Load ControlNet for Canny edges
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/sd-controlnet-canny",
torch_dtype=torch.float16,
)
# Check the Hugging Face Hub for the current SD 1.5 repo id; the original
# runwayml/stable-diffusion-v1-5 repo was removed in 2024.
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
controlnet=controlnet,
torch_dtype=torch.float16,
).to("cuda")
# Load source image and extract Canny edges
src = load_image("https://example.com/photo.jpg")
src_np = np.array(src)
edges = cv2.Canny(src_np, 100, 200)
edges = np.stack([edges, edges, edges], axis=-1) # 3-channel
edges = Image.fromarray(edges) # the pipeline wants a PIL image
# Generate with prompt + edge conditioning
out = pipe(
prompt="oil painting of a medieval knight, dramatic lighting, by Rembrandt",
image=edges,
num_inference_steps=30,
controlnet_conditioning_scale=0.7, # 0.5-0.8 is a common starting range
guidance_scale=7.5,
).images[0]
out.save("knight_from_photo.png")
# CHALLENGE: stack a second ControlNet (depth) and an IP-Adapter (style reference).
# 1. controlnets = [canny_controlnet, depth_controlnet]
# 2. pipe = StableDiffusionControlNetPipeline(..., controlnet=controlnets)
# 3. pipe.load_ip_adapter("h94/IP-Adapter", subfolder="models", weight_name="ip-adapter_sd15.bin")
# 4. pipe(prompt=..., image=[canny, depth], ip_adapter_image=style_ref,
# controlnet_conditioning_scale=[0.6, 0.4], ...)
# Reduce each scale because they compete for the same residual budget.The second cell runs here. It is a 2-D toy of the same idea: a frozen base model, a control branch whose last layer starts at zero, and a conditioning scale you can sweep.
Tests: Verify that the output equals the base at step 0, that training cuts the error a lot, that the error is smallest at scale 1.0, and that two stacked controls do better at 0.5 each than at 1.0 each.
#ComfyUI Stacks: Production Reality
- Generate base — SDXL with text prompt, low conditioning_scale
- ControlNet pose — impose pose from OpenPose extraction of a reference photo
- IP-Adapter style — inject style from an art reference image
- LoRA character. Apply pre-trained character LoRA for identity
- Inpaint face — second pass on face region only with FaceDetailer
- Upscale — 2x with ESRGAN or 4x-UltraSharp
- Img2img refine — final 0.3-strength img2img for texture polish
This is six conditioning mechanisms stacked, plus two post-processing steps. Each step adds a control that a single prompt cannot give.
#Key Takeaways
- ControlNet's zero-init trick is the foundation of conditional fine-tuning — by initializing the new branch to output zero, the base model is undisturbed at step 0 and the conditioning signal is learned smoothly without destabilization
- IP-Adapter does style transfer at inference time, no fine-tuning required — decoupled cross-attention adds an image-conditioning branch to the U-Net, summed with the text branch via a weighting α
- LoRA is the production champion for personalization — composable (multiple LoRAs sum their ΔW), tiny on disk, fast at inference; LoRA-Dreambooth is the go-to for custom subjects and styles
- Real production stacks use 3-5 conditioning mechanisms simultaneously — ControlNet (composition) + IP-Adapter (style) + LoRA (identity) + inpaint refinement + upscaling is a typical ComfyUI workflow; tune
conditioning_scaledown when stacking - Image editing is a separate problem from generation — img2img, inpainting, outpainting, Prompt-to-Prompt, and Null-Text Inversion are the canonical techniques; each works at a different point in the diffusion trajectory
#Quick Check
Why does ControlNet use zero convolutions to connect the conditioning branch to the frozen base?