Gradium × TensorTonic Voice Challenge is open for registration.Register now
TensorTonic guides

How to Learn Diffusion Models from Scratch, One Stage at a Time

Learn diffusion models in nine stages, from forward noising and the training loss to DDIM, flow matching, classifier-free guidance, DiT and latent diffusion, with a tested coding problem for each part.

By TensorTonic's founderLast updated 17 min read

How do you learn diffusion models?

You learn diffusion models by writing each part yourself in the order the model uses it, starting with how data is noised and ending with how a sampler turns noise back into data. The parts are the noise schedule, the closed-form forward sample, the noise prediction loss, the reverse sampling step, faster samplers, the score and flow views, guidance, the denoising network and latent diffusion. TensorTonic has a coding problem with tests for each of these, and the Build Diffusion Model from Scratch study plan collects 26 of them into seven sections.

This guide works as a diffusion model tutorial in nine stages. Each stage has a short explanation and a table that pairs every topic with a page to read and a problem to solve, so you can build a diffusion model from scratch one tested function at a time.

The nine stages of learning diffusion models and what each one produces
StageWhat you writeWhat works at the end
1. Forward noising and schedulesA linear and a cosine beta schedule and the signal-to-noise ratio they produceA list of noise levels that runs from clean data to pure noise
2. The closed-form forward sampleReparameterised Gaussian sampling and the one-jump formula for any timestepA noised copy of any input at any step, with no loop
3. Training objectiveThe noise prediction loss, the forward posterior and the conversions between noise, data and velocity targetsA loss value for a batch of noised inputs
4. The reverse processThe DDPM ancestral step and a full sampling loopNew samples generated from pure noise
5. DDIM and faster samplersThe DDIM step and Karras noise levels with an Euler solverGood samples in far fewer network calls
6. Score matching and flow matchingDenoising score matching, annealed Langevin dynamics and conditional flow matchingThe same kind of generator trained from two other directions
7. Conditioning and guidanceA conditional network and classifier-free guidanceSamples that follow a class label or a prompt
8. U-Net and DiT backbonesTimestep embeddings, time-conditioned residual blocks, spatial attention, a tiny U-Net and a DiT blockA network that maps a noisy input and a timestep to a prediction of the same shape
9. Latent diffusionAn autoencoder that compresses images and diffusion on its latentsGeneration on a small latent tensor that decodes back to an image

What is a diffusion model?

A diffusion model is a generator that learns to create data by learning to remove noise from it. During training, clean images are corrupted with Gaussian noise at a randomly chosen strength, and a network learns to predict the noise that was added. To generate, the model starts from pure random noise and removes a little of it at a time over many steps until an image is left.

The idea works because adding noise is easy and fully known, while removing it is a learning problem with a simple regression target. Each training example is a noisy input and the exact noise inside it, so the network is trained with an ordinary mean squared error loss. Image generators such as Stable Diffusion are built on this method, with the extra pieces covered in the later stages of this guide.

What do you need to know before learning diffusion models?

You need Python, NumPy, the basics of PyTorch and some probability before you start learning diffusion models. The probability is narrower than it looks, since almost everything rests on the normal distribution, its mean and variance, and the KL divergence between two Gaussians. You do not need to know GANs, and you do not need to follow the full variational derivation before you can write working code.

The first section of the study plan covers the Gaussian foundations directly, so you can check yourself on them before the diffusion stages begin.

Gaussian foundations topics with a page to read and a problem to solve
TopicReadPractice
Gaussian distributionsProbability distributions lessonReparameterized Gaussian Sample
KL divergence between GaussiansKL divergence lessonDiagonal Gaussian KL Divergence
The reparameterisation trickVAE reparameterization
Markov chainsMarkov chains lesson

In what order should you learn diffusion models?

You should learn diffusion models in the order the data moves through them, which is forward noising first, then training, then sampling, and then the improvements on each of those. The forward process defines what the network has to undo, the loss depends on the noise schedule, and the sampler reuses both. The network architecture comes later than most people expect, because a small multilayer perceptron on two-dimensional points is enough to test everything before it.

Stage 1: How does the forward process add noise?

The forward process adds a small amount of Gaussian noise to the data at each of many steps, often 1,000, until nothing of the original is left. At step t it scales the previous sample by the square root of one minus beta t and adds noise with variance beta t, and the list of beta values is called the noise schedule. The original DDPM paper used betas that grow linearly, and the cosine schedule was introduced later because the linear one destroys small images too quickly.

