🖌️ Diffusion Models
The images below were all generated by an AI image generator, using a diffusion process. But how exactly do such models work?
🌫️ Getting rid of noise
Picture this: on a summer day you are lying in the grass, staring at the clouds. You see all kinds of shapes: a dragon, a face... Look at the cloud below. What shape do you see in it?







Do you see someone lying down with their arms crossed? A turtle? A rabbit? Shrek?
If you saw a little rabbit, it probably becomes more and more "convincing" in your head. Look at the image below.







But that cloud is really just a random cluster of water droplets, pure chance, not a rabbit. Still, your brain cannot let go of it anymore: once you "see" the rabbit, it becomes more and more convincing.
This phenomenon is called pareidolia (external link): our brain is so well trained to recognize patterns that it even sees them in random noise. Think of faces in power outlets, animals in clouds and figures in the grain of wood.
The fun part is that there are AI models that can do the same trick, but take it much, much further. An AI diffusion model makes the image a little sharper again and again, until a completely realistic rabbit appears. Move the slider to see this step by step:







Diffusion models work on exactly this principle. Instead of seeing patterns in noise, they learn to create patterns from noise. They start from an image of pure static noise, similar to the "snow" on an old television screen. Then they remove a little noise, step by step. With every step the image becomes a bit sharper and a bit more recognizable. In the end, a "real" image is left.
A diffusion model is a generative AI model that creates images by removing noise step by step from a random noise pattern. During training, the model learns how to filter out the right noise at every noise level to get closer to a meaningful image.
🛠️ The training process: adding noise
To teach a model to remove noise, it first has to learn what noise looks like at every level. You do that by showing it the opposite: you take a real image and add noise to it, step by step.
Try it yourself in the demo below. Drag the slider to see how an image gradually dissolves into noise. At 0% noise you see the original photo. At 100% everything has disappeared into random noise.
Notice how quickly the image becomes hard to recognize at higher percentages. At 90% it is quite hard to tell what was in some of the photos if you did not know the original.
This is called the forward diffusion process. At step 0 the photo is still perfectly clear. At step 1 you add a tiny bit of noise, barely visible. At step 2 a bit more noise, at step 3 even more, and so on. After hundreds of steps the original image has completely disappeared and only random noise is left: pure snow. You can compare it to slowly making a photo fade away by sprinkling more and more grains over it until the photo is unrecognizable.
Why is that useful? Because it gives you an exercise whose correct answer you already know. The diffusion model is a large neural network that gets a noisy photo as input and has to guess which noise is in it. We added that noise ourselves a moment ago, so we can compare the model's guess with the real noise and adjust the weights a little, exactly as when training a neural network. Repeat that millions of times, with millions of photos and at every noise level, and the model learns for every level: "If I see an image with, say, 30% noise, which noise is in it, and how can I remove it to get closer to the original?"
🔄 The reverse: removing noise
Now comes the clever trick. Once the model is trained, we turn the process around. That is the reverse diffusion process. You start from pure noise and let the model remove noise step by step. At every step the model estimates which noise is on the current image, subtracts part of it, and so gets a slightly better image. After dozens of such steps, a completely new, "real" image appears, one that was never in the training data.

