Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college extension →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

Diffusion MathUnderstand the moving parts.

Forward + reverse process, score matching, why noise schedules matter.

Suggested preparation: 14

WORKBENCH / CHANGE ONE THING

Trace cumulative noise

Change cumulative alpha and verify the forward-process coefficients.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Repeated small noise additions are different from one arbitrary blur.

Where this deserves more time

Marginal versus transition distributions; score prediction; schedules and reverse variance.

Open the complete high-school reading

Moment 01 / 09

Course Introduction and Overview

Welcome to this course on the mathematics of diffusion models. Today we fix notation, define the core objects, and map the structure we will follow across the term.

We begin by defining diffusion probabilistic models and explaining why they displaced GANs as the dominant paradigm for image synthesis, following Ho et al. 2020 and the latent diffusion work that followed.

The framework rests on two Markov chains: a fixed forward process that gradually corrupts data with Gaussian noise, and a learned reverse process that inverts this corruption step by step.

We then develop denoising score matching, where the network learns the gradient of the log data density, and examine how the noise schedule beta-t controls the variance preserved at each step.

Expect rigorous derivations throughout: variational lower bounds, KL divergences between Gaussians, and stochastic differential equations, each paired with implementations in Python and PyTorch.

On the slide is the forward sampling function in closed form: the cumulative product of alphas lets us jump directly to any timestep, which we will derive and implement line by line.

By the end, you will be able to derive the training objective from first principles, implement DDPM and flow matching, and read current diffusion research with full command of the mathematics.

Equations, code and original cards

Course Introduction and Overview

• Diffusion probabilistic models, defined

• Why they dominate image synthesis (Ho et al. 2020)

• Forward process: fixed Gaussian corruption

• Reverse process: learned denoising chain

q(\mathbf{x}_t | \mathbf{x}_{t-1}) = \mathcal{N}(\mathbf{x}_t; \sqrt{1 - \beta_t} \mathbf{x}_{t-1}, \beta_t \mathbf{I})

Forward step: q(x_t | x_{t-1}) Gaussian, variance \(\beta_t\)

• Denoising score matching

• Noise schedule \(\beta_t\) and signal retention

• ELBO, KL divergences, SDEs

• Implementations in Python & PyTorch

import torchdef q_sample(x_start, t, noise):  return torch.sqrt(1 - beta_t[t]) * x_start + torch.sqrt(beta_t[t]) * noise

Moment 02 / 09

Mathematical Foundations: Forward Diffusion Process

We start with the forward diffusion process, the fixed Markov chain that corrupts data into approximately isotropic Gaussian noise. In DDPM this is not learned; it defines the target geometry that the reverse denoising model must invert.

The forward kernel q of x-t given x-minus-one is a Gaussian Markov transition: each step contracts the signal and injects fresh isotropic noise, so the marginal drifts toward the standard normal prior.

Explicitly, x-t is sampled from a normal whose mean is the square root of one minus beta-t times x-t-minus-one, and whose covariance is beta-t times the identity; signal is shrunk while independent noise is added coordinatewise.

Beta-t is the per-step noise variance; its schedule sets the corruption rate. A common linear or cosine schedule rises with t, driving the terminal marginal close to standard normal while keeping early steps nearly invertible.

Across steps, the joint q of x-one through x-T given x-zero factorizes as a product of these Gaussians. Because each transition is linear-Gaussian, the whole chain remains Gaussian and admits a useful closed form.

The key identity is x-t equals the square root of alpha-bar-t times x-zero plus the square root of one minus alpha-bar-t times epsilon, with epsilon standard normal. Here alpha-t is one minus beta-t and alpha-bar-t is their cumulative product, so arbitrary timesteps are sampled without simulating intermediate states.

The practical point is that alpha-bar-t, not beta-t alone, determines signal-to-noise at timestep t. Choose the schedule to control that decay; the linear-Gaussian factorization then gives exact marginals, stable training targets, and efficient sampling for the reverse model.

Equations, code and original cards

Forward Diffusion: Linear-Gaussian Corruption

Forward kernel: fixed Markov chain

• q(x_t | x_{t-1}) Gaussian; no learned parameters

• Contracts signal, injects isotropic noise → N(0, I)

q(\mathbf{x}_t \mid \mathbf{x}_{t-1}) = \mathcal{N}\bigl(\mathbf{x}_t; \sqrt{1 - \beta_t} \mathbf{x}_{t-1}, \beta_t \mathbf{I}\bigr)

