Skip to content
LearnAI

8.5ControlNet, LoRA, img2img & inpainting

Text alone is a blunt steering wheel. Start from an existing image, repaint only a masked region, pin down structure with edges or poses, or teach the model a new style with a small adapter.

⏱ 13 minIntermediate

Beyond “type a prompt and hope”

The Stable Diffusion lesson gave you a text-to-image machine. But a prompt is a blunt instrument. “A woman waving, seen from the left, in the exact pose of this photo, in my studio’s illustration style” is hard to say in words and harder for a text encoder to enforce. Designers want to start from a sketch, fix one hand, keep a character consistent across fifty images.

Remarkably, most of these controls need no new kind of model. They exploit one fact you learned in Diffusion: noising & denoising: sampling is a long sequence of small, inspectable steps, and the noisy state xtx_t at each step is just an image plus a known amount of noise. You can choose where to start, overwrite parts of xtx_t along the way, add extra inputs to the denoiser, or nudge its weights.

ANALOGY· A restorer with a half-finished painting

Hand a painter a photo and say “repaint this as a sunset”. If you smudge the photo only slightly first, they’ll keep everything and just change the colors. Smudge it heavily, and they’ll keep only the rough blobs of the layout and invent the rest. That smudging is img2img strength.

Put tape over part of the canvas and they can only paint inside the gap, matching the edges of what’s already there: that’s inpainting. Give them a tracing of the outlines to follow: ControlNet. And a weekend workshop on a particular artist’s technique, which leaves their skills intact but adds a new habit: that’s a LoRA.

img2img: start part-way down the mountain

Text-to-image starts from pure noise at t=Tt = T. img2imgimg2imgImage-to-image diffusion: noise an existing image part-way, then denoise it with a new prompt. 'Strength' sets how far into the noise you start. instead takes your input image x0srcx_0^{\text{src}}, noises it to an intermediate step t0t_0 in one shot with the closed form, and runs the ordinary sampler from there:

xt0=αˉt0 x0src+1−αˉt0 ε.x_{t_0} = \sqrt{\bar\alpha_{t_0}}\, x_0^{\text{src}} + \sqrt{1 - \bar\alpha_{t_0}}\,\varepsilon .

The strength setting (0 to 1) is simply t0/Tt_0 / T. Libraries also scale the step count: with 30 steps at strength 0.6, diffusers runs the last 18. Meng et al. introduced this idea as SDEdit (2021): adding noise erases detail but keeps coarse structure, and denoising toward the model’s data distribution makes the result realistic again.

The trade-off follows from what you know about the schedule. Noise destroys fine detail first and layout last. So at low strength the model can only change textures and colors; at high strength the layout itself is up for grabs, and at strength 1 the input is ignored entirely.

INTERACTIVEimg2img strength and inpainting
Task
Prompt
source image
noised start (t = 500)
result
start timestep
500
√ᾱ = 0.70 of the source survives
denoising steps
15 of 30
steps scale with strength
composition
kept
sun, tree and hills where the source had them?
RMS change vs source
0.272

The “model” is an exact denoiser for a toy training set of 16 tiny landscapes (8 daytime, 8 sunset, with different sun, tree and hill layouts); the prompt picks which 8 it is conditioned on. A real model has learned millions of images, but the mechanics of strength and masking are exactly these.

img2img: pick a prompt and sweep the strength. Low strength keeps the composition, high strength replaces it; try a few seeds at 0.9. Inpainting: paint a mask on the source (or use a preset) and the model regenerates only that region.

Things to try:

  1. “At sunset”, strength 0.1–0.3. The result is the source with a sunset tint. Only 1−αˉ\sqrt{1-\bar\alpha} worth of noise was added, and the denoiser keeps most of what it sees.
  2. Strength 0.5–0.7. A full sunset scene with the same composition: sun top-right, tree on the left. The noisy start still pins down the layout, and the model picks the training image most consistent with it.
  3. Strength 0.9–1.0, click “New seed”. The composition changes from seed to seed: the source has been noised away and the result depends mostly on the random noise.
  4. Inpainting, “Mask the tree”, then new seeds. Some seeds remove the tree and continue the hill; others put a tree back. Everything outside the mask stays pixel-identical.

