Diffusion Models and Stable Diffusion
Forward noise, reverse denoising, DDPM, latent diffusion — how Stable Diffusion generates photorealistic images from text prompts.
Diffusion models learn one thing: given a slightly noisy image, predict the noise that was added. Run this backwards 1000 times starting from pure noise and you get a photorealistic image.
GANs generate images in one forward pass — fast but unstable. VAEs generate via a compressed latent code — stable but blurry. Diffusion models take a third path: learn to reverse a gradual noising process. The training objective is deceptively simple — take a real image, add a known amount of Gaussian noise, ask the model to predict what noise was added. Repeat this for every noise level from slightly noisy to pure noise. At generation time, start from pure Gaussian noise and iteratively denoise, guided by what the model learned.
The results are extraordinary — diffusion models produce images that are sharper, more diverse, and more faithful to text prompts than any previous approach. Stable Diffusion, DALL-E 3, Midjourney, and Google Imagen are all diffusion models. At e-commerce companies: Shopify uses Stable Diffusion fine-tuned on product catalogs to generate product variations. Adobe's Firefly (widely used by creative agencies) is diffusion-based. Every modern text-to-image system is built on this foundation.
Teaching someone to restore old damaged photographs. You take a pristine photo and progressively scratch it — first a tiny scratch, then more, then more, until it is completely unrecognisable static. You train a restorer to undo each level of damage. After enough practice they can take completely random static and restore it step by step into a meaningful photograph. The key insight: each restoration step is easy — remove a small amount of noise. But chaining 1000 easy steps produces something remarkable.
The model never needs to generate from nothing. It only ever needs to answer: "given this noisy image at this noise level, what noise should I remove?" That is a much simpler task than "generate a photorealistic image from scratch."
Adding noise — the Markov chain from image to pure noise
The forward process is fixed — not learned. It gradually adds Gaussian noise to an image over T timesteps (typically T=1000). At each timestep t, a small amount of noise is added according to a noise schedule β₁, β₂, …, β_T. By timestep T the image is indistinguishable from pure Gaussian noise. The key mathematical property: you can jump directly to any timestep t without simulating all steps sequentially. This is what makes training efficient.
The U-Net denoiser — predict the noise, not the image
The learnable part of a diffusion model is a neural network that takes a noisy image x_t and a timestep t as input, and predicts the noise ε that was added. The architecture is a U-Net with time conditioning — the timestep t is embedded into a sinusoidal positional encoding and injected into every residual block via addition or cross-attention. The network must learn to denoise differently for each noise level — removing a tiny amount of noise at t=10 is very different from recovering structure at t=900.
DDPM training loop and reverse process sampling
Training is remarkably simple: sample a random image from the dataset, sample a random timestep t, add the corresponding amount of noise, ask the model to predict the noise, compute MSE loss. That is the entire training algorithm. No adversarial game, no posterior collapse, no mode collapse. This simplicity is why diffusion models train so reliably compared to GANs.
Sampling (generation) runs the reverse process: start from pure Gaussian noise x_T, iteratively denoise using the trained model, and arrive at a clean image x_0 after T steps. Each denoising step predicts the noise at the current timestep and subtracts it, producing a slightly cleaner image. The full T=1000 steps is slow — DDIM (denoising diffusion implicit models) achieves similar quality in 20–50 steps.
Why Stable Diffusion runs on consumer GPUs — diffusion in latent space
Running DDPM directly on 512×512 images requires 1000 U-Net forward passes on high-resolution feature maps — enormously expensive. Stable Diffusion's key insight: run diffusion in the latent space of a pretrained VAE, not in pixel space. A VAE encodes a 512×512×3 image into a 64×64×4 latent tensor — a 48× reduction in resolution. Diffusion in this compressed space is 48× faster per step with no loss in final quality, because the VAE decoder restores full resolution at the end. This is Latent Diffusion Models (LDM).
DreamBooth and LoRA — fine-tuning on your own images
Pretrained Stable Diffusion generates generic content. For specific fashion product images, architectural styles, or brand-specific visual language, you need to fine-tune. Two efficient methods: DreamBooth fine-tunes the entire U-Net on 3–30 images of a specific concept and teaches the model a new token that refers to it. LoRA (Module 51) fine-tunes only 0.5% of the U-Net parameters — achieves similar results with 10× less memory and training time.
Every common diffusion model mistake — explained and fixed
Where diffusion models actually run in production
Almost every consumer-facing "generate an image" feature shipped since 2022 is a diffusion model behind an API, not a raw prompt box. Shopify merchants generate product variations and lifestyle shots from a single hero photo. Adobe Firefly powers Generative Fill inside Photoshop — select a region, describe what should be there, and a latent diffusion model inpaints it consistent with lighting and perspective. Canva's Magic Media and Amazon's advertising creative tools generate dozens of ad variations per SKU overnight so a marketing team can A/B test creative instead of commissioning a photoshoot for every size and background colour. Game studios use fine-tuned diffusion pipelines for concept art and texture generation — not to ship final assets untouched, but to compress a week of concept iteration into an afternoon.
Video generation is the newest frontier built on the same core idea. Runway Gen-3, Pika, Luma, and OpenAI's Sora extend the denoising U-Net (or a Transformer backbone doing the equivalent job) along a temporal axis — instead of denoising one image, the model denoises a whole clip of correlated frames at once, with extra attention layers that keep objects and motion coherent from frame to frame. This is dramatically more expensive than image diffusion: a five-second clip at even a modest frame rate is effectively dozens of images that all have to stay consistent with each other, which is why production video diffusion still runs on large GPU clusters rather than a single consumer card.
Slack message from the growth team: "We are launching 60 new denim SKUs next week. Can we get 8 lifestyle images per SKU — different backgrounds, different models, same product — by Thursday?" That is 480 images with a Thursday deadline, not a research problem. The real work is pipeline engineering: a LoRA fine-tuned on the brand's existing catalog for visual consistency, a ControlNet conditioned on each product's silhouette so the garment shape never distorts, a queue that batches prompts across a small GPU fleet using DPM-Solver++ at around 20 steps for throughput, a safety/NSFW classifier and a brand-compliance check on every output before it reaches a human reviewer, and a fallback path to a real photoshoot for the handful of images that fail review. The model call is a small fraction of the actual engineering effort.
Five things people get wrong about diffusion models
The forward process is fixed before training even starts — it is entirely determined by the noise schedule (the sequence of beta values), with no trainable parameters anywhere in it. The only learned component is the reverse process: the U-Net that predicts what noise was added at a given timestep. This is why you can swap the sampler (DDPM to DDIM to DPM-Solver++) or change the number of inference steps without retraining anything — none of that logic lives in the trained weights, it lives entirely in how you choose to run the fixed forward process backwards.
A GAN's generator produces a full image in a single forward pass. A diffusion model necessarily runs many forward passes through the same network, each one removing a little more noise from an evolving canvas — even the fast samplers still take roughly 20 to 50 steps, not one. This iterative structure is not an implementation detail that could be optimised away without changing the model; it is the mechanism that makes diffusion training so much more stable than adversarial training, at the direct cost of slower generation.
The training objective does look exactly like denoising — predict the noise that was added to a real image. But a plain denoising autoencoder, run once, could never turn pure random static into a photorealistic image; it only knows how to clean up an already-mostly-correct input. What makes diffusion generative is that the network is trained across every noise level at once and then chained, at generation time, into a multi-step process that starts from pure noise rather than a corrupted real image. That chained reverse process is effectively performing iterative score-based sampling — repeatedly nudging a sample toward regions of higher data likelihood — which is a fundamentally different job than one-shot denoising.
Diffusion is not faster at inference — a GAN's single forward pass will always beat a 20-to-50-step diffusion sampler on raw generation speed, and well-tuned GANs remain competitive on narrow, single-domain tasks like face generation. What diffusion actually won on is training stability (no adversarial balancing act, no mode collapse to fight), sample diversity, and faithfulness on complex, multi-object, prompt-driven generation at scale — the exact properties that matter for a general-purpose text-to-image system serving arbitrary prompts. It is a better foundation for that specific job, not an unconditional upgrade on every axis.
Quality gains from additional steps flatten out sharply past roughly 30 to 50 steps with a good sampler like DPM-Solver++ — beyond that point you are mostly spending compute for an image nearly indistinguishable from a few steps earlier. Distilled models like LCM and SDXL-Turbo make this explicit: they train a student network to jump what would normally take many denoising steps in as few as one to four, trading a small, often barely perceptible quality cost for near real-time generation. Step count is a tunable engineering knob you trade against latency, not a fixed law that ties more computation directly to better output.
Diffusion models — 5 questions interviewers actually ask
The noise schedule is the sequence of beta values that controls how much Gaussian noise gets added at each of the T forward timesteps, and its cumulative product (alpha-bar) determines the signal-to-noise ratio at every point along the chain. A linear schedule, used in the original DDPM paper, spends a lot of the early timesteps barely perturbing the image and then destroys it very quickly near the end. A cosine schedule spreads the destruction more evenly, preserving more usable signal through the middle and late timesteps, which the Improved DDPM paper showed measurably improves perceptual sample quality. In short: the schedule determines what fraction of training effectively happens at "easy" versus "hard" noise levels, and a poorly chosen one wastes model capacity on noise levels that do not matter much for final quality.
Reverse diffusion is inherently sequential: producing the image at step t minus one requires the output already computed at step t, so you cannot parallelise across timesteps the way you can across a batch during training. DDIM reformulates the reverse process as a non-Markovian, deterministic mapping that solves the same underlying differential equation but allows skipping directly from one timestep to a much earlier one, cutting a thousand sequential steps down to roughly twenty to fifty with little quality loss. Distillation goes further: a student network is trained to directly predict what several steps of the full teacher process would have produced, eventually collapsing the entire chain to as few as one to four steps, which is how models like LCM achieve near real-time generation.
Classifier-free guidance runs the same U-Net twice per step — once conditioned on the text prompt, once with the prompt dropped — and pushes the final prediction further in the direction the conditioned pass diverges from the unconditioned one, scaled by the guidance_scale parameter. The older alternative, classifier guidance, required training a separate classifier on noisy images at every noise level and using its gradient to steer sampling — expensive to train, tied to whatever labels that classifier was built for, and numerically fragile. Classifier-free guidance needs no second model: the same diffusion model is simply trained with prompt conditioning randomly dropped some fraction of the time, so one set of weights can do both the conditioned and unconditioned forward pass needed for guidance.
A pretrained VAE compresses a 512-by-512 pixel image down to a much smaller latent tensor before diffusion ever touches it, so every one of the many denoising steps operates on roughly forty-eight times fewer values. That compression is handled once, by a separate frozen network trained specifically for perceptual compression, which frees the diffusion U-Net's entire capacity for modelling semantic content rather than spending iterations removing noise from raw pixels. The VAE decoder restores full resolution only once, at the very end, after the expensive iterative part is already finished — which is the difference between Stable Diffusion running on a consumer GPU and needing a data-centre-scale setup for the same output quality.
It comes down to how much data you have and how much you need to preserve the model's general knowledge. With only five to ten images of a single subject, textual inversion or DreamBooth with prior preservation loss is the right call — DreamBooth updates more of the network so it captures the subject better, at higher risk of catastrophic forgetting without prior preservation. For a broader style or a specific product line with more examples, LoRA is usually the right default: it trains a small fraction of parameters, produces a compact adapter file that is easy to version, swap, and combine with other LoRAs, and is much less prone to overwriting the base model's general capability. Full fine-tuning of the entire U-Net is rarely justified for an application team — it is expensive, slow to iterate on, and LoRA reaches comparable quality for a fraction of the cost in the vast majority of real product use cases.
You understand how images are generated. Next: how the largest language models are built and aligned.
Diffusion models generate images by learning to reverse a noising process. LLMs generate text by learning to predict the next token — but at a scale and with emergent capabilities that make them qualitatively different from anything before. Module 64 covers how GPT, Claude, and Gemini are built: next-token pretraining at scale, RLHF alignment, DPO, instruction tuning, and the scaling laws that predict capability from compute.
How GPT, Claude, and Gemini are built. Next-token prediction at scale, RLHF alignment, DPO, and the laws that predict capability.
🎯 Key Takeaways
- ✓Diffusion models learn to reverse a fixed noising process. The forward process gradually adds Gaussian noise to an image over T=1000 steps until it becomes pure noise. The reverse process trains a U-Net to predict the noise at each step. Generation = start from pure noise, run the reverse process T times.
- ✓The closed-form forward process lets you jump to any timestep t directly: x_t = √ᾱ_t × x_0 + √(1−ᾱ_t) × ε where ᾱ_t is the cumulative product of (1−β_s). Training samples random t values and asks the model to predict ε from x_t — the entire training algorithm is this MSE loss.
- ✓The denoising U-Net takes a noisy image x_t and a timestep t as input. Timestep t is converted to a sinusoidal embedding and injected into every residual block. The architecture is identical to segmentation U-Net but with time conditioning — skip connections preserve spatial detail for precise denoising.
- ✓Stable Diffusion runs diffusion in the 64×64×4 latent space of a pretrained VAE, not in 512×512 pixel space. This 48× compression makes each denoising step 48× cheaper with no quality loss. The VAE decoder restores full resolution at the end. This is Latent Diffusion Models (LDM).
- ✓Classifier-free guidance (CFG) runs the U-Net twice per step: once with the text prompt and once without. The final prediction is: eps_uncond + scale × (eps_text − eps_uncond). guidance_scale=7.5 is the standard. Higher scale = more prompt adherence but potential distortion. Lower scale = more diversity but ignores prompt.
- ✓Fine-tuning options by cost: Textual Inversion (learn one new token, 100KB, 5 images, weakest) → LoRA (train 0.09% of U-Net, 50MB, 10-50 images, strong) → DreamBooth (fine-tune full U-Net, 4GB, 5-30 images, strongest). Always use prior preservation loss in DreamBooth to prevent catastrophic forgetting of general knowledge.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.