Back to blog
Generative AI

Diffusion Models from SDEs to Images

A practical walk through the score-based image generation system I built with VE, VP, Sub-VP processes and multiple samplers.

Adam MaltoniPublished on 28 May 2025, 09:0019 min read
Diffusion samples progressing from noise to generated images

The one-sentence version of diffusion image generation is almost too clean: add noise until an image becomes Gaussian static, then learn how to reverse the process. It is a good intuition, but it hides the engineering question that made this project interesting:

What exactly is "the process" that we reverse, and how many ways can we reverse it?

In this project, I worked on a modular generative image system built around score-based diffusion. The goal was not to train a giant production model. It was to build a practical experimental platform where the user could swap the diffusion process, the noise schedule, the sampler, and the conditioning mode without rewriting the whole system.

The system supported grayscale and RGB image datasets, trained a U-Net-style score model, generated samples from noise, evaluated them with standard metrics, and included controlled generation modes such as class conditioning and imputation.

The part I liked most was that the project refused to stay as a single notebook. Diffusion code becomes misleading very quickly when the SDE, the scheduler, the sampler, and the visualization are all tangled together. You can get a grid of images, but you cannot tell whether an improvement came from the process, the integration method, a conditioning trick, or just a lucky seed. I wanted the package to make those choices explicit enough that a bad experiment would at least fail for a traceable reason.

The score is the direction back to data

The forward process starts from a clean image x_0 and progressively corrupts it into x_t. For a continuous-time diffusion model, this corruption can be described as an SDE:

dx = f(x, t) dt + g(t) dw

Here f is the drift, g controls the diffusion magnitude, and dw is Brownian noise. The model does not need to learn this forward process; we choose it.

Learning happens in the reverse direction. The model learns a score function:

score(x_t, t) ~= gradient_x log p_t(x_t)

Intuitively, the score points toward regions where the noisy sample looks more like something that could have come from the data distribution at that noise level. Sampling then becomes numerical navigation: start at noise, repeatedly ask the score network which way data lies, and integrate backward.

The two equations I kept coming back to were the denoising score-matching objective and the reverse-time dynamics. In implementation terms, the model is learning a time-conditioned vector field:

theta* = argmin_theta E_t,x0,z [
  lambda(t) || s_theta(x_t, t, y) - target_score(x_t, x0, t) ||_2^2
]

reverse SDE:
dx = [f(x,t) - g(t)^2 * s_theta(x,t)] dt + g(t) d_w_bar

probability-flow ODE:
dx = [f(x,t) - 0.5 * g(t)^2 * s_theta(x,t)] dt

That is why the sampler abstraction mattered. Euler-Maruyama, Predictor-Corrector, and Probability Flow ODE are not cosmetic variants; they are different ways of using the same learned score field.

A very compressed training loop looks like this:

for image x0 in dataset:
  sample time t
  sample noise z
  construct noisy image xt from the chosen SDE
  ask ScoreNet(xt, t, condition) to predict the score/noise direction
  update the network with a denoising score-matching loss

That is the conceptual core. The rest of the project is about making each block explicit and replaceable.

Three forward processes: VE, VP, and Sub-VP

The report implemented three diffusion-process families.

Variance Exploding (VE) behaves like a Brownian-motion-style process where the variance grows over time. There is no drift term pulling the sample back; the image degrades because dispersion increases. VE is conceptually direct and useful for understanding score-based SDEs, but its noise scale can grow aggressively.

Variance Preserving (VP) adds noise while keeping the overall variance controlled. In the project report, VP is described through an Ornstein-Uhlenbeck-style process where both drift and diffusion depend on time. The image becomes progressively less informative, but the distribution does not simply explode outward.

Sub-Variance Preserving (Sub-VP) modifies the VP coefficients so the transition from image to noise is more progressive. It is close enough to VP to share much of the machinery, but different enough to make comparisons interesting.

The user-facing point of implementing all three was simple: the diffusion process is not a background detail. It changes the signal-to-noise geometry seen during training and the numerical behavior encountered during sampling.

Noise schedules: linear versus cosine

For VP and Sub-VP, the system needed a schedule that controls how quickly noise is introduced. I implemented two options:

  • A linear schedule, which is easy to reason about and changes noise intensity in a direct way.
  • A cosine schedule, which changes more smoothly and often gives a more natural degradation path.