Forward process and noise schedule topics with a page to read and a problem to solve
TopicReadPractice
Linear beta scheduleDDPM noise scheduleLinear Beta Schedule
Cosine scheduleCosine Noise Schedule
Signal-to-noise ratio at the last stepRescale to Zero Terminal SNR

The signal-to-noise ratio at each step is the most useful way to compare schedules. Many common schedules leave a little signal at the final step, so the model never sees pure noise in training even though sampling starts from it, and rescaling the schedule to zero terminal SNR removes that mismatch.

Stage 2: How do you jump to any noise level in one step?

You jump to any noise level by using the fact that a chain of Gaussian steps is itself a single Gaussian. If alpha bar t is the product of one minus beta over the first t steps, then the noisy sample is the square root of alpha bar t times the clean data plus the square root of one minus alpha bar t times standard normal noise. This closed form lets training pick a random timestep and produce the noisy input directly, without running the steps before it.

Closed-form forward sample topics with a page to read and a problem to solve
TopicReadPractice
Sampling a Gaussian with a mean and a scaleVAE reparameterizationReparameterized Gaussian Sample
Jumping to any timestepDDPM forward diffusionForward Diffusion Sample
Scaling the data to the noisez-Score Standardization

The formula is the reparameterisation trick from VAEs applied to the forward process. It also assumes the data has roughly the same scale as unit Gaussian noise, which is why images are usually scaled to the range from minus one to one before training.

Stage 3: What does a diffusion model learn to predict?

A diffusion model usually learns to predict the noise that was added to a clean input. Each training step picks a clean example, a random timestep and fresh Gaussian noise, builds the noisy input with the closed form, and minimises the mean squared error between the true noise and the predicted noise. This simple loss comes from the evidence lower bound, where most terms are KL divergences between two Gaussians, and Ho and colleagues found that dropping the weights on those terms gave better samples.

Training objective topics with a page to read and a problem to solve
TopicReadPractice
Noise prediction lossDDPM training lossNoise Prediction Loss
Mean squared errorWhich loss function to useMean Squared Error (MSE)
The forward process posteriorKL divergence lessonPosterior Mean and Variance
Noise, data and velocity targetsPrediction Parameterization
Weighting the loss across timestepsMin-SNR Loss Weighting
One full training stepTraining loss not decreasingToy Diffusion Training Step

Predicting the noise is one of three equivalent targets. The network can also predict the clean data or a velocity that mixes the two, and any of them can be converted into the others with the schedule values at that step. The choice changes how the loss is weighted across timesteps, which is what methods such as Min-SNR weighting adjust directly.

Stage 4: How does a diffusion model generate a sample?

A diffusion model generates a sample by starting from pure Gaussian noise and applying a learned reverse step once for every timestep, from the noisiest to the cleanest. Each DDPM step uses the predicted noise to estimate the mean of the slightly cleaner sample, then adds fresh noise scaled by the posterior standard deviation, except at the final step. The mean and variance come from the posterior of the forward process, which is why the posterior problem from the previous stage matters here.

Reverse process and sampling topics with a page to read and a problem to solve
TopicReadPractice
One reverse stepDDPM reverse diffusionDDPM Ancestral Step
The full sampling loopDDPM samplingToy DDPM Sampler

Every reverse step is a full forward pass through the network, so a thousand-step sampler is slow, and samplers that need fewer steps matter a great deal in practice.

Stage 5: How do DDIM and other samplers make generation faster?

DDIM makes generation faster by replacing the random reverse step with a deterministic one that can skip most of the timesteps. It turns the noise prediction into an estimate of the clean data and then rebuilds the sample at an earlier noise level from that estimate and the same noise prediction. It works with a network trained by the ordinary DDPM loss, so you get faster sampling with no retraining.

Faster sampler topics with a page to read and a problem to solve
TopicReadPractice
Deterministic DDIM samplingDDIM Step
Karras noise levels and ODE solversKarras Euler Sampler
Measuring sample qualityEvaluating generative modelsFrechet Distance Between Feature Sets

The work of Karras and colleagues treats sampling as solving an ordinary differential equation over the noise level. Their schedule of noise levels spends more steps near the clean end, and an Euler or Heun solver over those levels gives good samples in a few dozen steps. The Frechet distance problem lets you measure whether a faster sampler has cost you quality, since it is the calculation behind FID.

Stage 6: How do score matching and flow matching relate to diffusion?

Score matching and flow matching are two other ways to train the same kind of noise-to-data generator. The score of a distribution is the gradient of its log density, and a network trained to predict noise is, up to a scale factor that depends on the timestep, an estimate of the score of the noised data. Denoising score matching trains that score directly, and annealed Langevin dynamics samples with it by taking small gradient steps plus noise at a sequence of falling noise levels.