Parameters

• \(\beta_t\): per-step noise variance; schedule sets corruption rate

• \(\sqrt{1-\beta_t}\): signal contraction coefficient

• \(\beta_t\mathbf{I}\): isotropic covariance, independent coordinates

q(\mathbf{x}_{1:T} \mid \mathbf{x}_0) = \prod_{t=1}^T q(\mathbf{x}_t \mid \mathbf{x}_{t-1})
\mathbf{x}_t = \sqrt{\bar{\alpha}_t} \mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t} \mathbf{\epsilon}, \quad \mathbf{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})

Closed form: \(x_t=\sqrt{\bar{\alpha}_t}x_0+\sqrt{1-\bar{\alpha}_t}\epsilon\), \(\alpha_t=1-\beta_t\), \(\bar{\alpha}_t=\prod_{s=1}^t\alpha_s\)

Moment 03 / 09

Reverse Diffusion Process and Score Matching

We now examine the reverse diffusion process and its equivalence to score matching, the mathematical backbone of modern generative modeling.

The reverse process is defined as the learned conditional p-theta of x-t-minus-one given x-t, a Gaussian transition whose mean is parameterized by a neural network. This distribution defines one denoising step backward through the Markov chain, and composing these steps from pure noise back to data constitutes generation.

The mean mu-theta of x-t and t is predicted by the network, which effectively learns how much of the current state is signal versus noise. This parameterization, introduced by Ho and colleagues in the 2020 DDPM paper, makes each reverse step tractable.

The training objective is the simplified noise-prediction loss: the expectation over data x-zero, Gaussian noise epsilon, and timestep t, of the squared error between the true noise epsilon and the network's estimate epsilon-theta of x-t and t. Minimizing this mean squared error trains the model to recover the exact noise realization that corrupted the sample.

The score function, the gradient with respect to x-t of the log density log p-t of x-t, points toward locally increasing data density. The key result is that the optimal noise predictor is proportional to the negative score, scaled by the noise standard deviation, so noise prediction is score estimation in disguise.

This equivalence, formalized by Song and colleagues in 2021, unifies diffusion models with denoising score matching: learning to remove noise at every scale is equivalent to learning the gradient field of the perturbed data distribution, which then drives Langevin-style sampling.

Turning to the gradient derivations: the gradient of the loss with respect to theta follows by the chain rule, passing through the network's Jacobian. Because the loss is a plain squared error, the gradient signal is stable and does not require the variational bound in practice.

In implementation, this reduces to a few lines of PyTorch: sample a timestep, corrupt the data with Gaussian noise, predict that noise with the network, and take the mean squared error. Backpropagation and an Adam update complete the training step.

To summarize: the reverse process is a learned Gaussian denoising step, its training objective is noise regression, and by the Tweedie-style identity this is equivalent to score matching. These three views, probabilistic, regression, and score-based, are the foundation on which modern diffusion systems are built.

Equations, code and original cards

Reverse Diffusion Process and Score Matching

Reverse Process Definition

• Learned Gaussian $p_{\theta}(\mathbf{x}_{t-1} | \mathbf{x}_t)$ per denoising step

• Network predicts noise $\boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t)$

• Learned mean $\boldsymbol{\mu}_{\theta}$, fixed variance (Ho et al. 2020, DDPM)

p_{\theta}(\mathbf{x}_{t-1} | \mathbf{x}_t) = \mathcal{N}(\mathbf{x}_{t-1}; \boldsymbol{\mu}_{\theta}(\mathbf{x}_t, t), \sigma_t^2 \mathbf{I})
\boldsymbol{\mu}_{\theta}(\mathbf{x}_t, t) = \frac{1}{\sqrt{\alpha_t}}\left( \mathbf{x}_t - \frac{1 - \alpha_t}{\sqrt{1-\bar{\alpha}_t}} \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t) \right)

Loss Function: MSE on Noise

• Objective: $\mathcal{L} = \mathbb{E}\left\| \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t) \right\|^2$

• Regression target = true added noise; stable gradients

• Expectation over $t \sim \mathrm{Uniform}$, $\mathbf{x}_0$, $\boldsymbol{\epsilon} \sim \mathcal{N}(0, I)$

\mathcal{L}_{t} = \mathbb{E}_{\mathbf{x}_0, \boldsymbol{\epsilon}} \left[ \left\| \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t) \right\|^2 \right]