The schedule is one of those small choices that becomes large in practice. If the model sees too much noise too early, learning becomes inefficient. If corruption is too gentle, the model may not learn the high-noise regime needed at the start of sampling. A diffusion system is less like a single algorithm and more like a chain of compatible numerical decisions.

The ScoreNet and why U-Net is a natural fit

The score model used a U-Net-style architecture with time information injected into the network. U-Nets work well here because denoising is both local and global. Local texture matters, but the model also needs long-range context to reconstruct coherent structure.

The system used Fourier embeddings for time, and, in conditional cases, class information was injected alongside the temporal embedding. So the model learned not only:

score(x_t, t)

but, when labels were available:

score(x_t, t | y)

That distinction matters for controlled generation. If y is a class label such as a digit in MNIST, the score field changes: the model should guide the noisy sample toward images that are plausible and also belong to that class.

Sampling is numerical analysis wearing a generative-AI jacket

Once the score network is trained, image generation becomes integration. Start from random noise and step backward through the learned reverse dynamics. The project implemented four samplers.

Euler-Maruyama is the basic stochastic integrator. It combines a drift-like update with a random noise term. It is simple, fast, and a good baseline, but it may need many steps for high-quality results.

Predictor-Corrector improves the basic reverse path by alternating two moves: a predictor step that advances the reverse SDE, and a corrector step that refines the sample, often with Langevin-style updates. It can produce better images, but extra corrector steps increase compute.

Probability Flow ODE turns the reverse stochastic process into a deterministic ordinary differential equation. This removes the random component during sampling. The result is often more deterministic and repeatable; diversity depends more directly on the initial noise.

Exponential Integrator uses exponential functions to handle parts of the reverse dynamics more carefully. In the implementation, it can also become deterministic when the noise parameter is set to zero, making it conceptually close to Probability Flow ODE in that regime. The report notes one important compatibility constraint: the VE process is not used with the Exponential Integrator.

The sampling API made the tradeoff explicit:

load trained model
choose diffusion process
choose compatible sampler
choose number of steps and sampler parameters
generate a batch
plot samples

This may sound like ordinary software modularity, but for diffusion models it is a big deal. A sampler is not just an implementation detail; it is part of the model's behavior.

One of the useful sanity checks was timing the sampler combinations instead of only looking at final images. The plot below is not a universal benchmark; it came from a small experimental setting, so I would not over-interpret CPU versus CUDA ratios. But it captures the engineering shape of the problem: Predictor-Corrector is cheap in this configuration, Euler-Maruyama is heavier, and the Exponential Integrator sits in the middle while behaving differently from the stochastic samplers.

Average sampling time per sampler grouped by device for a digit-3 MNIST Sub-VP experiment.

That matters because sampler choice is not only about visual quality. It changes latency, repeatability, and the number of reverse steps you can afford. In a teaching notebook, that tradeoff can be hidden. In a reusable package, it needs to be surfaced because the "best" sampler under a metric may be the wrong sampler for an interactive workflow.

Conditioning: pushing the sample toward a class

The system included class-conditioned generation when the dataset supported labels. The model can be trained with class embeddings, so generation can ask for a specific category:

sample class = 3
start from Gaussian noise
run reverse process using score(x_t, t | class=3)
return images that should look like that class

The report also discusses classifier-free guidance. The basic idea is to learn both conditional and unconditional behavior, then combine them during sampling:

guided_score =
  unconditional_score
  + guidance_scale * (conditional_score - unconditional_score)

Increasing the guidance scale pushes harder toward the class condition. Too little guidance and the class signal is weak; too much and diversity can suffer. One of the useful observations from the project was that guidance intensity can be adjusted over time to balance visual precision and variety.

Imputation: diffusion as constrained editing

Imputation was the other control mechanism. Instead of generating the whole image freely, the model receives a partially observed image and a binary mask indicating which region is missing. The reverse process is constrained so the observed pixels stay fixed while the missing region is regenerated.

The conceptual loop is:

given original image x and mask M:
  keep observed region fixed
  diffuse or initialize the missing region
  during each reverse step:
    update only the masked region with the score model
    restore observed pixels from the known image

This turns diffusion from "make me an image" into "complete this image in a way that is consistent with its context." It is a small version of the same principle behind many modern image-editing workflows: the model has learned a distribution over images, and the mask constrains where it is allowed to move.