The reverse diffusion process: step by step the noise is removed until an image of an astronaut cat appears.
You can compare this to a sculptor who has a block of marble (the pure noise) and chips material away from it step by step. Every blow of the chisel is a denoising step. The model has learned which piece of marble it has to remove at each stage. First the rough outlines become clear (the head, the shoulders), then the finer details (the nose, the eyes), and only at the very end come the very smallest details (the texture of the skin, individual hairs).
See this in the demo below. Drag the slider to see how an image is built up step by step from pure noise. Notice how the global composition appears first (shapes, colors) and the fine details only show up later.
Below the image you can choose between two views. Predicted shows what the model thinks the clean final image will be at each step. Noisy shows what the intermediate result really looks like at that moment, still with noise. You can see that the model already predicts a fairly good image quite early on, but that the intermediate steps themselves are still very noisy. That is normal: the model removes the noise gradually, not in one go.
Why not in one go? In the Predicted view, look at step 1. The model already roughly guesses what is coming (for the first prompt, a cat in a spacesuit), but the guess is blurry: the image looks like an average of all the cats that could be hidden in that noise. If the model had to remove all the noise in one step, it would be stuck with such a blurry compromise. By removing only a little noise each time and looking again, it can decide a bit more at every step: first the composition (where the head is, which colors), and only then the details (the whiskers, the reflection in the helmet). That also explains why generating images is slow: every step is a full pass through a large neural network.
🧭 CLIP: text and images in the same space
You now know how a diffusion model removes noise to create an image. But how does the model know which image it has to create? If you start from pure noise, in principle anything could come out of it: a dog, a landscape, an abstract pattern. You need a "compass" that steers the model in the right direction. That compass is the text prompt.
When you type "a red cat playing the piano" in a tool such as Midjourney or Stable Diffusion, that text steers the denoising process. At every step the model asks itself: "Which noise should I remove so that the result looks more like a red cat playing the piano?" So the text determines the direction in which the model removes the noise.
But how does a model understand that a sentence like "a red cat playing the piano" has something to do with certain visual patterns? For that you need CLIP.
CLIP (external link) (contrastive language-image pre-training) is a model developed by OpenAI. It learns to understand text and images in the same "language". That "language" is a vector space, also called the latent space. But what exactly is such a vector space?
🔢 What is a vector?
A vector is simply a list of numbers that describes something. Imagine you want to describe a piece of fruit by three properties: redness, roundness and size. A red apple could then be described as : very red, fairly round, medium-sized. A tomato would be : also red and round, but smaller. A banana, on the other hand: : hardly red, not round, a bit bigger.
Notice that the vectors of the apple and the tomato are very much alike: their numbers are close to each other. The banana differs much more. That is exactly the idea: things that resemble each other get similar vectors, so they lie "close together" in that vector space.
An embedding is a vector representation: a list of numbers that captures the meaning of something (a word, a sentence, an image).
In our fruit example we chose three dimensions ourselves. CLIP works with vectors of 512 or 768 dimensions. That is far too many to imagine, but the principle is the same: each number in such a vector captures an abstract aspect of the meaning. The difference is that nobody chooses those dimensions for CLIP: the model learns by itself which aspects are useful for telling which text belongs with which image.
🧲 How does CLIP learn?
CLIP places text and images in the same vector space, so that you can compare them directly. But how does it learn that?
CLIP was trained on 400 million pairs (external link) of images and their captions, collected from the internet.
The training process works through contrastive learning. Concretely, it goes like this: take a group of image-caption pairs. CLIP turns every image and every caption into a vector and computes for every combination how well they fit together. That gives an table. The goal: matching pairs as close together as possible, all other combinations far apart.
Suppose we have three pairs: (🐕 dog, "a dog"), (🐱 cat, "a cat"), (🐦 bird, "a bird"). CLIP computes a similarity score for each of the nine combinations. This is how CLIP, once trained, scores the photos of a dog, a cat and a bird from the demo further down:
| "a dog" | "a cat" | "a bird" | |
|---|---|---|---|
| 🐕 dog | 0.26 ✅ | 0.22 | 0.20 |
| 🐱 cat | 0.22 | 0.27 ✅ | 0.22 |
| 🐦 bird | 0.19 | 0.18 | 0.24 ✅ |
The goal: in every row and every column, the correct pair (marked ✅) should get the highest score. CLIP adjusts its weights to push matching pairs closer together and non-matching pairs further apart.
Those scores look low, but what counts is the ranking: CLIP passes them through a softmax with a very low temperature (0.01), so that even small differences become decisive. For the cat, "a cat" scores only 0.05 higher than the two other captions, and yet that caption gets about 99% of the probability.
After training on hundreds of millions of pairs, CLIP "understands" that the caption "a dog on the beach" belongs with a photo of a dog on the beach. That photo and that text then lie close together in the shared vector space. Non-matching pairs are pushed far apart.
So CLIP learns statistical patterns: it has seen millions of times that photos with dogs go together with texts in which "dog" appears. The model does not "understand" what a dog is the way we do, but it does reliably recognize which texts belong with which images.
🗺️ Exploring CLIP space
Below you see a few images and text concepts plotted in a two-dimensional projection of the CLIP space. You can clearly see that conceptual clusters really do lie close together. For example, "coffee" and "espresso" are next to each other, with the food clusters ("pizza", "bell pepper") nearby. Most animals are at the bottom, where "wolf", "puppy" and "dog" are close together and "cat", "kitten" and "tiger" also form a cluster. The matching photos also lie close to those text concepts.
Click a photo to see its cosine similarity with the word that belongs to it. Cosine similarity measures how similar two vectors are: a score of 1 means identical, 0 means completely unrelated. You can think of it as the extent to which two arrows point in the same direction. Do not expect scores close to 1: as in the example above, the matching pairs here score between 0.23 and 0.34.
So CLIP gives the diffusion model a compass: the text is turned into a point in the CLIP space, and the diffusion model tries to generate an image that lies as close as possible to that point.
📝 Prompt engineering for image generation
Just like with large language models, the quality of your prompt largely determines the quality of the result. In image generation, though, prompt engineering works a bit differently than with text. To understand why certain prompts work better, let us briefly go back to how these models were trained.
🏷️ Why prompts work
Diffusion models learned the link between text and image from the captions of images on the internet. Especially for the first generations of image models, this had two important consequences. With newer models this plays less of a role, but the principles are still relevant:
-
The style of the caption determines the style of the image. Images on a stock photo website have professional captions such as "cinematic portrait of a woman, golden hour lighting, shallow depth of field". Amateur holiday photos have captions like "photo of John at the beach". If you ask the model for "a man on a horse", you get a fairly ordinary result, because that is what the average internet caption describes. But if you add "cinematic lighting, bokeh" and even certain types of camera, you steer the model toward the nicer, more professional images in the training data. This is really a kind of conditional probability: with the words in your prompt you steer toward higher-quality images. It is mainly a consequence of the style of the captions in the training data.
Fortunately, modern image models are trained to depend less on specific "magic words" in the prompt. They generate nicer results without you having to add all kinds of magic spells. Still, just like with language models, many style words remain very effective. They help the model understand exactly what kind of image you want.
-
The model knows concepts, not absolute positions. Captions rarely describe the exact positions of objects ("the dog is on the left, the cat on the right"). As a result, the model has mostly learned associations between words and visual concepts, but not always the precise spatial relations.
On top of that, it is hard to tell the model that something must not be in the image. A prompt like "a garden without a dog" will often still generate a dog. That is because captions on the internet typically do not say "this photo has no dog", but rather "a photo of a dog in a garden". So the model has learned that the word "dog" is associated with the visual concept of a dog. Mentioning a concept, even in a negative sentence, is exactly what brings it into the picture.
🧱 Building a good prompt
An effective prompt for image generation typically mentions the form, the subject, the details and the style.
- Form: What kind of image do you want? ("a photo", "an oil painting", "a sketch", "digital art")
- Subject: What should be in the image? ("an old man with a long beard")
- Details: Specific features that enrich the image ("wearing a red cloak, standing in a snowy valley, looking at the sunset")
- Style: What should the image look like? ("fantasy style, dramatic lighting")
The more specific, the better. For example:
🎨 Choosing and combining styles
Style cues such as "digital art", "oil painting", "watercolor", "photorealistic", "anime style" or "pencil sketch" have a big effect. The same prompt with a different style cue gives a completely different result:
You can also combine styles that never occur together in the real world. For example, you can write "a cyberpunk city in the style of Van Gogh's Starry Night" and the model generates a cyberpunk city with the color palette and brushstrokes of Van Gogh. This works because the model has learned the visual features of "Van Gogh" and "cyberpunk" as separate concepts and can combine them.
🚫 Negative prompts
Many tools also support negative prompts as a separate feature: text that describes what you do not want in the image. This works as the opposite of the normal steering with text: the model pushes the result away from the negative prompt.
Commonly used negative prompts are:
- "blurry, low quality, ugly, deformed" (to get sharp, high-quality images)
- "extra fingers, extra limbs" (to reduce anatomical errors)
- "text, watermark" (to avoid unwanted text)
This is only possible in tools that have a separate field for it, such as Stable Diffusion and Midjourney. In a chat application such as ChatGPT it works better to simply describe what you do want.
🧰 Applications
Diffusion models can be used much more broadly than just for generating images out of nothing. The same technology is already built into professional software such as Adobe Photoshop and Canva.
🖼️ Inpainting: filling in missing parts
Inpainting is filling in a selected part of an image. You select an area (e.g. an unwanted object), and the model generates new pixels that blend in seamlessly with the rest of the image. So you condition the model on both an input image and text, and only allow changes within a certain zone.
You do not even have to give any text. Suppose you have a nice group photo, but there is a trash can in the background. With inpainting you select the trash can, and the diffusion model fills that area in with what "logically" belongs there: grass, bushes, or the continuation of the building behind it. The model takes the surrounding context into account (colors, textures, perspective) to make a convincing result.
Try it yourself in the demo below. Upload a photo, choose the brush in the toolbar on the left and paint over the part that has to change. Below that, type a prompt for what you want to see in that area and click Run. Does the demo give the error Value 50 is greater than maximum value 30? Then open Advanced Settings and set the Guidance Scale to 30.
https://huggingface.co/spaces/black-forest-labs/FLUX.1-Fill-dev
This demo runs on HuggingFace Spaces and may take a moment to start up.
🔭 Outpainting: extending the image
Outpainting is the opposite: you extend an existing image beyond its original edges. The model generates new content that connects smoothly with the existing image.
This is handy, for example, if you have a portrait photo that is cropped too tightly. With outpainting, the model can fill in more of the background: continue the landscape, extend the room or fill in more of the sky. The model "imagines" what could be outside the frame, based on the visual information that is already there.
Try it yourself on a photo of your own in the demo below.
https://huggingface.co/spaces/fffiloni/diffusers-image-outpaint
This demo runs on HuggingFace Spaces and may take a moment to start up.
✏️ Image-to-image: a sketch as a starting point
In image-to-image generation you do not start from pure noise, but from an existing image. That image can be a rough sketch, a photo, or even another generated image. The model adds noise to the starting image (but not all the way to pure noise) and then runs the denoising process, steered by a text prompt.
That way you can draw a simple sketch of a landscape with a few colors and lines, and the model transforms that sketch into a photorealistic landscape. The rough structure of your sketch is kept (the mountain is where you drew it, the tree follows your sketch), but all the details are filled in by the model. You can try this yourself on Diffuse The Rest (external link): draw a simple sketch, type a description, and the model fills in the rest.
A more modern variant is FLUX Kontext, which lets you edit an existing image with a simple text instruction such as "change the cat into a dog" or "make the image anime style".
https://huggingface.co/spaces/black-forest-labs/FLUX.1-Kontext-Dev
This demo runs on HuggingFace Spaces and may take a moment to start up.
🎮 ControlNet: precise control
ControlNet goes one step further than image-to-image. It offers precise control over the structure of the generated image through extra input signals, such as certain edges or contours that have to be kept. For example, in the Illusion Diffusion (external link) app you can make sure that a generated image has the same contrast as a given input photo.
Below you see an example with the KU Leuven logo as input. The two pictures on the right have the contrast of the KU Leuven logo subtly worked into them. Squint and you will see it!