Score matching and flow matching topics with a page to read and a problem to solve
TopicReadPractice
The score of a distributionPartial derivatives and gradientsGaussian Mixture Score
Denoising score matchingDenoising Score Matching Loss
Langevin dynamicsMonte Carlo methodsAnnealed Langevin Dynamics
Flow matchingConditional Flow Matching Loss

Flow matching trains a network to predict a velocity that carries a noise sample to a data sample along a chosen path. With a straight path between the two, the target velocity is simply the data minus the noise, and sampling integrates that velocity with a few Euler steps. Rectified flow uses these straight paths, which is why it degrades more gracefully than DDPM when you cut the number of sampling steps.

Stage 7: How does classifier-free guidance steer a diffusion model?

Classifier-free guidance steers a diffusion model by combining a conditional and an unconditional noise prediction at every sampling step. During training the condition, such as a class label or a text embedding, is replaced with an empty token for a small fraction of examples, so one network learns both predictions. At sampling time the guided prediction is the unconditional prediction plus a guidance scale times the difference between the conditional and unconditional ones.

Conditioning and guidance topics with a page to read and a problem to solve
TopicReadPractice
Classifier-free guidanceClassifier-Free Guidance
Reading a prompt with cross-attentionTransformer multi-head attentionMulti-Head Attention
Text and image embeddingsTrain a Tiny CLIP from ScratchSymmetric CLIP Contrastive Loss

A larger guidance scale makes samples follow the condition more closely and reduces their variety, so the scale is a trade-off you tune. Text-to-image models read the prompt through cross-attention, where the image features provide the queries and the text embeddings provide the keys and values.

Stage 8: Should the denoising network be a U-Net or a Transformer?

The denoising network can be either a U-Net or a Transformer, and the choice mostly depends on scale. A U-Net shrinks the image in an encoder, grows it back in a decoder, and carries fine detail across with skip connections, while a sinusoidal timestep embedding is added inside each residual block so the network knows how noisy its input is. Self-attention at the lower resolutions lets distant parts of the image affect each other.

Denoising network topics with a page to read and a problem to solve
TopicReadPractice
U-Net encoder and decoderU-Net encoder block, U-Net decoder block
Skip connectionsU-Net skip connectionU-Net Skip Connection
Residual blocksResNet Residual Block
Timestep embeddingTransformer positional encodingSinusoidal Timestep Embedding
Time-conditioned residual blockTime-Conditioned Residual Block
Self-attention over image featuresAttention in LLMsSpatial Self-Attention Block
The full U-NetFull U-NetTiny U-Net Forward Pass
Images as patchesViT patch embeddingPatchify a Batch of Images
The Diffusion Transformer blockDiT Patchify and adaLN-Zero Block

A Diffusion Transformer, or DiT, cuts the input into patches and processes them with Transformer blocks. It conditions each block with adaptive layer normalization, where the timestep and class embedding produce a scale and a shift, and adaLN-Zero adds a gate initialised to zero so that each block starts as the identity. DiTs scale more predictably with compute, which is why many recent large image and video models use them.

Stage 9: What is latent diffusion?

Latent diffusion is diffusion run on the compressed latent space of an autoencoder instead of on raw pixels. An autoencoder is trained first to encode an image into a much smaller tensor and decode it back, and the diffusion model is then trained and sampled entirely on those latents. Stable Diffusion works this way, and its autoencoder reduces each spatial side of the image by a factor of eight, which makes every denoising step far cheaper.

Latent diffusion topics with a page to read and a problem to solve
TopicReadPractice
AutoencodersAutoencoder Forward Pass
The VAE encoder and decoderVAE encoder, VAE decoderVariational Autoencoder Forward Pass
The KL term and the ELBOVAE KL divergence, VAE ELBO loss

Nothing in the earlier stages changes when you move to latents, since the schedule, the loss and the sampler all work on whatever tensor they are given. The new parts are the autoencoder and the final decode, and the VAE lessons explain the KL term that keeps the latent space smooth enough to generate from.

Can you learn diffusion models without a GPU?

Yes, you can learn diffusion models without a GPU, because every component can be written and tested on small arrays or two-dimensional toy data. A GPU only matters when you train an image model at a useful size, and even then a small model on small images trains quickly. The skills you are building are the formulas and the shapes, and those are identical on a laptop and on a cluster.