Image imputation demo showing original MNIST digits, masked inputs, and reconstructed missing regions.

The imputation demo is small, but it is a good test of whether the implementation is really doing conditional generation and not just unconditional sampling with a mask drawn on top. The observed pixels have to be re-imposed during the reverse process, otherwise the sample drifts away from the known context. That tiny implementation detail is exactly the kind of thing that separates a diffusion explanation from a diffusion tool.

Evaluation: do not trust the prettiest grid

The project included a metrics module with three common image-generation metrics.

Bits per dimension (BPD) estimates how well the model explains the data distribution, normalized by image dimensionality.

Frechet Inception Distance (FID) compares statistics of generated images against real images in an Inception feature space. Lower is better, and the metric is often used as a rough proxy for visual realism and distributional similarity.

Inception Score (IS) tries to reward images that are both classifiable and diverse across classes.

These metrics are imperfect, especially on small academic experiments and simple datasets. Still, including them matters because visual grids are dangerously persuasive. A generated sample can look promising while the model is collapsing in diversity, or the metric can look acceptable while the images are blurry. The healthy approach is to inspect both.

The software shape

The report describes the system as a package rather than a single notebook. The main design separated:

  • Diffusion process definitions.
  • Noise schedules.
  • The ScoreNet architecture.
  • Training routines.
  • Sampling algorithms.
  • YAML/dictionary configuration.
  • Conditioning and imputation utilities.
  • Evaluation functions.
  • Notebooks for training, generation, evaluation, and advanced examples.

The central orchestrator was a DiffusionExperiment-style class that hid the wiring from the user. A typical workflow looked like this:

experiment = DiffusionExperiment(config)
experiment.train(dataset)
experiment.sample_and_plot(sampler="predictor_corrector")
experiment.evaluate(metrics=["bpd", "fid", "is"])

The actual implementation also handled practical requirements: grayscale or RGB inputs, normalization to [-1, 1], PyTorch tensor formatting, model saving/loading, CPU/GPU detection, tests for key components, and notebooks that execute the workflows in order.

What the demos showed

The report describes five demonstration notebooks.

The first trained models on MNIST digit 3, using VE, VP, and Sub-VP variants with linear or cosine schedules. The second compared sampling methods from the trained models: Euler-Maruyama, Predictor-Corrector, Probability Flow ODE, and Exponential Integrator. The third moved to color images using the boat class from CIFAR-10. The fourth evaluated generated samples with BPD, FID, and IS. The fifth demonstrated class conditioning and imputation over MNIST digits.

The results were deliberately framed with modest compute in mind. Training a U-Net-based model from scratch with reduced model size and a limited number of training steps cannot compete with large diffusion systems. But the generated images were coherent enough to demonstrate that the system learned useful relationships between noise, class information, and visual form.

Sub-VP Predictor-Corrector sample progression from random noise to CIFAR-10 boat images.

I would not present these samples as artistic output. They are more useful as debugging evidence. The left side is still noise, the right side has learned class-level structure, and the middle of the pipeline is where small mistakes in normalization, timestep scaling, or sampler compatibility usually show up. When a generated image looks wrong, the bug is rarely just "the model is bad"; it can be the score target, the marginal probability function, the timestep embedding, the reverse-step variance, or the conditioning path.

That makes the project valuable as an experimental platform: not "look, I recreated a frontier image model," but "look, every important moving piece of score-based image generation is implemented, swappable, and testable."

The lesson I took from building it

Diffusion models are often taught as if the key idea is just repeated denoising. Building one makes the real structure clearer. A diffusion model is a stack:

data preprocessing
  -> forward SDE
  -> noise schedule
  -> score network
  -> training objective
  -> sampler/integrator
  -> conditioning rule
  -> evaluation metric

Each layer can be changed. Each change has mathematical and software consequences. VE, VP, and Sub-VP define different noise geometries. Euler-Maruyama and Probability Flow ODE express different beliefs about stochasticity during sampling. Class conditioning and imputation turn generation into controlled navigation through the learned image distribution.

The most useful part of the project was seeing how the math becomes engineering. The equations tell you what the process should be; the package design decides whether you can actually compare variants without tearing the system apart.

That is the kind of generative AI project I like: not just a gallery of samples, but a small laboratory where the algorithm's moving parts are visible.