Home / Chapter 9 · Images, video and audio
    Last edited · 11 min read

    Use with AI

    Image generation

    A diffusion model starts from random noise and improves the whole image at once over a series of steps, guided by the prompt at every step. One real Stable Diffusion run shows how the prompt shapes the image, which areas of the image each prompt word influences, and how a new prompt changes a finished image.

    In plain wordsLike an illustrator who keeps a written description on the desk and looks at it again on every pass over the sketch. First they decide where everything goes, then refine the shapes and add the details. The more you insist that they follow the description, the more faithfully they do so, but the stiffer and more garish the drawing becomes.

    From noise to an image in 20 steps

    startstep 1step 4step 20 gridGrid at the start: pure noiseGrid after step 1: still noiseGrid after step 4: noise with the outline of a lighthouseGrid after step 20: the finished lighthouse on a cliff previewnonePreview after step 1: blurred sky, cliff and red lighthousePreview after step 4: a clear lighthousePreview after step 20: the same as the finished image
    The model denoises a grid, not pixels: an array of 64×64 cells with 4 numbers each, which a separate network, the autoencoder’s decoder, turns into a 512×512 image. The top row is the grid after each step, shown through the decoder, which is why the start looks like coloured noise. The sampler, the algorithm that performs a step, removes only part of the noise at each step. The bottom row is the preview: the finished image the model expects at that step. After the first step the grid is still noise, but the preview already has a layout: sky at the top, a dark cliff at the bottom and the red blob of a lighthouse in the middle. The preview is blurred because from pure noise the model can predict only an averaged image, and that is why one step is not enough. After the fourth step the shapes are clear, and the last steps add detail such as the texture of the rocks and the foam.

    Same prompt, different settings

    The guidance scale controls how strongly the prompt influences the image, and the seed is the number that determines the starting noise; both are covered in the section “Guidance and seed” below.

    A pale image, a small lighthouse on rocks
    Guidance 1
    the prompt is not amplified: a pale image and a different layout
    A lighthouse on rocks, natural colours
    Guidance 3
    natural colours
    A red lighthouse on a cliff
    Guidance 7.5
    the default for SD 1.5 in the diffusers library, the same image as at step 20
    Oversaturated colours, red rocks
    Guidance 20
    oversaturated colours, harsh contrast
    A lighthouse on the left and a small red house
    Seed 8
    different starting noise, different layout
    A lighthouse with a building on a cliff
    Seed 9
    another layout again

    Real Stable Diffusion 1.5 (2022) images. Prompt: “a red lighthouse on a rocky cliff above a stormy sea, photograph”, in English because the model was trained on English captions. The model generated a 512×512-pixel image, shown here at 256×256; 20 steps of the DDIM sampler, guidance 7.5 and seed 7 unless the caption says otherwise. The basics shared by images, video and audio, including the grid and the autoencoder, are covered in “How models generate images, video and audio”.

    The denoising loop and how the generator is trained

    What happens to the prompt and the noise

    1. Text encoder. In Stable Diffusion 1.5 it is the CLIP model (OpenAI, 2021). Unlike in an LLM, the text is a separate input and the image is not a continuation of it. The CLIP tokeniser splits this prompt into 13 tokens, adds start and end markers and pads the result to 77 positions; it cuts a longer prompt off after 75 content tokens. The encoder turns each position into a vector of 768 numbers. These vectors are computed once and fed into every step.
      aredlighthouseonarockycliffaboveastormysea,photograph+ start, end and 62 padding positions
    2. The loop, 20 times. At the start the 64×64×4 grid is random noise. The grid has 64×64 cells with 4 numbers each, and each cell corresponds to a square of 8×8 pixels. It can also be described as 4 channels of 64×64 numbers. An RGB image has 3 channels, one per colour, but the grid’s channels do not stand for colours. Each channel is shown here as a grey square: the brighter the point, the larger the number. At every step the generator receives the grid, the noise level and the prompt vectors, and predicts the noise. In SD 1.5 the generator is a U-Net, described below. With guidance it does this twice per step, and the sampler combines the two predictions (section “Guidance and seed”). Subtracting all of the predicted noise and rescaling leaves a grid that decodes to the preview of the finished image, the bottom row in the figure above. The preview is only a visualisation: what goes into the next step is the grid with part of the noise removed by the sampler.
      Four grey squares of noise
      the grid entering step 4: still mostly noise
      → preview
      A blurred cliff and a clear red lighthouse
      the preview from step 4
    3. The end. After 20 steps the grid is denoised and the shape of the image is visible in it. The autoencoder’s decoder turns it into a 512×512 image.
      Four grey squares with the outline of a lighthouse and a cliff
      the grid after 20 steps
      decoder →
      A red lighthouse on a cliff above a stormy sea
      the finished image

    Which parts of the image the model ties each prompt word to

    A bright patch on the lighthouse
    “lighthouse”
    A bright patch on the lighthouse
    “red”
    Bright rocks of the cliff
    “cliff”
    Bright water on the left and at the bottom
    “sea”
    Bright sky and sea
    “stormy”
    A red lighthouse on a cliff above a stormy sea
    the finished image
    At every step the generator computes, for each patch of the grid, attention weights over the prompt vectors (cross-attention: the mechanism from “Attention”, with queries coming from the grid and keys and values from the prompt). Brighter areas have a higher attention weight for the given word: “lighthouse” and “red” land on the lighthouse, “cliff” on the rocks, “sea” on the water, “stormy” on the sky and the sea. This is the path by which the prompt affects what appears where.

    The maps come from the U-Net layers that work on the grid reduced to 16×16, which is 256 patches (inside, the U-Net shrinks the grid and then enlarges it again), and are averaged over all steps. Each map is one column of the attention matrix: the rows are those 256 patches, the columns are the 77 prompt positions. Most of the weight, 88% on average, goes to the start marker, like the start token in “Attention” (an attention sink); each of the five words shown gets between 0.1 and 2%, and two to three times more in steps 1–⁠4 than later. Each map has its own brightness scale, so brightness cannot be compared between the maps of different words. A map is a hint about where the model used a word, not proof of which pixel depends on it. SD3 and FLUX have no separate cross-attention: the prompt tokens sit in one sequence with the image tokens and ordinary attention connects them.

    Training the generator: a real image and its caption

    A red lighthouse on a cliffimage512×512 pixels with 3 numbers each
    autoencoder’s encoderturns the image into a grid of 64×64 cells with 4 numbers each
    The same image under dense noisenoisy gridrandom noise level
    image captiontext encoderturns the caption into vectors

    generatorreceives the noisy grid, the noise level and the caption vectors; it predicts the added noise, and the weights are adjusted according to the prediction error

    The numbers and the image are those of Stable Diffusion 1.5 from the run above; the noisy grid is shown through the decoder. FLUX.1 from “How models generate images, video and audio” uses a grid of 128×128 cells with 16 numbers each for a 1024×1024 image. The autoencoder is trained separately, before the generator, and then frozen. Generating from scratch needs only the decoder, not the autoencoder’s encoder; the encoder comes back when a finished image is edited.

    Guidance and seed

    Guidance: two predictions and their amplified difference

    Grey-beige fog with no shapes
    Without the prompt
    grey-beige fog
    A pale, blurred outline of a cliff and a lighthouse
    With the prompt
    a pale outline of a cliff and a lighthouse on the right
    A blurred image with a clear red lighthouse
    Guidance 7.5
    a clear red lighthouse
    The sampler uses the noise given by the formula: prediction without the prompt + 7.5 × (prediction with the prompt − prediction without the prompt). Each picture is the preview computed from one of these noise predictions. The figure shows the first step: the prompt alone changes the preview only slightly, while the amplified difference already gives a clear outline of the lighthouse. At scale 1 the formula reduces to the prediction with the prompt.

    A real first step of Stable Diffusion 1.5, prompt “a red lighthouse on a rocky cliff above a stormy sea, photograph”. The whole run is above, in the figure “From noise to an image in 20 steps”.

    Editing and reference images

    Same image, new prompt

    New prompt: “…on a snowy cliff above a frozen sea at night”. Strength says what fraction of the denoising loop to run on the original: 0 means no change, and 1 means the whole loop from pure noise, which is generating from scratch.

    A red lighthouse on a cliff above a stormy sea
    Original
    The lighthouse almost unchanged
    Strength 0.3
    little noise: almost unchanged
    Ice on the water, lighthouse and cliff unchanged
    Strength 0.5
    ice appears on the water, the rest stays
    Snow on the cliff, the same layout
    Strength 0.7
    snow on the cliff, same layout
    A different, wider lighthouse, pink sky, snow
    Strength 0.9
    a new lighthouse and sky, original layout; the prompt’s request for a night scene has little effect

    Inpainting: a mask marks the area to edit

    New prompt: “a white windmill on a rocky cliff above a stormy sea, photograph”.

    A red lighthouse on a cliff above a stormy sea
    Original
    A bright rectangle covers the lighthouse
    Mask
    a rectangle around the lighthouse
    A white windmill where the lighthouse was
    Result
    a windmill in place of the lighthouse, small changes outside the mask

    Edits: Stable Diffusion 1.5, guidance 7.5. Strength picks the starting point in the 20-step loop. Noise at that point’s level is added to the original’s grid (noise accounts for about 33% of the grid’s variance at strength 0.3 and about 98% at 0.9), and then the remaining steps run: six at 0.3 and eighteen at 0.9. The request for a night scene has little effect even at strength 0.9, most likely because the image’s average brightness survived under the noise. Inpainting: a version of Stable Diffusion 1.5 trained with the mask as an extra input, 20 steps.

    Resolution, errors and cost

    Check yourself

    How does a diffusion model turn a prompt into an image, and how does that differ from an LLM generating text?

    A text encoder turns the prompt into vectors. The model works on a smaller grid of numbers that an autoencoder can turn into an image, and generation starts from random noise in that grid. At every step the generator predicts the noise (or the direction of change) for the whole grid at once and the sampler updates the grid; at the end the decoder turns it into pixels. An LLM appends one token from its vocabulary at a time, while here the generator improves the whole grid at once; the grid’s size depends on the resolution, not on the content. Randomness comes mainly from the starting noise, which the seed determines (some samplers add noise at every step), not from a draw at every token. A separate parameter, the guidance scale, controls how strongly the prompt influences the image.

    Po polsku

    Koder tekstu zamienia prompt w wektory. Model pracuje na mniejszej siatce liczb, którą autoenkoder umie zamienić w obraz, a generowanie startuje od losowego szumu w tej siatce. W każdym kroku generator przewiduje szum (albo kierunek zmiany) dla całej siatki naraz, a sampler aktualizuje siatkę; na końcu dekoder zamienia ją w piksele. LLM dopisuje po jednym tokenie ze słownika, a tu generator poprawia całą siatkę naraz; jej rozmiar zależy od rozdzielczości, nie od treści. Losowość pochodzi głównie z szumu startowego, który wyznacza seed (część samplerów dodaje szum w każdym kroku), a nie z losowania przy każdym tokenie. Siłę promptu ustawia osobny parametr, skala guidance.

    Follow-up questions (4)
    After you raise the guidance scale, the image has oversaturated colours and harsh contrast. What do you change?
    Lower the guidance scale and leave the seed and the other settings alone, so that you see the effect of one parameter. A scale that is too high pushes the result outside what the model has learned. If the image drifts from the prompt at the lower scale, fix the prompt or pass a reference image, and don’t raise the guidance scale again.
    You need a 4096×4096 poster and the model handles 1024×1024. How do you do it?
    Generate several versions at 1024×1024 with different seeds and pick a layout. Then upscale the chosen version and run it through image-to-image in tiles at a low strength, which adds detail. Generating directly at 4096×4096 means sixteen times as many tokens and a size the model never saw in training, so it often produces repeated objects. Add text and logos in code at the end.
    The same character has to appear in ten illustrations. How do you set that up?
    Don’t describe the character in words alone, because one description fits many different faces and outfits. If the model supports it, pass the same reference image of the character with every illustration. Generate from that image, not from the previous illustration, and compare the character in every result with it. If that is not enough, you can fine-tune the model on images of the character, for example using LoRA (see “Fine-tuning and LoRA”).
    You set the same seed and prompt, and the image from the API came out different from a month ago. Why?
    The seed reproduces the starting noise, but the result also depends on the model version, the sampler, the libraries and the hardware. The provider may have changed any of these. Many services rewrite the prompt with an LLM before generating, and the way they rewrite it can change as well. If you will need the image later, save the file, not just the settings.

    Sources

    Report an error · Suggest a fix