Score Function & Noise Prediction

• Score: $\nabla_{\mathbf{x}} \log p_t(\mathbf{x}_t)$, direction of increasing density

• Optimal $\boldsymbol{\epsilon}_{\theta} \propto -\sigma_t \nabla_{\mathbf{x}} \log p_t(\mathbf{x}_t)$

• Noise prediction $\equiv$ score estimation (Tweedie identity)

\nabla_{\mathbf{x}_t} \log p_t(\mathbf{x}_t) = -\frac{1}{\sigma_t} \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t)

• Song et al. 2021: score matching with Langevin dynamics unifies score-based and diffusion modeling

\begin{aligned} \mathcal{L} &= \mathbb{E}_{\mathbf{x}_0, \boldsymbol{\epsilon}, t} \left\| \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t) \right\|^2 \\\ &= \mathbb{E}_{t} \mathbb{E}_{\mathbf{x}_t | \mathbf{x}_0} \left[ \left\| \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t) \right\|^2 \right] \\\ &= \mathbb{E}_{t} \mathbb{E}_{\mathbf{x}_t} \left[ \left\| \sigma_t \nabla_{\mathbf{x}_t} \log p_t(\mathbf{x}_t) + \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t,t) \right\|^2 \right] \end{aligned}

Matrix & Gradient Derivations

• $\nabla_{\theta} \mathcal{L}$ via chain rule through network Jacobian

• Squared-error loss yields stable, low-variance gradients

• Backpropagation handled by PyTorch autograd

\nabla_{\theta} \mathcal{L} = \mathbb{E}_{\mathbf{x}_0, t, \boldsymbol{\epsilon}} \left[ 2 \big( \boldsymbol{\epsilon}_{\theta} - \boldsymbol{\epsilon} \big) \cdot \nabla_{\theta} \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, t) \right]

Python & PyTorch Implementation

• Sample $t$, corrupt $\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\,\mathbf{x}_0 + \sigma_t \boldsymbol{\epsilon}$

• Loss = MSE between predicted and true noise

• Adam updates minimize the objective end-to-end

\begin{aligned}\text{def loss_fn}(model, x_0, t):\\ \quad \epsilon = \text{torch.randn_like}(x_0)\\ \quad x_t = \sqrt{\bar{\alpha}_t} x_0 + \sqrt{1 - \bar{\alpha}_t} \epsilon \\ \quad \epsilon_{\theta} = model(x_t, t) \\ \quad \mathcal{L} = \| \epsilon - \epsilon_{\theta} \|^2 \\ \quad \text{return}~\mathcal{L}\end{aligned}

Moment 04 / 09

Interactive Diagram: Forward and Reverse Processes

This diagram shows the forward and reverse diffusion processes. The forward process is a fixed Markov chain that gradually corrupts data with Gaussian noise; the reverse process is the learned transition that inverts it step by step.

Try adjusting the noise schedule types—linear, cosine, or sigmoid—to see how they affect image quality and noise levels through each step.

Observe closely how the noise profile changes with each schedule and the impact on the clarity of the image in both forward noising and reverse denoising directions.

Equations, code and original cards

Moment 05 / 09

Noise Schedules: Comparison and Impact

We now compare the principal noise schedules used in diffusion models and quantify how each one shapes the forward corruption process and, ultimately, generation quality.

Recall that the schedule fixes the per-step variance beta-t, which determines the cumulative signal retention, the product of one minus beta-s up to time t. This single quantity governs both training stability and the signal-to-noise ratio the denoiser must invert.

The linear schedule of Ho et al. 2020 interpolates beta uniformly, from ten to the minus four up to two times ten to the minus two. Its defect: signal decays too fast, so late timesteps carry almost no information and waste model capacity.

Nichol and Dhariwal's cosine schedule instead parameterizes the cumulative signal directly with a squared cosine, slowing corruption near the endpoints. This preserves structure into intermediate timesteps and yields a better-behaved variational bound and lower FID.

The sigmoid schedule interpolates log signal-to-noise ratio with a logistic curve, concentrating steps where the denoising task is hardest. It pairs naturally with learned variance, as in improved DDPM, and with the variance-preserving versus variance-exploding taxonomy of Song et al.

