Skip to main content
LearnMLAcademy
Advanced10 min read

Controlling Diffusion Models

Control image generation with ControlNet and edge conditioning, with diffusion diagrams, prompt experiments, and output-quality checks.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Control without retraining the model

A text prompt gives a diffusion model a goal, but many tasks need more precise control: repeat this random starting point, preserve this photograph, change only the jacket, or follow this pose. These are inference-time controls. They change the information or settings used while a pretrained model generates; they do not teach the base model new parameters.

The controls in this lesson answer different questions. Guidance scale controls how strongly text steers the denoising prediction. A seed controls the initial random latent. Image-to-image and inpainting provide pixels to preserve or edit. ControlNet-style conditioning provides a spatial structure such as edges, depth, or pose. The next lesson covers training-time adaptation.

Controlling Diffusion Models in Simple Words

Standard text prompts can be vague—asking for "a warrior on a cliff" might yield unpredictable poses, lighting, or compositions. Diffusion controls give you a master control board: CFG Scale turns up prompt intensity, ControlNet enforces human skeleton poses or architectural wireframes, and Inpainting lets you paint over a small mask to swap an outfit while keeping the face perfectly intact!

1

Unconditioned Signal

Model predicts generic plausible image

2

Conditioned Signal

Model predicts prompt-aligned features

3

CFG Guidance Scale

Pushes difference vector: ε_u + w(ε_c - ε_u)

4

Structural Adapters

ControlNet locks poses, edges, and depth maps

Classifier-free guidance: compare two predictions

At a denoising step, a classifier-free-guidance system evaluates the denoiser with the requested condition and with an empty or negative condition. The difference between those predictions points toward what the condition changes. Guidance scales that direction before the scheduler uses the result to calculate the next latent.

Classifier-free guidance (CFG)
ε̂guided = ε̂uncond + s(ε̂cond − ε̂uncond)
  • ε̂uncond is the model's prediction under the no-condition or negative-condition input.
  • ε̂cond is the prediction under the user-supplied prompt or condition.
  • s is the guidance scale chosen by the user or developer; it is not learned in this calculation.
  • ε̂guided is the calculated prediction passed into the scheduler update.

A larger scale pushes farther in the conditional direction, but larger is not automatically better. Excessive guidance can reduce variety, exaggerate contrast, or create artifacts because the update is being pushed beyond the model's ordinary conditional prediction.

Worked CFG example

This is a pedagogical scalar example. Real denoisers predict large tensors, but using one number makes every arithmetic step visible. Suppose the model produces 0.2 without the positive prompt and 0.5 with it. Both values are model outputs for the same noisy latent and timestep. We choose a guidance scale of 3.

1. Difference

0.5 − 0.2 = 0.3

2. Scale

3 × 0.3 = 0.9

3. Add baseline

0.2 + 0.9 = 1.1

4. Guided value

The scheduler receives 1.1

The result 1.1 is calculated, not sampled and not a pixel brightness. It represents one component of the guided denoising prediction. Applying the formula component by component gives the tensor version.

Figure 1 — Classifier-free guidance scales the difference between two model predictions

The numbers are pedagogical scalar values, not pixels. Both 0.2 and 0.5 are model outputs for the same noisy latent and timestep; scale 3 is chosen by the user or developer; 1.1 is calculated.

The same noisy latent x t and timestep enter two evaluations of the same fixed denoiser. The unconditional or negative branch produces epsilon hat uncond equal to 0.2. The prompt-conditioned branch produces epsilon hat cond equal to 0.5. Their difference is 0.3, the chosen guidance scale 3 expands it to 0.9, and adding the 0.2 baseline gives guided prediction 1.1. A number line shows that scale 3 pushes the guided result beyond the ordinary conditional output 0.5.

Reproduce the CFG arithmetic

This self-contained Python 3 code reproduces the worked scalar result. It teaches the equation; it does not run an image model.

Python 3 · runnable without extra packages
# Runnable Python 3: the same scalar arithmetic used in the worked example.
unconditional_prediction = 0.2
conditional_prediction = 0.5
guidance_scale = 3.0

difference = conditional_prediction - unconditional_prediction
guided_prediction = unconditional_prediction + guidance_scale * difference

print(f"conditional direction: {difference:.1f}")
print(f"guided prediction: {guided_prediction:.1f}")

Classifier-Free Guidance (CFG Scale w) Trade-off Analysis

ε̂ = ε_uncond + w · (ε_cond - ε_uncond). Sweet spot is typically between 6.0 and 8.5.

Notice that while higher CFG scales force tighter adherence to the prompt, values above 12 induce extreme contrast, oversaturation, and burned artifact edges.

Controls that change the sampling process

Negative prompt

In many pipelines it replaces the empty text used for the negative or unconditional branch. CFG then moves relative to that prediction. It can discourage learned associations, but it is not a perfect inverse command and cannot guarantee that an unwanted feature disappears.

Random seed

A seed is a user- or developer-chosen integer used to initialize the random-number generator. With the same model, settings, hardware path, and software versions, it helps reproduce the same starting latent; it is not a visual style value.

Inference steps

This chosen count controls how many scheduler updates are performed. More steps cost more U-Net evaluations and may improve refinement only up to a point; the useful range depends on scheduler and model.