The coding problems linked in this guide run in the browser and are checked against tests, so there is nothing to install. Our guide on practising ML without a GPU covers where to find compute when you want to train something larger.

How do you put the pieces together into a model that generates?

You put the pieces together by training on a toy dataset first, checking each part against a known answer, and only then moving to images. The Generate Images with Diffusion and Rectified Flow project follows this path in PyTorch, training DDPM and rectified flow on a 2D spiral and then on 14 × 14 clothing images, and it measures how many sampling steps each model needs.

  1. Scale the data so it has roughly the same range as unit Gaussian noise.
  2. Build the schedule and confirm that alpha bar falls steadily towards zero at the last step.
  3. Noise a batch to the last step and check that its mean is close to zero and its standard deviation close to one.
  4. Check that a network which always predicts zero noise gets a loss of about one, which is the variance of the noise.
  5. Train on the 2D toy data until the loss falls clearly below that baseline.
  6. Sample with the full DDPM loop, plot the samples against the data, and then try DDIM with far fewer steps.

What should you build after your first diffusion model?

After your first diffusion model, the useful next steps are sampling in very few steps, conditioning on text, and moving to Transformer backbones. Each of these is one of the stages above taken further, and the table pairs each direction with something to read and a project or plan to work through.

What to build after a first diffusion model, with a page to read and a project or plan for each direction
DirectionReadBuild
Sample in very few stepsGenerate Images with Diffusion and Rectified Flow
Condition on textTransformer encoder blockTrain a Tiny CLIP from Scratch
Work with Transformer backbonesFull ViTBuild a Tiny Vision Transformer
Compare with older generatorsGAN, VAECracking Deep Learning study plan
Go deeper on visionCracking CV study plan

If you are preparing for interviews, the computer vision interview questions guide has a section on generative models that compares GANs, VAEs and diffusion and explains how a diffusion model is trained. For a wider list of papers to build in order, see the ML papers worth implementing from scratch.

What mistakes do people make when learning diffusion models?

  • Starting with the full derivation before writing any code slows most people down, so write the forward sample and the loss first and read the derivation once they work.
  • Mixing up beta, alpha and alpha bar, or indexing them off by one step, gives samples that are slightly wrong with no error message, so print the values at the first and last step.
  • Feeding images in the range from zero to one instead of minus one to one leaves the data on a different scale from the noise.
  • Sampling the timestep once per batch instead of once per example makes the loss jump around and slows training.
  • Adding fresh noise on the final reverse step leaves visible grain in the output.
  • Judging progress by the training loss alone hides poor samples, since the loss stays fairly flat late in training, so look at samples and measure a distance such as FID.
  • Jumping straight to a large U-Net on real images makes every bug expensive, and a small network on 2D points shows the same bugs in seconds.

Practice this

Then work through the full Build Diffusion Model from Scratch study plan, or train both models end to end in the Generate Images with Diffusion and Rectified Flow project.

How long does it take to learn diffusion models?

Most people with working PyTorch and basic probability can learn the core of a diffusion model in a few weeks of steady practice. The forward process, the noise prediction loss and the DDPM sampler are the core, and they take the most time to understand properly. DDIM, flow matching, guidance and latent diffusion each add a smaller idea on top of that core and go faster once it is solid.

Do you need advanced math to learn diffusion models?

You need less math than the papers suggest. Writing and testing a diffusion model only requires the normal distribution, its mean and variance, the KL divergence between two Gaussians and the chain rule. The full variational derivation and the stochastic differential equation view are worth reading later, after the code works, because the code makes the symbols much easier to follow.

Should you learn GANs and VAEs before diffusion models?

You do not need GANs before diffusion models, but a VAE is worth learning first or alongside. A VAE teaches the reparameterisation trick and the KL term, which diffusion uses directly, and latent diffusion runs on the latent space of an autoencoder. GANs are a separate family, and they matter mainly for comparison questions in interviews.

What is the difference between DDPM and DDIM?

DDPM and DDIM use the same trained network and differ only in how they sample. DDPM adds fresh random noise at every reverse step and usually needs hundreds or a thousand steps. DDIM uses a deterministic update when its noise parameter is zero, which lets it skip steps and produce good samples in tens of steps without any retraining.

Is flow matching replacing diffusion?

Flow matching is closely related to diffusion, and several recent image models are trained with it instead of the noise prediction loss. Both methods move samples from a Gaussian to the data distribution with a learned network, and a diffusion model can be rewritten as a flow with a particular path. Flow matching with straight paths tends to need fewer sampling steps, which is a large part of its appeal.

Related guides

Keep reading