Inpainting: keep what you know

InpaintingInpaintingRegenerating only a masked region of an image while keeping the rest, so the new content blends with its surroundings. regenerates only a masked region. The simplest method needs no retraining. At every sampling step, take the current xtx_t and overwrite the unmasked pixels with the original image noised to the same level tt; let the model’s update decide only the masked pixels. The known region keeps steering the denoiser through its predictions, so the new content tends to match its surroundings. Lugmayr et al.’s RePaint (2022) refined this with “resampling” (jumping back and forth in tt) to harmonize the boundary better.

Production systems usually go further and train a dedicated inpainting model. Stable Diffusion’s inpainting checkpoints take extra input channels, the mask and the VAE-encoded masked image, next to the noisy latent, so the network learns to blend seams directly. Outpainting is the same trick with the mask outside the original canvas.

ControlNet: structure from a side channel

Prompts are poor at geometry. ControlNetControlNetA trainable copy of a diffusion model's encoder, attached through zero-initialized convolutions, that conditions generation on edges, pose, depth and similar maps. (Zhang, Rao and Agrawala, 2023) adds a spatial conditioning input: an edge map, a human pose skeleton, a depth map, a segmentation map or a scribble. The design is clever because it doesn’t disturb the original model:

  1. Lock the pretrained U-Net’s weights.
  2. Make a trainable copy of its encoder blocks. The copy receives the noisy latent plus the condition image (encoded by a few small conv layers).
  3. Connect the copy’s outputs back into the locked U-Net’s skip connections through zero convolutions: 1×1 convolutions whose weights and biases start at exactly zero.

At the start of training, the zero convolutions output zero, so the combined model behaves exactly like the original, and no random noise is injected into a network that took enormous compute to train. Gradients still flow into the zero convs, so they gradually learn how much of the control signal to pass. The paper reports robust training with small datasets (under 50k pairs) as well as large ones, and the pairs are cheap to make: run an edge or pose detector over existing images.

ControlNets stack: a pose ControlNet and a depth ControlNet can steer the same generation, each with its own weight.

Adapters: new styles, subjects and image prompts

LoRA. The same LoRALoRALow-Rank Adaptation: freeze the original weights and learn a small low-rank update ΔW = B·A, which has far fewer parameters to train. technique used to fine-tune LLMs (see Fine-tuning: LoRA & QLoRA) applies to the U-Net or DiT, usually on its attention projection matrices. A frozen weight WW gets a low-rank update ΔW=BA\Delta W = BA, trained on a few dozen to a few thousand images of a style or character. The resulting files are megabytes instead of gigabytes, can be shared separately from the base model, and can be mixed with adjustable weights. Much of the open image ecosystem is built on these shareable adapters.

DreamBooth (Ruiz et al., 2022) fine-tunes the model on 3–5 photos of a specific subject bound to a rare token (“a photo of sks dog”), with a prior-preservation loss so the model doesn’t forget what ordinary dogs look like. It is often combined with LoRA to keep it lightweight.

Textual inversion (Gal et al., 2022) is even smaller: freeze the entire model and learn only a new word embedding for a pseudo-word like <my-cat> from a handful of images. It can capture a concept the model can already almost express, but less faithfully than weight fine-tuning.

IP-Adapter (Ye et al., 2023) lets you prompt with an image. It encodes a reference image with a CLIP image encoder and feeds it through separate, newly trained cross-attention layers alongside the text ones (“decoupled cross-attention”), with about 22M trainable parameters. Use it to transfer a style or a face without any per-subject training.

Combining controls in a real workflow

In practice these tools are layered. A typical editing session might start with a rough composition from text, fix the layout with a depth or pose ControlNet, apply a style LoRA at weight 0.7, then repair one hand with inpainting and finally run a low-strength img2img pass at a higher resolution to add detail (often called a “hires fix” or refiner pass). Each step reuses the same denoiser; what changes is where sampling starts, which pixels are frozen, and which extra signals enter the network.