Scheduler

The scheduler defines the timestep sequence and numerical update rule. Changing it can alter the speed, stochasticity, and appearance of results even when the denoiser's learned parameters stay fixed.

Starting from an image

Image-to-image strength

The supplied image is VAE-encoded, then noise is added before denoising begins. A strength value is chosen by the user or developer and determines how far into the noise schedule the workflow starts. Lower strength tends to preserve more of the source; higher strength allows a larger transformation. The exact numerical meaning is pipeline-dependent, so it should not be described as “percent changed.”

Inpainting mask

A mask is a spatial input aligned with the source image. It identifies the region intended for regeneration while the remaining region acts as context to preserve. Libraries differ in mask conventions, so confirm whether white or black means “edit.” Even with a correct mask, soft edges, latent compression, or attention can produce seams or small changes outside the intended area.

Structural conditioning with ControlNet

A prompt can name “a cyclist,” but it does not precisely specify the bend of each limb. A ControlNet-style model adds a trainable control path that reads a spatial condition while preserving a pretrained diffusion backbone. An edge map carries boundaries, a depth map carries near/far structure, a pose map carries joint locations, and a segmentation map carries region labels. The condition does not contain the final texture; it constrains where the generated content should go.

Figure 2 — Each diffusion control supplies a different kind of constraint

Prompt/CFG supplies language only; image-to-image supplies an entire starting composition; inpainting supplies a spatial edit mask; ControlNet-style guidance supplies explicit geometry such as pose, edges, depth, or segments.

Four spatially different mini diagrams compare diffusion controls. Prompt and guidance send only a text bubble toward a flexible generated scene. Image-to-image sends an existing scene plus a strength control toward a transformed scene with the same broad layout. Inpainting overlays a highlighted mask on one region of an image and changes only that region under a prompt. A ControlNet-style path sends a stick-pose condition and a prompt toward a generated figure that follows the same pose. Each mini diagram names what the method attempts to preserve.

Which control should you choose?

NeedStart withWhat it preserves or changesMain caution
Style or content influencePrompt, guidance, seedGuides semantics and appearance without an anchor imageLanguage may not control exact layout
Preserve an existing imageImage-to-image with modest strengthKeeps broad composition while restyling or revisingStrength is not a guaranteed preservation percentage
Edit one regionInpainting with image + mask + promptTargets a spatial area and uses surroundings as contextCheck mask convention, borders, and unintended spill
Preserve pose, depth, edges, or layoutMatching ControlNet-style conditionConstrains explicit geometry while allowing new appearanceA poor detector or condition map transfers its errors

Summary / Key Takeaways

  • Inference-time controls change the information or settings used during generation without retraining the base model.
  • Classifier-free guidance scales the difference between conditional and unconditional predictions before the scheduler update.
  • In the scalar example, 0.2 + 3 × (0.5 − 0.2) = 1.1; excessive guidance can reduce variety or create artifacts.
  • A seed helps reproduce the starting latent, while inference steps and the scheduler affect cost, refinement, randomness, and appearance.
  • Image-to-image strength trades source preservation against transformation, and inpainting uses a mask to target one region.
  • ControlNet-style inputs preserve explicit geometry such as pose, depth, edges, or segmentation layout.
  • Every control is an influence rather than a contract, so compare controlled outputs and verify task-critical details.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Controlling Diffusion Models"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5numerical/formula
For ε̂uncond = 0.2, ε̂cond = 0.5, and guidance scale s = 3, what guided prediction is calculated?
Question 2 of 5conceptual
What does a random seed control in a diffusion pipeline?
Question 3 of 5practical selection
A generated cyclist must follow an exact supplied pose while appearance may change. Which control is the best starting point?
Question 4 of 5debugging/diagnostic
An inpainting pipeline edits the opposite region from the one intended. What should be checked first?
Question 5 of 5application/scenario
A team wants to restyle a photograph while preserving most of its composition. What should it try first?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1For ε̂uncond = 0.2, ε̂cond = 0.5, and guidance scale s = 3, what guided prediction is calculated?▼

Correct Answer: 1.1

CFG gives 0.2 + 3×(0.5 - 0.2) = 0.2 + 0.9 = 1.1. The result is a guided denoising component, not a pixel brightness.

2What does a random seed control in a diffusion pipeline?▼

Correct Answer: Initialization of the random-number generator and therefore the starting latent

A seed is a chosen integer used to initialize randomness. Under matching model, settings, hardware path, and software versions, it helps reproduce the same starting latent.

3A generated cyclist must follow an exact supplied pose while appearance may change. Which control is the best starting point?▼

Correct Answer: A pose-based ControlNet-style condition

A pose map explicitly represents joint locations, so ControlNet-style conditioning can preserve the required geometry while allowing new appearance.

4An inpainting pipeline edits the opposite region from the one intended. What should be checked first?▼

Correct Answer: Whether the library treats white or black mask values as ‘edit’

Mask conventions differ across libraries. Confirming which colour means ‘edit’ is the direct diagnostic before changing unrelated model settings.

5A team wants to restyle a photograph while preserving most of its composition. What should it try first?▼

Correct Answer: Image-to-image with modest strength

Image-to-image anchors the result to the supplied image, and modest strength tends to preserve more of the original composition while allowing revision.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next