🔍 Errors in fine details
Although diffusion models produce good results, they still have clear limitations. Many of those limitations can be traced back to how the model removes noise: it starts with the global composition (large shapes and colors) and only then works toward the fine details. This "coarse to fine" principle explains many of the typical errors.
Because the model decides the global structure first and only fills in the details later, it can happen that the overall composition is fine but the details are wrong. The model has, as it were, already "zoomed in" on the big plan and can then no longer easily go back to adjust details that are inconsistent with what has already been decided.
✋ Limbs and fine anatomy
The most discussed problem of image generators is generating hands. You have probably seen it already: generated people with six fingers, twisted joints, or hands that melt into each other.
Why is this so hard? There are two reasons:
- Hands are not repetitive. Many textures in images are repetitive: grass, fabric, bricks. The model can learn a "tile" and repeat it. But hands are unique: five fingers, each in a different position and at a different angle, with complex joints. A small mistake stands out immediately.
- The coarse-to-fine problem. If, in an early step, the model accidentally decides on a rough structure that suggests six finger-shaped patterns, it is already "too late" in the later, finer steps to correct that.
The good news: newer models keep getting better at this. The newest generation of image generators already produces much more convincing hands and hardly makes any mistakes in them anymore.
🔤 Text in images
Another common error is generating text in images. If you ask for "a sign with the text WELCOME", the model will often generate letters that look almost right but are slightly wrong: reversed letters, nonexistent characters, or words in the wrong order.
Part of the cause is the same as with the hand problem: text requires pixel-perfect precision in a small area. A letter that is shifted by a few pixels becomes another letter, or nonsense. The coarse-to-fine process makes it hard to generate such small, precise details correctly. On top of that, the model reads your prompt, just like a language model, in tokens and not in letters: so it does not really know which letters a word like WELCOME is made of. Models that have the prompt read by a large language model, or by a model that does see letters, spell much better as a result (external link).
Recent models are improving quickly here too, but they still make mistakes now and then, especially with longer texts.
🧩 Compositionality: the right order
Ask an image generator for "a red cube on a blue cube", and you often get a blue cube on a red cube, or two cubes next to each other, or cubes whose colors are swapped.
This problem is called a lack of compositionality: the model has trouble placing several objects correctly, each with the right properties and the right relations to the others.
Why? Because the captions in the training data rarely contain precise positional information. A caption usually says "a cat and a dog in a garden", not "a cat in the lower-left corner and a dog in the upper-right corner". So the model has mostly learned which objects belong to which words, but not always where exactly they should be, or which object has which property when there are several objects.
Newer models, however, have much less trouble with compositionality, and can more and more often generate complex scenes with several objects and relations correctly.
💪 Strengths and limitations
✅ Strengths
- 🎨 High image quality: diffusion models produce photorealistic images with rich details and coherent compositions, better than earlier generative models such as GANs.
- 🎛️ Flexible steering: thanks to conditioning on text, images or structural input (such as ControlNet), you have a lot of control over the end result.
- 🖌️ Widely applicable: the same basic principle works for image generation, inpainting, outpainting, image-to-image, and even video and audio generation.
- 🔄 Stable training: unlike GANs, which are notoriously hard to train (the generator and the discriminator have to stay in balance), the training process of diffusion models is more stable and more predictable.
🚨 Limitations
- 🐌 Slow generation: the model has to denoise the image step by step, typically in 20 to 50 steps. Every step requires a full pass through the neural network. That makes generation much slower than with GANs, which produce an image in a single step.
- 💻 A lot of computing power needed: because of all those steps, considerably more GPU time is needed per generated image. Training a diffusion model also requires huge amounts of data and weeks of computation on expensive hardware.
- ✋ Errors in fine details: hands, text and the correct placement of several objects remain difficult, because the model works from coarse to fine and can no longer fix early errors later on.
- 🔀 Little consistency: if you enter the same prompt twice, you get two different results, because the model starts from different random noise each time. That makes it hard to create a consistent character or scene across several images.
- 📏 Fixed resolution: diffusion models are trained on a certain image resolution. Generating images in a different format (e.g. extremely wide or extremely tall) can lead to artifacts or repeated patterns.
🧭 When to use them?
Diffusion models are ideal for creative applications such as concept art and quickly exploring visual ideas, or for illustrations and marketing material, although those often still need editing in Photoshop afterwards to remove errors or to fit them into a larger composition. They are typically less suitable for situations that require speed (e.g. real-time applications) or exact control (e.g. pixel-perfect technical drawings).
⚖️ Ethical challenges
Generating photorealistic images from a few words brings ethical questions along with the creative opportunities. Here we discuss the main ones.
🎭 Deepfakes
The most discussed concern is the use of image generation for deepfakes: fake but convincing images (or videos) of real people. Although deepfakes were already possible before diffusion models existed (for example based on generative adversarial networks, or GANs), diffusion models make them much easier to create, more accessible and more varied. With modern diffusion models, anyone with a computer can generate, in a few seconds, a photo of a politician, a celebrity or even a random person in a situation that never took place. The video below is a well-known early warning from 2018, from before diffusion models: a deepfake of Barack Obama, voiced by the comedian Jordan Peele, warns you not to trust videos like this one.
https://www.youtube.com/watch?v=cQ54GDm1eL0
📷 Copyright and training data
Diffusion models are trained on billions of images from the internet, including works by artists, photographers and illustrators. That raises difficult questions:
- May these images be used for training without permission? Many artists think not. They feel robbed when a model can imitate their style because many models were trained on data without permission.
- Who owns the copyright on a generated image? If a model generates an image "in the style of Picasso", or one that closely resembles an existing work, who is the owner then?
- Economic impact: If companies can generate images for free, will work disappear for illustrators, stock photographers and graphic designers?
🔏 Watermarks and detection (C2PA)
To tackle the problem of deepfakes, the industry is working on standards to mark generated images. The most important of these is C2PA (external link) (in full, Coalition for Content Provenance and Authenticity), an open standard that adds signed metadata to digital files with information about their origin.
The idea: an image carries content credentials that indicate that it was generated or edited, when, and with which system. So that is not the same as an invisible watermark in the pixels themselves, although some systems can combine both. Big tech companies such as Google, Microsoft, Adobe and OpenAI support this standard and implement variants of it in their tools.
This system has limitations, however:
- Taking a screenshot or saving the image again can remove that provenance metadata.
- Not all tools support the standard.
- It is a voluntary standard. People with bad intentions can get around it.
🪞 Bias in generated images
Just like large language models, diffusion models inherit the biases in their training data. If the training data mostly contains photos of white people in certain professions (e.g. CEO, doctor), the model will by default also generate white people for those professions.
This can reinforce existing stereotypes:
- Women are generated more often in certain professions, and men in others.
- Certain ethnic groups are underrepresented or shown in a stereotypical way.
- Beauty ideals from the training data are reproduced as if they were universal.
Below are three attempts with the same prompt "a CEO giving a presentation". Notice how one-sided the picture is that the model generates by default:
Makers of models try to reduce this by making the training data more diverse and by applying bias corrections, but it is still an open problem. Technical "fixes" are risky too: when OpenAI detected that DALL-E 2 was generating a person, for example, it used to add "female" or "black" to the prompt (external link) to increase diversity. That covered up the problem rather than tackling its cause. A few years later, Google repeated (external link) this mistake with its Gemini model, which also added random ethnicities when generating images, so that a generated image of the pope or of the American "Founding Fathers" suddenly got different ethnicities and genders.
💻 Hands-on
Do you want to generate images with diffusion models yourself? There are several tools available.
🌐 Online tools (no installation needed)
- ChatGPT (external link) and Gemini (external link): Both have an image generator built into their chat application. You simply type a description and the built-in image generator generates the image. Availability depends on the product version, the region and your subscription.
- Midjourney (external link): Known for its artistic, aesthetically strong results. Works through Discord or the website. Paid subscription.
- Adobe Firefly (external link): Adobe's own image generator, trained on licensed content. Integrated into Photoshop for inpainting and outpainting. A free version is available.
🕹️ Demos
Experiment further with the full simulators and demos featured above.




🗣️ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.










