Two practical details matter in latent diffusion. First, img2img and inpainting happen in the VAE latent space: the source image is encoded to a 64×64×4 latent, so a mask is downsampled by 8× and a tiny 5-pixel blemish may cover less than one latent pixel. Second, the decoder re-renders every pixel, so even unmasked areas can shift slightly after a round trip; editors often paste the original pixels back outside the mask at the end.

MATH CORNER · optionalHow much of the source survives img2img, and why zero convs don't freeze

Strength vs surviving signal. With the cosine schedule from the diffusion lesson:

strengtht0t_0αˉt0\sqrt{\bar\alpha_{t_0}} (signal)1−αˉt0\sqrt{1-\bar\alpha_{t_0}} (noise)SNR
0.252500.9200.3915.5
0.505000.7030.7110.98
0.757500.3800.9250.17
0.909000.1550.9880.025

At strength 0.5 signal and noise are equal, which is enough to fix the large-scale layout but not textures. At 0.9 the SNR is 0.025: pixel by pixel the source is buried, but averaged over large regions (say a 10×10 patch, where independent noise averages down by a factor of 10) coarse blobs can still survive, which is why even high strengths keep a faint echo of the source’s composition.

Zero convolution. A zero conv computes y=Wx+by = Wx + b with W=0,b=0W = 0, b = 0 at initialization. Its output is zero, but its gradients are not:

∂L∂W=∂L∂y x⊤≠0  whenever x≠0.\frac{\partial L}{\partial W} = \frac{\partial L}{\partial y}\, x^\top \neq 0 \ \text{ whenever } x \neq 0 .

After the first update WW is non-zero, and from then on gradients also flow back through WW into the trainable copy. So training starts from the exact behavior of the original model and departs from it only as far as the data demands.

In code

All of these are a few lines in diffusers (model names are examples of public checkpoints):

import torch
from diffusers import (StableDiffusionImg2ImgPipeline, StableDiffusionInpaintPipeline,
                       StableDiffusionControlNetPipeline, ControlNetModel)
base = "stable-diffusion-v1-5/stable-diffusion-v1-5"

img2img = StableDiffusionImg2ImgPipeline.from_pretrained(base, torch_dtype=torch.float16).to("cuda")
out = img2img(prompt="the same landscape at sunset", image=src, strength=0.6,
              num_inference_steps=30).images[0]          # runs ~18 of the 30 steps

inpaint = StableDiffusionInpaintPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16).to("cuda")
out = inpaint(prompt="a grassy hill", image=src, mask_image=mask).images[0]

cn = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
pipe = StableDiffusionControlNetPipeline.from_pretrained(base, controlnet=cn,
                                                         torch_dtype=torch.float16).to("cuda")
pipe.load_lora_weights("path/to/style_lora.safetensors")  # optional style adapter
out = pipe(prompt="a watercolor city street", image=canny_edges).images[0]
COMMON MISCONCEPTIONS
  • “img2img edits the image directly.” It noises your image and then generates from that noisy start. Even at low strength every pixel is resynthesized; that’s why faces or text in the source can subtly change.
  • “Strength 0.5 means a 50/50 blend of source and new image.” Strength picks a point on the noise schedule. How much survives depends on the schedule (αˉt\sqrt{\bar\alpha_t}) and on scale: coarse layout survives much longer than fine detail.
  • “ControlNet retrains Stable Diffusion.” The base model is locked. ControlNet trains a separate copy of the encoder and connects it through zero-initialized convolutions, so it can be added or removed at will.
  • “A LoRA contains the images it was trained on.” It’s a small low-rank weight update. It encodes a tendency (a style, a character’s features), not a stored picture, although heavily overfit LoRAs can reproduce training images closely.

Check your understanding

0/5 answered
  1. Q1.In img2img, what does the strength parameter control?

  2. Q2.You use img2img with strength 0.2 and the prompt "at sunset". What do you expect?

  3. Q3.In the simple (RePaint-style) inpainting method, what happens to the unmasked pixels at each step?

  4. Q4.Why does ControlNet connect its trainable copy through zero-initialized convolutions?

  5. Q5.You want many images of the same illustrated character in different scenes. Which tool fits best?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.