ControlNet: Adding Conditional Control to Text-to-Image Diffusion Models
Freeze a text-to-image model, train a copy of its encoder on edge maps or poses, and join the two through layers that start at zero.
ControlNet steers Stable Diffusion with a spatial guide such as an edge map, a depth map, or a pose skeleton, using a trainable copy of the U-Net encoder connected through zero-initialized convolutions so training begins from the unmodified model.
Explaining the paperAdding Conditional Control to Text-to-Image Diffusion ModelsTraining a spatial condition on 50,000 image pairs when the base diffusion model was pretrained on billions risks overfitting and catastrophic forgetting. Zero-initialized connections preserve Stable Diffusion's output at step 0 while passing nonzero gradients to the output convolutions on step 1 and into the copied encoder from step 2 onward.
Why text prompts miss layout, and why direct fine-tuning fails
A text-to-image diffusion model such as Stable Diffusion generates a 512×512 picture by starting from random noise and refining it over dozens of denoising steps while a text prompt steers each step. That text interface specifies what appears in a scene, yet it has almost no vocabulary for exact geometry. Typing "a dancer, left arm raised, seen from slightly below" leaves the angle of the elbow, the horizon line, the framing, and the camera distance unspecified. Getting a particular composition out of a prompt-only model reduces to rewording the caption and drawing dozens of random seeds until one happens to land near the layout you pictured.
Computer vision already had models built for direct spatial control. Image-to-image translation networks take a spatial map directly as input (a Canny edge drawing from a classic gradient edge detector, a human pose skeleton, a depth map where brightness encodes distance from the camera, or a color-coded semantic segmentation mask) and learn to render a matching photograph. Training such a model from scratch, or fine-tuning a large text-to-image model on paired examples, hits a wall of data scale. The ControlNet paper (Lvmin Zhang, Anyi Rao, and Maneesh Agrawala, Stanford University, posted February 2023 and published at ICCV 2023) notes that task-specific datasets for surface normals, human poses, or segmentation typically hold at most about 100,000 paired examples. Stable Diffusion was trained on LAION-5B, a web crawl of roughly five billion image-text pairs, 50,000 times larger.
The straightforward way to add a spatial input to Stable Diffusion is to widen its first convolutional layer to accept extra channels for the edge map or depth map, then continue training all 860 million weights of its denoising network on the paired dataset. Stability AI built its Stable Diffusion V2 Depth-to-Image model this way, and the first arXiv version of the ControlNet paper uses that exact recipe as its baseline. With more than 12 million training pairs and thousands of GPU-hours on a data-center cluster, direct fine-tuning works. With tens of thousands of examples, updating all 860 million parameters runs into two well-known failure modes: overfitting, where the network memorizes the small dataset's specific textures and lighting, and catastrophic forgetting, where gradients from the narrow task overwrite the broad visual knowledge learned from billions of web images.
A standard way to avoid catastrophic forgetting is to freeze the pretrained model and train only a small number of new parameters, as LoRA (Low-Rank Adaptation, Hu et al., 2021) does by adding a low-rank matrix product to existing weight matrices. The ControlNet authors argue that low-rank updates have too little capacity to parse arbitrary spatial inputs in the wild. Interpreting a rough hand-drawn scribble, or mapping a segmentation mask with 150 object classes into realistic lighting and perspective, takes a deep visual encoder. Instead of building a tiny adapter from scratch or risking the base model's weights, how can you give the new spatial condition a deep, already-trained visual backbone while leaving the pretrained model untouched?
ControlNet answers that question by splitting the problem into two copies. The pretrained model stays completely frozen so none of its capabilities can be overwritten. Beside it, ControlNet creates a full trainable clone of the pretrained encoder, initialized with the exact same weights, so the spatial branch starts out knowing how images are structured at every scale. The clone and the frozen model meet only through convolution layers whose weights and biases start at zero.
How ControlNet works on one block
Inside a convolutional or transformer vision network, an image is represented at each intermediate stage as a 3D grid of numbers called a feature map, with shape : height , width , and channels. Each cell holds a -dimensional vector describing what appears at that spatial patch (oriented edges near the top of the network, object parts and scene layout deeper down). A network block is any reusable group of layers, such as a ResNet residual block, a convolution-normalization-activation stack, or a Vision Transformer attention block, that maps an input feature map to an output feature map using trained parameters :
In Stable Diffusion, a mid-level block might take a feature map and output another map . Now suppose we also have a spatial condition feature map of the same spatial shape, encoding an edge drawing or pose skeleton, and we want the block's output to reflect both and without risking the trained weights .
ControlNet locks so gradient updates never touch it, clones into a trainable copy with parameters initialized equal to , and inserts two 1×1 convolution layers whose weights and biases are initialized to zero. The condition enters through the first zero convolution, adds to , passes through the trainable copy, passes through the second zero convolution, and adds onto the locked block's output:
Read equation (2) from the inside out. The first term, , is the original frozen block running identically to before. Inside the second term, translates the condition map into an offset that gets added to the normal input . The trainable copy processes that combined map, and the second zero convolution projects the copy's output into a residual correction added onto the locked block's output .
A 1×1 convolution looks at one pixel at a time: at each position , it multiplies the -element channel vector by a weight matrix and adds a -element bias vector, applying the exact same linear layer independently at every spatial cell without blurring across neighbors. Because every weight and bias in both and starts at zero, both calls return an all-zero tensor on the first forward pass regardless of their input. Equation (2) collapses to
At initialization, the trainable copy is already computing real features rather than outputting zeros. Because , the copy receives , and because , it computes the exact same feature map as the frozen block before zeroes out the branch. In software engineering terms, the arrangement behaves like shipping a parallel code path behind a feature flag set to off: production output is bit-for-bit identical on step 0 while the new path is already wired up and executing. The analogy stops at the switch itself, because here the flag is the weight matrix , which gradient descent moves smoothly away from zero as training runs.
Why zero convolutions still learn
Standard neural network advice forbids initializing weights to zero. If every layer in a multi-layer network starts at zero, every hidden neuron computes the same output, receives the same gradient, and stays permanently identical to its neighbors (symmetry collapse). ControlNet sidesteps that trap because zero initialization applies only to the two 1×1 boundary layers. Between them, the trainable copy holds distinct, pretrained weights , so different channels compute different features and break symmetry from step 1.
If a layer multiplies its input by zero, does backpropagation stall and leave every parameter stuck at zero? The partial derivatives of a 1×1 convolution show why gradients still move, and produce a strict two-step wake-up sequence. Write a 1×1 convolution with input , weight matrix , and bias vector at pixel and output channel :
Each output channel is a dot product between row of and pixel 's input vector, plus . Taking partial derivatives with respect to the bias, the weights, and the input gives three expressions:
Let be the upstream loss gradient arriving at the output of the zero convolution. Applying the chain rule and summing over all spatial pixels separates what happens to the layer's own weights from what passes backward to the layers before it:
When , the right-hand gradient is identically zero: the zero convolution blocks any gradient from flowing backward into its input. The left-hand gradient does not depend on ; it depends only on the upstream error and the layer's nonzero input .
A concrete two-channel calculation makes the two-step transition explicit. Take a single pixel with input vector , upstream loss gradient , initial and , and learning rate . On step 1, the weight gradient is the outer product while the input gradient is zero:
After one gradient-descent update at , the parameters move away from zero while passing no gradient backward to earlier layers:
On step 2, is nonzero, so multiplying the same upstream gradient yields the nonzero vector = [-0.0625, 0.03125]T and gradients begin reaching the layers before the zero convolution.
Tracing that rule across the three trainable parts of equation (2) on step 1 gives a strict ordering:
- Z2, the output zero convolution. Its input is the trainable copy's output, which equals and is nonzero. Its upstream gradient is the loss gradient at , nonzero whenever the frozen model does not already match the target. Both and receive a nonzero gradient and move on step 1.
- The trainable copy. Its gradient must travel backward through Z2, which multiplies by . The copy receives exactly zero gradient on step 1 and stays frozen at its pretrained weights for that first update.
- Z1, the input zero convolution. Its weight gradient multiplies its upstream gradient by , and that upstream gradient has to pass through both Z2 and the copy, so Z1 also receives zero gradient on step 1.
Once step 1 shifts by times its gradient from above, step 2 sends a nonzero gradient through Z2 into the copy and onward into Z1. Paper v1 derives the first-step update for a single zero convolution; the ordering across Z2, the copy, and Z1 follows directly from the same derivatives. The pattern mirrors LoRA, where initializing keeps at step 0, updates on step 1, and begins updating on step 2. Zero-initialized output convolutions also predate both papers: the ADM diffusion codebase of Dhariwal and Nichol (2021) wraps the last convolution of every residual block in a helper called zero_module, which the ControlNet authors cite directly.
Figure 1 trains a 4-channel toy ControlNet block directly in your browser using exact hand-coded backpropagation on 24 pairs whose target is built from the pretrained block's own features. The figure numbers states by completed updates, so step 0 shows the initial weights together with the first update's gradients, and step 1 shows the weights after that first update together with the second update's gradients. Start at init scale 0 and step 0 and inspect the gradient norm printed beneath each box: Z2 shows 4.15 while both the copy and Z1 print exactly 0, and output deviation is 0. Advance one step to step 1: all three gradients are now nonzero, yet the copy's drift from its pretrained weights (right plot) is still 0 because its step-0 gradient was zero. Then raise the init scale slider to replace the zero convolutions with randomly initialized layers.
Raising the init scale shows what random connecting weights do on step 0: the branch injects random offsets into immediately, and backpropagating through random weights in Z2 sends a random-direction gradient into the pretrained copy before Z2 has learned what the condition means. At scale 1.5 in the toy, initial loss roughly doubles relative to zero init and the copy finishes 40 steps about 2.7 times farther from its pretrained weights. The paper describes this phenomenon as harmful noise reaching the pretrained backbone. Its direct evidence on Stable Diffusion is the ablation in Section 4.2: replacing the zero convolutions with standard Gaussian-initialized convolutions degraded sketch-conditioned generations to roughly the level of ControlNet-lite, a stripped-down variant that replaces each copied encoder block with a single convolution layer. The authors interpret that drop as destruction of the copy's pretrained features during fine-tuning. That ablation is qualitative (random batches of six images per setting, no numeric score), and the 4-channel browser toy is too small to reproduce backbone destruction; at small nonzero scales in the toy, training converges as cleanly as zero init or slightly faster.
How ControlNet attaches to Stable Diffusion
To see every tensor shape and memory trade-off, we need the layout of Stable Diffusion 1.5. Stable Diffusion is a latent diffusion model: instead of running a denoiser directly on 512×512×3 RGB pixels (786,432 numbers), a frozen variational autoencoder (VAE) compresses each image by a factor of 8 in height and width into a 64×64×4 latent grid (16,384 numbers, multiplied by the constant scale factor 0.18215 to keep unit variance). A U-Net then learns to predict the noise added to that 64×64×4 latent. Text prompts enter via cross-attention as 77 token vectors of width 768 produced by the frozen CLIP (Contrastive Language-Image Pre-training, a vision-language model that maps images and text into a shared embedding space) text encoder (1,024 wide in Stable Diffusion 2.1, which shares the exact same U-Net wiring), and the diffusion timestep enters as a sinusoidal embedding.
Stable Diffusion's U-Net has 25 blocks arranged in a U shape: 12 encoder blocks that progressively halve the spatial grid across four resolutions (64×64, 32×32, 16×16, and 8×8, three blocks at each resolution), 1 middle block at the 8×8 bottleneck, and 12 decoder blocks that upsample the grid back to 64×64. As the encoder downsamples, spatial precision shrinks while channel depth grows (from 320 channels at 64×64 up to 1,280 channels at 16×16 and 8×8). To keep fine spatial detail from washing out at the 8×8 bottleneck, the U-Net sends each encoder block's output sideways across a skip connection and concatenates it onto the input of the matching decoder block in last-in, first-out order: encoder block feeds decoder block .
ControlNet treats that entire 12-block encoder plus 1 middle block as the block in equation (2). It locks the whole U-Net (all 859,520,964 parameters) and creates a trainable copy of the input convolution, timestep embedding, 12 encoder blocks, and middle block (348,712,960 parameters, 40.6% of the U-Net). The copy receives the same noisy latent, timestep, and CLIP text embeddings as the locked encoder. Rather than attaching a single output zero convolution at the very end, ControlNet places 13 separate 1×1 zero convolutions, one on each of the 12 copied encoder blocks and one on the copied middle block. Their outputs are added elementwise to the 12 skip connections (right before concatenation into the decoder) and to the locked middle block's output, so every resolution of the frozen decoder receives a spatial correction without duplicating or modifying a single decoder weight.
Before the condition image can enter the copy, its spatial dimensions must match the U-Net's first feature map. A user supplies an edge map, depth map, or pose skeleton at full 512×512×3 pixel resolution, whereas the copy's first layer converts the 64×64×4 noisy latent into a 64×64×320 feature map. ControlNet bridges the 8× spatial gap with a small convolutional condition encoder trained jointly from scratch, mapping the 512×512×3 image-space condition to a 64×64×320 feature-space condition :
In the official code (input_hint_block in cldm/cldm.py), consists of eight 3×3 convolutions with SiLU (Sigmoid Linear Unit, a smooth nonlinear activation function). Three of those layers use stride 2 to halve the resolution three times (512 → 256 → 128 → 64) while stepping channel counts through 16, 16, 32, 32, 96, 96, and 256. The eighth layer is a zero-initialized 3×3 convolution projecting 256 channels to 320 channels (1,086,480 parameters for in total). Its 64×64×320 output is added once to the copy's feature map immediately after the copy's first convolution (conv_in). That final zero-initialized layer acts as in equation (2), guaranteeing at initialization. (The paper's Section 3.2 text instead describes four 4×4 stride-2 layers with ReLU, a Rectified Linear Unit that zeroes negative values; four stride-2 halvings divide 512 by 16 to give 32×32 rather than 64×64, and the Provenance panel documents the discrepancy.)
Figure 2 maps all 13 connections of Stable Diffusion 1.5's U-Net side by side. Click or scrub any row to inspect its tensor dimensions, zero-convolution parameter count, and target decoder block. Switch to gradients to see which frozen blocks still carry backward activations, and inspect inference scales (used in the guidance section below) to compare resolution weighting formulas.
The gradients view in Figure 2 explains why ControlNet is relatively cheap to train. Because nothing upstream of the locked U-Net encoder or locked middle block is trainable, the official code runs both inside torch.no_grad() (cldm/cldm.py lines 25–32) and stores none of their intermediate activations for backpropagation. The locked decoder cannot use no_grad(): ControlNet's 13 outputs enter at the decoder's skip inputs, so the backward pass must still propagate activation gradients through the decoder to reach the ControlNet, even though no decoder weights are updated. Benchmarked on a single NVIDIA A100 PCIe 40GB GPU, training Stable Diffusion with ControlNet uses roughly 23% more GPU memory and 34% more time per iteration than training Stable Diffusion alone. Counting every tensor in the released SD 1.5 checkpoint (sd-controlnet-canny), the trainable branch totals 361,279,120 parameters: 348,712,960 for the copied encoder and middle block, 1,086,480 for , and 11,479,680 for the thirteen 1×1 zero convolutions (four 320-channel layers at 102,720 parameters each, three 640-channel layers at 410,240 each, and six 1,280-channel layers at 1,639,680 each).
Training, prompt dropout, and sudden convergence
ControlNet does not introduce a new loss function, discriminator, or perceptual penalty. It trains with the exact same noise-prediction objective from DDPM (Denoising Diffusion Probabilistic Models) that trained Stable Diffusion originally. Given an uncorrupted image's latent , pick an integer noise step uniformly from 0 to 999, draw unit Gaussian noise of shape 64×64×4, and blend them according to the noise schedule :
Under Stable Diffusion 1.5's 1,000-step linear schedule (linear_start = 0.00085, linear_end = 0.0120), drops from nearly 1 at (almost pure image) down to 0.0047 at (almost pure noise). Halfway through at , the signal weight is 0.526 and the noise weight is 0.851. The combined model (frozen U-Net plus trainable ControlNet) takes the noisy latent , timestep , text prompt , and encoded spatial condition , predicts the added noise , and minimizes mean squared error:
Equation (6) is equation (5) of paper v3 (shifted by one because this page numbers the 1×1 convolution as equation (4)). Predicting which portion of a corrupted latent is random noise forces the network to infer what uncorrupted image lies underneath; once the spatial condition is available, using edges or poses reduces the noise-prediction error wherever the prompt alone is ambiguous. In the official training script, one batch of 4 target images (scaled to ) and 4 condition maps (scaled to ) produces a 64×64×4 predicted noise tensor, computes the squared error against , backpropagates through the frozen decoder into the 361M ControlNet weights, and applies one AdamW (adaptive gradient optimizer with decoupled weight decay) update at learning rate 1e-5.
Building a training dataset requires no manual drawing for most conditions. Take existing captioned photos and run an off-the-shelf vision detector over each photo to extract its spatial condition: Canny edge detection, HED (Holistically-Nested Edge Detection) soft edges, M-LSD (Mobile Line Segment Detection) straight lines, MiDaS monocular depth maps, OpenPose human keypoint skeletons, or semantic segmentation maps. That yields triples of (image, caption, condition). The v1 paper documents the budgets across tasks: the Canny edge model trained on 3 million triples for 600 NVIDIA A100 80G GPU-hours, whereas the surface-normal model trained on 25,452 triples from the DIODE indoor-and-outdoor scan dataset (captioned automatically with BLIP) for 100 A100 80G GPU-hours. For very large datasets of at least one million pairs (on 8 or more A100 80G GPUs), v1 Section 3.4 recommends training ControlNet alone for more than 50,000 steps and then unlocking Stable Diffusion weights for joint fine-tuning. In the released code, setting sd_locked = False adds only the decoder's output_blocks and final out layer to AdamW while leaving the encoder locked.
During training, 50% of the text prompts are randomly replaced with the empty string "". When a training sample arrives without a caption, the text cross-attention carries no information about whether the target image is a cathedral, a deer, or a kitchen. The only clue is in the spatial map . Dropping half the prompts forces the ControlNet copy to learn visual recognition directly from edges, depth gradients, and skeletons, so at test time the model handles all four prompt regimes tested in Section 4.2: an empty prompt, an insufficient generic prompt ("a high-quality, detailed, and professional image"), a conflicting prompt that reinterprets the shape, or a specific matching prompt.
Monitoring sample images across training revealed an unexpected behavior the authors name the sudden convergence phenomenon. Because the zero convolutions begin at zero, the model outputs sharp, normal Stable Diffusion pictures from step 0 onward, rather than blurry noise-to-image progressions. For thousands of steps, those outputs ignore the condition image completely. Then, within a narrow burst of updates, samples abruptly snap to the condition geometry. In the example run printed in the paper (learning rate 1e-5, AdamW, no exponential moving average of weights), generated samples still ignore the condition at step 6,100 and follow it accurately by step 6,133; the authors report that this jump usually occurs before 10,000 optimization steps. The paper presents this from visual sample grids without a training loss curve or a mechanistic explanation.
Classifier-free guidance, resolution weighting, and stacking
At sampling time, Stable Diffusion relies on classifier-free guidance (CFG) to produce sharp, prompt-faithful images. Plain conditional diffusion averages over many plausible images that loosely fit a caption, which often looks washed out. CFG fixes that by running the U-Net twice on the same noisy latent at every denoising step: once conditioned on the user's prompt to get , and once with an empty or negative prompt to get an unconditional prediction . The difference points in the direction that makes the image match the prompt better, and CFG extrapolates along that vector by a scale factor :
Equation (7) is identical to Ho and Salimans's formulation with . All results in the ControlNet paper sample with over 20 steps of DDIM (Denoising Diffusion Implicit Models, a deterministic sampler that jumps across the 1,000 training noise levels in 20 large steps).
Adding a ControlNet creates an immediate routing choice: should the spatial condition enter both the conditional pass and the unconditional pass , or only ? Check what happens to the difference in each case:
- Condition in both branches. Because the spatial map enters both and , its contribution remains in the baseline and cancels out of . Guidance amplifies the text prompt by while the spatial condition applies at strength. If the user supplies an empty prompt, both passes receive identical inputs, so identically and CFG vanishes (paper Figure 5b).
- Condition in only. Now the spatial map appears only on the conditional side, so its effect is inside and gets multiplied by . With an empty prompt, guidance amplifies the condition alone by 9×, which over-drives fine details and produces overly rigid, high-contrast artifacts (paper Figure 5c).
Figure 3 illustrates this exact geometry with a 2D linear toy denoiser where the prompt shifts the noise prediction rightward and the spatial condition shifts it upward. Start with a prompt given and control in both branches, then toggle the prompt to empty and drag : the guided point stops moving altogether. Next switch to control in eps_c only and watch the control multiplier track directly.
To get prompt-free generation without 9× over-driving, the paper introduces CFG Resolution Weighting (CFG-RW): feed the condition to only, and multiply each of the 13 skip connections by , where is that block's spatial size. The 64×64 blocks get weight 1, 32×32 gets 2, 16×16 gets 4, and the 8×8 blocks get 8. The official demo (gradio_canny2image.py) ships the same coarse-over-fine idea under the name guess mode, but with a different exponential formula: control is dropped from , and connection (0 to 12, from the first 64×64 block to the 8×8 middle block) is multiplied by strength times , ranging from 0.0994 at block 0 up to 1.0 at the middle block (the code's inline comment writes 0.825**12 < 0.01, off by a factor of 10 from 0.0994). Both schedules weight the coarse 8×8 layout roughly 8 to 10 times higher than the fine 64×64 edges, though their absolute magnitudes differ (the paper's weights are at least 1, the code's at most 1 at strength 1.0). Outside guess mode, the demo sends control to both branches and multiplies all 13 outputs by one uniform strength slider (default 1.0, range 0 to 2).
Because ControlNet injects its outputs additively into the U-Net's 13 skip and middle connections, combining multiple spatial conditions requires no retraining and no blending network. Run a pose ControlNet and a depth ControlNet on the same noisy latent, and add their 13 feature maps directly onto the same 13 connections: the paper reports that direct summation works without extra weighting or interpolation. The same modular wiring allows zero-retraining transfer across community fine-tunes of Stable Diffusion 1.5. Because fine-tuned style checkpoints such as Comic Diffusion and Protogen 3.4 keep the identical U-Net layer shapes and 768-dimensional CLIP interface, a ControlNet trained on base SD 1.5 plugs directly into them.
Figure 4 builds an illustrative 2D multi-scale model of those four U-Net resolutions (8×8 global layout, 16×16 object shapes, 32×32 contours, 64×64 crisp edges) combining into the decoder's skip input. Switch between uniform (1.0), guess mode, and paper 64/h to see how attenuating the fine 64×64 band lets coarse layout lead without over-driving edges. Raise both edge s1 and pose s2 to watch two ControlNets compose by direct addition, drag both to 0 to confirm the frozen baseline is untouched, and push strength toward 2.0 to see fine cells saturate.
What the experiments show
The paper tests ControlNet across eight condition types (Canny edges, HED soft edges, M-LSD straight lines, MiDaS depth maps, surface normals, ADE20K semantic segmentation, OpenPose human skeletons, and hand-drawn sketches) and evaluates performance with three benchmark tables plus a human comparison against Stability AI's industrial depth model. Figure 5 plots all three tables interactively.
- Human preference on sketches (Table 1). Twelve raters ranked outputs from five methods across 20 unseen hand-drawn sketches on a 1 (worst) to 5 (best) scale, once for overall image quality and once for sketch fidelity. The baselines were PITI (Pretraining-based Image-to-Image translation, built on OpenAI's GLIDE diffusion model), Sketch-Guided Diffusion (Voynov et al., which nudges each denoising step with a learned edge predictor at guidance weight ), and ControlNet-lite (the single-convolution ablation). Sketch-Guided Diffusion shows a sharp trade-off: doubling its edge-guidance scale from to lifted fidelity from 2.31 to 3.28 while dropping quality from 3.21 to 2.52. ControlNet topped both axes at 4.22 (±0.43) for quality and 4.28 (±0.45) for fidelity, ahead of ControlNet-lite (3.93 / 4.09) and PITI (1.10 / 1.02).
- Semantic layout recovery on ADE20K (Table 2). ADE20K is a scene-parsing dataset whose masks label every pixel across 150 categories (sky, building, road, chair, person). To measure whether generated photos put objects where the mask asked, the authors generated images from ADE20K test masks, ran the pretrained OneFormer segmentation model on the generated images, and computed IoU (Intersection over Union: the area where predicted and target class masks overlap divided by their combined area, from 0 to 1, higher is better). Running OneFormer on the real ground-truth ADE20K photographs achieves an IoU of 0.58 (±0.10), which sets the practical ceiling for the metric. ControlNet reaches 0.35 (±0.14), roughly 60% of that ceiling, ahead of ControlNet-lite (0.32), segmentation-conditioned LDM (Latent Diffusion Model, 0.31), PITI (0.26), and VQGAN (Vector-Quantized Generative Adversarial Network, a discrete image-token generator, 0.21).
- Image quality and prompt alignment (Table 3). On the same ADE20K segmentation task, the paper reports three automatic scores. FID (Fréchet Inception Distance) compares feature statistics of generated and real images inside a pretrained Inception vision network; lower is better. CLIP score measures cosine similarity between generated image embeddings and text prompt embeddings in CLIP space; higher is better. CLIP aesthetic score runs a linear predictor trained on human aesthetic ratings over CLIP embeddings; higher is better. ControlNet scores 15.27 FID, beating ControlNet-lite (17.92), PITI (19.74), and from-scratch LDM (25.35) and VQGAN (26.28). Plain Stable Diffusion with no segmentation input scores 6.09 FID; it serves as a quality reference rather than a layout competitor because it can draw any scene layout it likes. ControlNet's CLIP score (0.26) and aesthetic score (6.31) match unconditioned Stable Diffusion's 0.26 and 6.32, showing that locking the base model keeps its visual fidelity and text alignment intact.
The paper also compares ControlNet head-to-head against Stability AI's industrial Stable Diffusion V2 Depth-to-Image model (SDv2-D2I), which was trained on more than 12 million images using thousands of NVIDIA A100 GPU-hours. The authors trained a depth ControlNet on Stable Diffusion 2 using 200,000 samples on a single consumer NVIDIA RTX 3090 Ti GPU for 5 days. They showed 12 raters 100 labeled images from each model to learn their visual quirks, then asked those raters to identify which model produced each of 200 new images. The raters achieved an average precision (the fraction of images flagged as one model that came from it, where 0.50 corresponds to random guessing on a balanced split) of 0.52 (±0.17), meaning observers could barely distinguish the 5-day single-GPU ControlNet from the 12-million-image cluster run.
ControlNet also tolerates tiny datasets. Training on as few as 1,000 edge-image pairs does not collapse the frozen model and still produces a recognizable lion from a lion edge map, with visual fidelity improving as the training subset scales up (shown qualitatively in Figure 10 of the paper, without a quantitative curve).
Limits and open questions
Several gaps in the paper matter if you implement or deploy ControlNet in production:
- Sudden convergence lacks an explanation. Zero initialization explains why early samples stay clean while ignoring the condition, since the connecting weights begin at zero. The paper offers no loss curve and no theoretical or empirical mechanism explaining why condition following switches on abruptly over roughly 33 steps (6,100 to 6,133 in the paper's shown run) rather than ramping smoothly.
- Small human studies and qualitative ablations. Table 1 rests on 12 users and 20 sketches. Section 4.3 calls the metric Average Human Ranking (AHR) while Table 1's caption calls it Average User Ranking (AUR), and the text reports 100 rankings per criterion (20 sketches times 5 methods) without stating how the 12 raters' individual scores were aggregated into those 100 rankings. Section 4.2's architectural ablations (replacing zero convolutions with Gaussian weights, or shrinking the copy to ControlNet-lite across the four prompt settings in Figure 8) are shown as qualitative 6-image grids; ControlNet-lite is later scored in Tables 1–3, whereas the Gaussian-init ablation and the community-model transfers (Comic Diffusion, Protogen 3.4, Figure 12) never receive numerical metrics. Very small nonzero random initializations and copying the U-Net decoder were never tested.
- Per-step inference cost. Because the trainable copy takes the noisy latent and timestep as inputs, its 13 feature maps change on every denoising step and cannot be precomputed once. Running one ControlNet adds a 361-million-parameter pass onto every 860-million-parameter U-Net call, twice per step under default classifier-free guidance (dropping to once per step only in guess mode). Stacking two or three ControlNets multiplies that added compute linearly. Concurrent lightweight designs such as T2I-Adapter avoid per-step re-encoding by running a small image-only encoder once before the denoising loop, at the cost of giving the adapter no access to the noisy latent or text prompt.
- Ambiguous or misread spatial maps. When a condition image is visually ambiguous and the text prompt does not clarify it, ControlNet guesses an interpretation (Figure 11 of v3 shows a bare silhouette rendered as different objects). Section 5 of v1 highlights the harder failure mode: once ControlNet misidentifies the semantics of an input condition map, even supplying a strong corrective text prompt often fails to override the wrong reading.
- Ad-hoc resolution weights. Neither the paper's rule nor the demo's guess-mode decay comes with a derivation or quantitative sweep beyond the visual strip in Figure 5d.
Training and sampling in pseudocode
The first listing implements one training iteration using the exact tensor shapes of Stable Diffusion 1.5. Both the VAE and the CLIP text encoder stay frozen under no_grad(); the locked U-Net encoder and middle block also run inside no_grad(), while gradients pass through the locked decoder so AdamW updates only the ControlNet parameters.
# One ControlNet training step (SD 1.5, 512x512, batch of 4)
img, hint, caption = batch() # img [4,512,512,3] in [-1,1]
# hint [4,512,512,3] in [0,1]
if rand() < 0.5: caption = "" # 50% empty prompts (Sec. 3.3)
with no_grad():
z0 = 0.18215 * vae.encode(img) # [4,64,64,4] scaled latent
txt = clip_text(caption) # [4,77,768] CLIP token vectors
t = randint(0, 1000, size=4) # [4] one noise step per image
eps = randn(4, 64, 64, 4) # [4,64,64,4] Gaussian noise
zt = sqrt(abar[t]) * z0 + sqrt(1 - abar[t]) * eps # [4,64,64,4] noised
# Eq. (5): hint -> input_hint_block -> [4,64,64,320], added after conv_in
# Eq. (2): copy of 12 encoder blocks + middle block -> 13 zero-conv outputs
ctrl = controlnet(zt, t, txt, hint=hint) # 13 maps: 64x64x320 .. 8x8x1280
# Locked encoder + middle run under no_grad(); ctrl added to 13 skips/mid
eps_hat = unet(zt, t, txt, control=ctrl) # [4,64,64,4] predicted noise
loss = mean((eps - eps_hat) ** 2) # Eq. (6), SD's own DDPM loss
loss.backward() # grads cross decoder; only ControlNet updates
adamw_step(controlnet.parameters(), lr=1e-5)Sampling runs the ControlNet inside every DDIM step. The branch below contrasts default inference (control in both guidance passes, uniform scale) against the released demo's guess mode (control in only, exponential resolution decay ).
# Sampling with one ControlNet: DDIM, 20 steps, guidance 9.0 (Eq. 7)
txt_c = clip_text(prompt) # [1,77,768] prompt embedding
txt_uc = clip_text(negative_prompt) # [1,77,768] often ""
z = randn(1, 64, 64, 4) # [1,64,64,4] pure noise
for t in ddim_timesteps(20): # 999 ... 0
raw_c = controlnet(z, t, txt_c, hint) # 13 maps: 64x64x320 .. 8x8x1280
ctrl_c = [s * m for s, m in zip(scales, raw_c)]
eps_c = unet(z, t, txt_c, control=ctrl_c) # [1,64,64,4]
if guess_mode: # control in eps_c only
eps_uc = unet(z, t, txt_uc, control=None) # [1,64,64,4]
else: # default: control in both
raw_u = controlnet(z, t, txt_uc, hint)
ctrl_u = [s * m for s, m in zip(scales, raw_u)]
eps_uc = unet(z, t, txt_uc, control=ctrl_u) # [1,64,64,4]
eps = eps_uc + 9.0 * (eps_c - eps_uc) # Eq. (7) CFG, beta_cfg = 9.0
z = ddim_update(z, eps, t) # [1,64,64,4] denoised step
image = vae.decode(z / 0.18215) # [1,512,512,3] RGB pixels
# scales: [strength] * 13 by default;
# [strength * 0.825 ** (12 - i) for i in range(13)] in guess modeTwo conventions in tutorial_dataset.py and cldm/cldm.py are not specified in the paper: the condition image hint is normalized to whereas the target photo img is normalized to before the VAE, and unlocking Stable Diffusion via sd_locked = False adds only the decoder's output_blocks and final out layer to AdamW while keeping the U-Net encoder frozen.
Questions you might still have
Is ControlNet a kind of LoRA?
Both start as an exact no-op on a frozen model, and both use a zero-initialized factor to get there. They differ in size and placement. LoRA adds a low-rank matrix product BA to individual weight matrices inside the existing layers. ControlNet adds a separate full-size copy of the U-Net encoder and middle block, 361 million parameters for Stable Diffusion 1.5, whose outputs are added to the skip connections. The LoRA explainer covers the low-rank version.
Why not initialize the connecting convolutions with small random weights instead of zeros?
Zero initialization guarantees two exact properties: the combined model matches the frozen model at step 0, and zero gradient reaches the trainable copy until the output convolution has taken its first step. The paper's Section 4.2 ablation replaced the zero convolutions with standard Gaussian-initialized ones and found sketch quality dropped to roughly ControlNet-lite. The authors did not test very small random initializations. In the small 4-channel toy of Figure 1, a small random scale trains about as well as zero initialization.
Does the ControlNet run at every denoising step?
Yes. The trainable copy reads the noisy latent z_t and the timestep t, both of which change at every denoising step, so its 13 outputs cannot be computed once and cached. Each step therefore runs the 361-million-parameter copy alongside the 860-million-parameter U-Net, twice per step under standard classifier-free guidance unless guess mode drops the control from the unconditional branch.
Can a ControlNet trained for Stable Diffusion 1.5 be used with another base model?
With a fine-tuned derivative of SD 1.5 that keeps the same U-Net topology and text encoder, yes; the paper demonstrates zero-retraining transfer on Comic Diffusion and Protogen 3.4. With a different architecture, no: the copy's layers and the 13 output shapes must match the base model. SD 2.1 keeps the U-Net layout but swaps the CLIP text encoder to 1,024-dimensional token embeddings (versus 768 in SD 1.5), so it needs ControlNets trained specifically for SD 2, as the paper's SD 2 depth model was.
Why are half the training prompts replaced by empty strings?
When the text prompt is empty, the only clue about what the target image depicts is inside the condition image itself. Dropping 50% of prompts forces ControlNet to learn visual semantics directly from edge maps, depth maps, or pose skeletons, so the finished model can generate coherent images from a spatial guide even when the user supplies no prompt at all.
What does the control strength setting change?
It multiplies all 13 ControlNet outputs before they are added to the U-Net skip connections and middle block. At 0 the model is unmodified Stable Diffusion; at 1 it is the model as trained; the official demo allows up to 2, where high strength can saturate features and create harsh contrast. Guess mode instead multiplies connection i (0 to 12) by strength times 0.825^(12 - i), falling from 1.0 at the middle block to 0.0994 at the first 64x64 block, while removing control from the unconditional guidance pass.
Why copy the encoder and not the whole U-Net?
Every U-Net decoder block already reads the encoder's features across the skip connections, so adding ControlNet's 13 outputs to those skip connections and the middle block steers every resolution of the decoder without duplicating it. Copying only the encoder and middle block keeps the trainable branch at 361 million parameters instead of the U-Net's 860 million, and lets the locked encoder run inside torch.no_grad(). The paper does not report an ablation that copies the decoder as well.
Why does ControlNet converge suddenly instead of gradually?
The paper does not explain it. Zero initialization accounts for why early samples look like clean Stable Diffusion images that ignore the condition, because the connecting weights start at zero and take thousands of steps to grow large enough to steer the locked decoder. Why the switch from ignoring the condition to following it happens over a narrow window (between steps 6,100 and 6,133 in the paper's example) is reported as an empirical observation from sample grids, with no loss curve or theoretical account.
Footnotes & further reading
- The paper: Zhang, Rao & Agrawala, Adding Conditional Control to Text-to-Image Diffusion Models (ICCV 2023; arXiv v3, November 2023). The first arXiv version (February 2023, Zhang & Agrawala) includes the zero-convolution gradient derivation, per-task dataset and GPU-hour details, and the semantic-error limitation in its main text.
- Official code and released checkpoints: github.com/lllyasviel/ControlNet (
cldm/cldm.pyfor the architecture and optimizer setup,gradio_canny2image.pyfor sampling and guess mode,tutorial_train.pyandtutorial_dataset.pyfor input scaling and training hyperparameters). - Stable Diffusion's architecture: Rombach et al., High-Resolution Image Synthesis with Latent Diffusion Models (CVPR 2022), covered in the Latent Diffusion explainer; the U-Net layout comes from Ronneberger et al. (2015), covered in the U-Net explainer; the autoencoder formulation is covered in the VAE explainer; text conditioning uses CLIP.
- Diffusion objective and sampling: Ho, Jain & Abbeel, Denoising Diffusion Probabilistic Models (2020; DDPM explainer); Song, Meng & Ermon, Denoising Diffusion Implicit Models (2020; DDIM explainer); Ho & Salimans, Classifier-Free Diffusion Guidance (2022; CFG explainer).
- Zero-initialized and parameter-efficient fine-tuning: Hu et al., LoRA (2021; LoRA explainer), and the
zero_modulehelper in openai/guided-diffusion (Dhariwal & Nichol, 2021; Diffusion Models Beat GANs explainer). - A concurrent, lighter alternative: Mou et al., T2I-Adapter (2023), which encodes the condition image once through a small separate adapter instead of running a copy of the U-Net encoder at every denoising step.
How could this explainer be improved? Found an error, or something unclear? I read every message.