The takeaway: the schedule sets the signal-to-noise trajectory, and that trajectory directly moves FID. Choosing it well, or learning it, buys sample quality at zero extra compute, which is why modern latent diffusion systems tune it carefully.

Equations, code and original cards

Noise Schedules: Comparison and Impact

Key Concepts:

• Noise schedules in diffusion models govern transition noise variance βt

• Common types: Linear, Cosine, Sigmoid

• Impact on signal preservation and sample quality (FID scores)

• Reference advanced methods: iDDPM, variance-preserving and exploding schedules

\text{Linear Noise Schedule: } \quad \beta_t = \beta_{\min} + t \cdot \frac{\beta_{\max} - \beta_{\min}}{T}
\text{Cosine Noise Schedule: } \quad \beta_t = 1 - \frac{\alpha_t}{\alpha_{t-1}}, \quad \alpha_t = \cos\left( \frac{t/T + s}{1 + s} \cdot \frac{\pi}{2} \right)^2
\text{Sigmoid Noise Schedule: } \quad \beta_t = \mathrm{sigmoid}\left( k \cdot (t/T - x_0) \right) \cdot (\beta_{\max} - \beta_{\min}) + \beta_{\min}

Moment 06 / 09

Implementation Details: Python & PyTorch Coding

We now translate the diffusion framework into PyTorch. Every equation from the DDPM paper of Ho and colleagues, 2020, collapses into a few lines of tensor arithmetic.

The forward process admits a closed-form marginal: rather than simulating every noising step, we sample x-t directly from x-zero through the cumulative product of alphas, an application of the reparameterization trick.

The formula on the slide is that marginal: a Gaussian with mean square root of alpha-bar-t times x-zero, and variance one minus alpha-bar-t. The code is a single line of broadcasting arithmetic.

The model interface is an epsilon-prediction network, typically a U-Net with sinusoidal timestep embeddings, mapping the noisy sample and timestep to an estimate of the injected Gaussian noise.

The simplified objective discards the weighting terms of the variational bound: it is the expected squared error between true and predicted noise, with timesteps sampled uniformly. Ho and colleagues found this trains better.

Implementation-wise, a gather indexes alpha-bar by timestep, broadcasting aligns batch dimensions, and noise is drawn once per sample. These vectorized operations keep the entire training step to a handful of lines.

To summarize: the closed-form forward marginal, the epsilon-prediction network, and the simplified mean-squared-error loss constitute the whole training algorithm. Sampling then iterates the reverse update from pure noise to a clean image.

Equations, code and original cards

Implementation: DDPM in Python & PyTorch

Core Functions & the Noise-Prediction Interface

• Forward process: closed-form marginal q(x_t | x_0)
  def q_sample(x_start, t, noise):
     return sqrt_alphas_cumprod[t] * x_start + sqrt_one_minus_alphas_cumprod[t] * noise

• Reverse process: predict injected noise
  eps_theta = model(x_t, t)
• Simplified objective (Ho et al. 2020):
  loss = mse(eps_theta, noise)

q(x_t|x_0) = \mathcal{N}\left(x_t; \sqrt{\bar{\alpha}_t}x_0, (1 - \bar{\alpha}_t) \mathbf{I}\right)
\mathcal{L}_{\text{simple}} = \mathbb{E}_{x_0,\epsilon,t} \left[ \| \epsilon - \epsilon_\theta(x_t, t) \|^2 \right]

Moment 07 / 09

Advanced Techniques and Optimizations

We now turn to the optimizations that define modern diffusion practice: variance schedules, fast samplers, conditioning interfaces, and scale. The goal is not novelty; it is lower latency at fixed perceptual quality.

Start with the noise schedule, the variance path that controls signal-to-noise ratio across time. Cosine and EDM-style parameterizations reduce train-test mismatch; adaptive or learned schedules spend steps where the score is hardest to estimate.

Formally, choose a monotone mapping from continuous time to log signal-to-noise ratio, then reparameterize the loss so the network predicts noise, velocity, or clean data under one weighting.

For inference, DDIM makes sampling deterministic by removing the Markov noise term; DPM-Solver and EDM integrators exploit the probability-flow ordinary differential equation, while consistency and rectified-flow models target one to eight network evaluations.

Conditioning is an alignment problem: text embeddings must enter the residual stream through cross-attention or adaptive normalization with compatible scale. Classifier-free guidance trades diversity for prompt fidelity by extrapolating between conditional and unconditional logits.

Architecturally, latent diffusion and diffusion transformers dominate: move computation to a compressed latent space, use patch tokens with rotary positions, and scale width, depth, data, and guidance jointly rather than chasing resolution alone.

Equations, code and original cards

Advanced Diffusion: Schedules, Samplers, Conditioning, Scale

Variance design, probability-flow sampling, alignment, and scaling practice

Key Concepts:

• Log-SNR schedules: cosine, EDM, learned or adaptive

• Deterministic DDIM; ODE solvers; consistency and rectified flow

• Cross-attention, AdaLN, classifier-free guidance alignment

• Latent diffusion plus DiT: patchify, RoPE, joint scaling

• Ablate guidance, loss weighting, sampler order, step budget

\text{Diffusion Process: } x_{t} = \sqrt{\alpha_t} x_{0} + \sqrt{1-\alpha_t} \epsilon_t, \quad \epsilon_t \sim \mathcal{N}(0, I)
\text{Noise Schedule Adaptive Update: } \alpha_{t+1} = \alpha_t - \eta \cdot \nabla_{\alpha_t} L \quad (L = \| \hat{x}_0 - x_0 \|^2)
# Deterministic probability-flow samplingdef sample_ode(model, x_T, steps=20):  with torch.no_grad():    x = x_T    for t in reversed(range(steps)):      eps = model(x, t)      x = heun_update(x, eps, t)
# PyTorch: prompt conditioning alignmentclass PromptAlign(nn.Module):  def __init__(self, embed_dim):    super().__init__()    self.align_map = nn.Linear(embed_dim, embed_dim)  def forward(self, prompt_embed):    return self.align_map(prompt_embed)

Moment 08 / 09

Open Research Questions and Variations

Today we survey open research questions and experimental variations in diffusion modeling, where score-based generative methods remain an active frontier.

We begin with challenges in extending diffusion to multimodal generation and editing, where conditioning must couple heterogeneous modalities through a shared latent or cross-attention interface.

Key difficulties include modeling joint distributions over images and text, and achieving localized edits that preserve global consistency and sample fidelity under classifier-free guidance.

Next, the quality-versus-latency trade-off: reducing the number of function evaluations via distillation, consistency models, or better ODE solvers remains central to practical deployment.

Theoretical directions include sharper analyses of score estimation error, refined noise schedules such as cosine or learned variance, and hierarchical or latent-space architectures that improve expressiveness.

These variations, from latent diffusion to flow matching formulations, define the current research frontier, driven by reproducible community benchmarks and open ablations.

Together these questions underscore that score-based generative modeling is a maturing yet still rapidly evolving discipline, moving toward broader applicability and provable efficiency.

Equations, code and original cards

Open Research Questions and Variations

Open problems and experimental variations in score-based diffusion mathematics and modeling.

Key Open Questions

• Multimodal generation and editing under cross-attention conditioning
• Joint score estimation across heterogeneous domains

• Quality–latency trade-off: NFE reduction via distillation and ODE solvers
• Balancing sample fidelity against inference cost

Research Directions & Variations

• Score estimation theory: error bounds and convergence
• Cosine and learned noise schedules; hierarchical and latent architectures
• Flow matching and consistency-model variants from community ablations

\mathrm{d} \mathbf{x} = f(\mathbf{x}, t)\mathrm{d}t + g(t) \mathrm{d}\mathbf{w}_t
\nabla_{\mathbf{x}} \log p_t (\mathbf{x}) \approx s_{\theta}(\mathbf{x}, t)

Python & PyTorch Code Snippets (2026)

import torch

from torch import nn



class ScoreModel(nn.Module):

    def forward(self, x, t):

        # Estimate score function

        pass



def diffusion_loss(model, x_0, t):

    # Variance-preserving SDE loss

    noise = torch.randn_like(x_0)

    x_t = sqrt_alpha(t) * x_0 + sqrt_beta(t) * noise

    score = model(x_t, t)

    return ((score + noise / sqrt_beta(t)) ** 2).mean()

Moment 09 / 09

Quiz: Conceptual and Computational Mastery Check

Time to test your command of the diffusion framework: the forward noising process, the learned reverse dynamics, and the variational objective connecting them. Work each problem independently before looking at any solution.

After you submit, we will walk through the results together, paying particular attention to where the score-matching intuition and the noise-schedule arithmetic tend to break down. Good luck.

Equations, code and original cards

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

0 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.