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

VAE + DiffusionUnderstand the moving parts.

VAE compression, Stable Diffusion denoising, CLIP text conditioning.

Suggested preparation: 05, 23

WORKBENCH / CHANGE ONE THING

Mix signal with Gaussian noise

Change cumulative signal retention and inspect signal and noise 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

Mix a clear signal with noise; learning to remove noise is a separate process.

Where this deserves more time

ELBO signs; reparameterization; forward corruption versus learned reverse sampling.

Open the complete high-school reading

Moment 01 / 10

Course Introduction and Objectives

Welcome to the course on Variational Autoencoders and diffusion models, the probabilistic generative frameworks underpinning contemporary large-scale image synthesis.

We will develop VAEs and diffusion models from first principles: the evidence lower bound, reparameterization, forward noising, and the reverse denoising process, then study their composition.

Our central case study is latent diffusion: a VAE compresses images into a lower-dimensional latent space, a diffusion model denoises there, and CLIP supplies text conditioning.

This stack is not a toy: it is the architecture behind Stable Diffusion and most deployed text-to-image systems in research and industry.

Over ten weeks we move from variational inference and score matching through implementation, ending with classifier-free guidance, latent-space diffusion, and modern applications.

By the end you should be able to derive the training objectives, implement both model families, and reason about where each inductive bias helps or fails.

Equations, code and original cards

VAEs and Diffusion: Course Objectives

• Derive VAEs and diffusion from first principles: evidence lower bound, reparameterization, score matching

• Latent diffusion stack: VAE compression, latent-space denoising, CLIP text conditioning

• Connect theory to deployed text-to-image systems such as Stable Diffusion

• Ten-week arc: foundations, implementation, guidance and applications

Duration: 10 weeks • Arc: variational inference and score matching, implementation, then guidance and applications

Moment 02 / 10

Mathematical Foundations of VAEs

We open with the mathematical foundations of Variational Autoencoders, introduced by Kingma and Welling in 2013. The framework treats generation as inference in a latent-variable probabilistic model.

The latent variable z is unobserved; x is the observed data. The encoder defines an approximate posterior q of z given x, while the decoder defines the likelihood p of x given z.

The central object is the Evidence Lower Bound, the ELBO. Because the true posterior is intractable, we maximize this lower bound on the log marginal likelihood of the data instead.

The ELBO decomposes into two terms: an expected reconstruction log likelihood under the encoder distribution, minus the KL divergence between the approximate posterior and the prior.

The reconstruction term rewards faithful decoding of x; the KL term regularizes the posterior toward the prior, shaping a structured, interpolable latent space.

In practice both networks are affine transformations interleaved with nonlinearities, and the reparameterization trick, sampling z as mu plus sigma times epsilon, keeps gradients flowing through the stochastic node.

To summarize: a VAE is a latent-variable model trained by maximizing the ELBO, which trades off reconstruction fidelity against posterior-prior KL divergence. The reparameterization trick makes this objective differentiable end to end, giving us a tractable, amortized approach to deep generative modeling.

Equations, code and original cards

Mathematical Foundations of VAEs

• Latent variable: z (unobserved)

• Observed data: x

• Encoder: q_φ(z|x) — amortized approximate posterior

• Decoder: p_θ(x|z) — generative likelihood

• ELBO objective:

log p_θ(x) ≥ 𝔼q_φ(z|x)[log p_θ(x|z)] − KL(q_φ(z|x) ∥ p(z))

• Maximizing ELBO trains q_φ and p_θ jointly (amortized inference)

• Reconstruction term: expected log likelihood of x under the decoder

• KL divergence: pulls q_φ(z|x) toward the prior p(z)

\mathcal{L}(\theta, \phi; x) = \mathbb{E}_{q_{\phi}(z|x)}[\log p_{\theta}(x|z)] - \mathrm{KL}(q_{\phi}(z|x)\|p(z))

• Affine transforms + nonlinearities; reparameterization trick (z = μ + σ ⊙ ε) enables backpropagation through sampling

Moment 03 / 10

Loss Functions and Gradient Derivations

We now derive the loss functions and gradients of the Variational Autoencoder. The training objective is the evidence lower bound, and we will differentiate its reconstruction and prior-matching terms exactly, then show how the reparameterization trick renders the stochastic encoder amenable to backpropagation.

Start with the ELBO gradients. The bound is an expectation under the approximate posterior q of z given x, so naive differentiation is blocked by the sampling operation; the score-function estimator is unbiased but high-variance, which motivates a pathwise derivative instead.

The slide shows the ELBO: expected log p of x given z, minus the KL divergence from the approximate posterior to the prior. Maximizing it tightens a lower bound on the intractable log p of x.

The reparameterization trick rewrites the sampling step. Rather than drawing z directly from q, we set z equal to mu plus sigma times epsilon, with epsilon standard normal. The randomness is now exogenous and parameter-free, so gradients flow through mu and sigma.

Differentiating through phi now reduces to an expectation over epsilon of the gradient of the ELBO integrand evaluated at mu plus sigma times epsilon. This pathwise derivative is low-variance and plugs directly into backpropagation.

These two pieces, an exact KL in closed form for Gaussian posteriors and a Monte Carlo reconstruction gradient, give an unbiased ELBO estimator trainable with Adam. That is the computational core you will implement.

Equations, code and original cards

ELBO Gradients and the Reparameterization Trick

Differentiate the ELBO terms:

• Reconstruction: \( \nabla \log p_\theta(x|z) \), backpropagated through \( z \)

• Prior matching: \( D_{KL}(q_\phi(z|x) \,\|\, p(z)) \), closed form for Gaussians

\mathcal{L}(\theta, \phi) = \mathbb{E}_{q_{\phi}(z|x)}[\log p_{\theta}(x|z)] - D_{\mathrm{KL}}\big(q_{\phi}(z|x)||p(z)\big)

Reparameterization trick:

• \( z = \mu_\phi(x) + \sigma_\phi(x) \odot \epsilon \), \( \epsilon \sim \mathcal{N}(0,I) \)

• Pathwise gradient: exogenous noise, low variance, unbiased

\nabla_{\phi} \mathbb{E}_{q_{\phi}(z|x)}[f(z)] = \mathbb{E}_{\epsilon \sim \mathcal{N}(0,I)}\left[ \nabla_{\phi} f\big(\mu_{\phi}(x) + \sigma_{\phi}(x) \odot \epsilon\big) \right]

Moment 04 / 10

Stable Diffusion: The Denoising Process

Here is the core mechanism of Stable Diffusion: a fixed forward corruption process paired with a learned reverse denoising process. Understanding this pair, following Ho and colleagues 2020, is the foundation of every modern diffusion model.

The forward process is a fixed Markov chain. At each step we inject Gaussian noise, gradually transforming a clean image into approximate pure noise over capital-T steps.

Formally, q of x-t given x-t-minus-1 is a Gaussian whose mean scales the previous image by the square root of one minus beta-t, with variance beta-t. The beta schedule controls how quickly the signal decays toward noise.

The reverse process is where learning happens. A neural network, typically a U-Net, is trained to predict the injected noise, or equivalently the mean of the previous, less noisy image, step by step.

This is the reverse transition, parameterized by the model's predicted mean and covariance. Sampling from it repeatedly traces a trajectory from pure noise back to a clean image.

The total timestep count capital-T and the variance schedule matter enormously: they set the noise variance at each stage, trading sample quality against the number of network evaluations required.

Finally, Stable Diffusion runs this entire process in the compressed latent space of a pretrained variational autoencoder rather than pixel space, cutting compute dramatically while preserving perceptual quality. That is the latent diffusion idea.

Equations, code and original cards

Stable Diffusion: The Denoising Process

• Forward diffusion: progressively add Gaussian noise to images over timesteps

• Reverse diffusion: model denoising as a learned probabilistic process

• Timestep T controls noise level; schedule affects learning and samples quality

• Connects to latent compression in Variational Autoencoders (VAEs)

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 Diffusion: \(q(\mathbf{x}_t \mid \mathbf{x}_{t-1}) = \mathcal{N}(\sqrt{1-\beta_t}\,\mathbf{x}_{t-1},\; \beta_t \mathbf{I})\)

p_{\theta}(\mathbf{x}_{t-1}|\mathbf{x}_t) = \mathcal{N}\Big(\mathbf{x}_{t-1}; \mathbf{\mu}_\theta(\mathbf{x}_t, t), \Sigma_\theta(\mathbf{x}_t, t)\Big)

Reverse Diffusion: \(p_\theta(\mathbf{x}_{t-1} \mid \mathbf{x}_t) = \mathcal{N}(\mu_\theta(\mathbf{x}_t, t),\; \Sigma_\theta(\mathbf{x}_t, t))\)

Moment 05 / 10

Interactive Diffusion Denoising Simulation

Let's explore how noise progressively corrupts an image using the noise level slider.

Now, observe how the diffusion timestep slider controls the reverse denoising process.

Load the preset for intermediate latent representations to inspect how the hidden state evolves across steps, mirroring the latent diffusion setup where denoising runs in a compressed autoencoder space.

Switch presets and vary the noise schedule, linear versus cosine, to see how the corruption rate reshapes both the forward trajectory and the quality of the reverse samples.

Equations, code and original cards

Moment 06 / 10

CLIP Text Conditioning for Controlled Generation

CLIP text conditioning turns a prompt into a control signal for synthesis: CLIP, from Radford and colleagues, maps captions and images into one contrastive embedding space, so semantic similarity becomes geometry we can exploit during generation.

The key object is the joint embedding: the text encoder and image encoder are trained with a contrastive loss, pulling paired prompts and images together while pushing mismatches apart, which gives a shared metric for cross modal alignment.

Formally, the prompt is mapped to a conditioning vector by the CLIP text encoder; think of it as a semantic coordinate, normalized in embedding space, that downstream modules can consume without ever seeing raw words.

That vector is not a label; it is a continuous direction whose cosine neighborhood encodes style, objects, attributes, and relations.

At every reverse diffusion step we condition the denoiser on that vector, usually through cross attention or adaptive normalization, so each noise removal move is biased toward prompt consistent structure.

Probabilistically, the reverse kernel is p theta of x t minus one given x t and c; in DDPM the network predicts epsilon theta of x t, t, and c, so text shifts the Gaussian mean.

The prompt therefore steers the whole trajectory, not just the final pixel readout: early steps set layout and semantics, late steps refine texture, and guidance scale trades fidelity against diversity.

So the pipeline is: contrastive CLIP aligns language and vision, the text encoder produces a conditioning vector, the conditional denoiser injects it at every reverse step, and sampling converts that bias into controlled images with editable semantics.

Equations, code and original cards

CLIP Text Conditioning for Controlled Diffusion

1. Contrastive Joint Embedding

• CLIP (Radford et al. 2021): paired text/image encoders, InfoNCE alignment

• Shared metric: cosine proximity approximates semantic match

2. Prompt as Conditioning Vector

• c = CLIP text encoder(p); normalized semantic coordinate

• Injected via cross-attention or AdaLN, not as a class label

c = E_{text}(p)

3. Conditional Reverse Diffusion

• p_theta(x_{t-1} | x_t, c); denoiser predicts epsilon_theta(x_t, t, c)

• Guidance scale trades prompt fidelity for sample diversity

x_{t-1} \sim p_{\theta}(x_{t-1}|x_t, c)

4. Trajectory-Level Prompt Control

• Early steps: layout and semantics; late steps: texture detail

• Enables controlled synthesis, editing, and prompt-term ablation

Moment 07 / 10

Python/PyTorch Implementation Details

Let's examine the PyTorch implementation of our variational autoencoder and diffusion pipeline, mapping each theoretical component to executable code and tracing how gradients flow through training and sampling.

First, the encoder and decoder architectures. These networks parameterize the approximate posterior q of z given x and the likelihood p of x given z, the two halves of the evidence lower bound.

Here is the Encoder class, subclassing nn.Module. Two strided convolutions downsample the input, and the final linear layer outputs twice the latent dimensionality: the mean and log variance of a diagonal Gaussian posterior.

Next, the reparameterization trick, the technique that makes stochastic latent variables differentiable, introduced by Kingma and Welling in 2013.

The function samples z as mu plus epsilon times sigma, with epsilon drawn from a standard normal. The randomness enters through epsilon, which carries no gradient, so mu and sigma receive clean backpropagation signal.

Now the forward diffusion process. We corrupt data with Gaussian noise over a fixed schedule of timesteps, following Ho et al. 2020, and train the network to invert each step.

This code defines a linear beta schedule from ten to the minus four to zero point zero two across one thousand steps, then computes the cumulative product of alphas, which lets us sample x at any timestep in closed form.

Finally, CLIP embeddings condition the model during sampling. These joint image-text representations from Radford et al. supply the semantic signal that steers generation toward a prompt.

This snippet loads the pretrained CLIP model under torch.no_grad, encodes the tokenized prompt once, and injects the embedding into each denoising step via cross-attention conditioning.

Together these components bridge theory and practice: a differentiable ELBO for the VAE, a closed-form forward process for diffusion, and frozen CLIP conditioning for controllable generation.

Equations, code and original cards

Python/PyTorch Implementation Details

• Encoder and Decoder Architectures

class Encoder(nn.Module):

    def __init__(self, latent_dim):

        super().__init__()

        self.net = nn.Sequential(

            nn.Conv2d(3, 64, 4, 2, 1), nn.ReLU(),  # 64 x 32 x 32

            nn.Conv2d(64, 128, 4, 2, 1), nn.ReLU(), # 128 x 16 x 16

            nn.Flatten(),

            nn.Linear(128 * 16 * 16, 2 * latent_dim) # output mu and logvar

        )class Decoder(nn.Module):

    def __init__(self, latent_dim):

        super().__init__()

        self.net = nn.Sequential(

            nn.Linear(latent_dim, 128 * 16 * 16),

            nn.Unflatten(1, (128, 16, 16)),

            nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.ReLU(),

            nn.ConvTranspose2d(64, 3, 4, 2, 1), nn.Sigmoid()

        )

• Reparameterization Trick

def reparameterize(mu, logvar):

    std = torch.exp(0.5 * logvar)

    eps = torch.randn_like(std)

    return mu + eps * std

• Diffusion Noise & Scheduling

beta = torch.linspace(1e-4, 0.02, steps=1000)

alpha = 1 - beta

alpha_cumprod = torch.cumprod(alpha, dim=0)

• CLIP Embeddings and Conditioning

clip_model = CLIPModel.from_pretrained(...).eval()

with torch.no_grad():

    embeds = clip_model.encode_text(tokenized_prompt)# Use embeds as conditioning during sampling step

Moment 08 / 10

Advanced Techniques and Optimizations (2024-2026)

Let's examine the advanced techniques shaping diffusion and VAE systems from 2024 through 2026: scaling laws, learned latent sampling, alignment via preference optimization, and hardware-aware inference.

First, model scaling. Following Kaplan and colleagues, and the compute-optimal analysis of Hoffmann's Chinchilla work, we can predict loss as a function of parameters and data, letting us allocate FLOPs precisely rather than by trial and error.

Here the scaling law takes a power-law form: loss L of model size m equals alpha times m to the beta, with beta negative. This lets us forecast gains and avoid wasting capacity on under-trained large models.

Next, efficient latent sampling. Rather than brute-force search, we amortize inference with a learned encoder that approximates the true posterior, trading a small KL penalty for orders-of-magnitude faster generation.

This is the amortized posterior: q-phi of z given x, optimized against the prior by the KL term in the evidence lower bound. Mastering this trade-off is the key to compression with faithful reconstructions.

Next, alignment. RLHF, as in Ouyang's InstructGPT, and its closed-form successor DPO from Rafailov and colleagues, steer generation toward human preferences and safety constraints without hand-crafted reward hacking.

Finally, inference optimization for real-time deployment: mixed-precision compute, distillation into few-step samplers, and hardware-aware parallelism cut latency while holding perceptual quality essentially fixed.

These hardware-aware schedules exploit tensor-core throughput and memory bandwidth directly, which becomes the binding constraint once models move from the lab to production serving.

In summary, we covered scaling laws, amortized latent inference, preference-based alignment, and systems-level optimization. Together these define the frontier of efficient, controllable generative modeling.

Equations, code and original cards

Advanced Techniques and Optimizations (2024-2026)

• Compute-optimal scaling laws and parameter-data trade-offs

• Amortized latent sampling and ELBO-driven compression

• Preference alignment: RLHF and DPO for controlled generation

• Few-step distillation and hardware-aware inference

Model Scaling & Trade-offs

L(m) = \alpha m^{\beta} \quad \text{(Performance scaling law)}

Latent Space Sampling

z \sim q_{\phi}(z|x) \quad \text{with efficient compression}

Alignment Strategies

• RLHF (Ouyang et al. 2022) and DPO (Rafailov et al.)

• Controlled generation via fine-tuned latent priors

Inference Optimization

• Mixed-precision computation

• Hardware-aware parallelism and batching

Moment 09 / 10

Open Research Questions and Variations

We close with open problems in variational autoencoders and diffusion models: the questions are not cosmetic, they concern latent geometry, objective design, robustness, and whether representations mean anything at all.

First, replace the standard normal prior with structured alternatives: mixture latents, discrete codes, or normalizing flows in the sense of Rezende and Mohamed, so the posterior need not hide multimodality.

Second, hybridize: diffusion supplies stable likelihood training, adversarial losses sharpen samples, and flows give exact density; the research problem is trading bias, variance, coverage, and sampling latency deliberately.

Third, robustness is empirical, not decorative: since Szegedy and Goodfellow, small perturbations can flip semantics, so evaluate attacks, adversarial purification, certified bounds, and likelihood behavior under distribution shift.

Fourth, interpretability remains unresolved: disentanglement after Higgins is fragile, so probe latent directions, test causal interventions, and connect units to concepts rather than trusting pretty traversals in practice.

The common thread is principled uncertainty: which prior, which divergence, which inductive bias, which failure metric. Progress will come from ablations that isolate mechanisms, not from larger checkpoints alone, and from honest negative results.

Equations, code and original cards

Open Problems in Deep Latent-Variable Generative Modeling

• Non-Gaussian and structured priors: mixture, discrete, flow-based latents

• Hybrids: diffusion with adversarial or flow objectives; consistency and distillation

• Robustness: adversarial purification, certified bounds, shift-aware likelihood

• Interpretability: disentanglement, concept probes, causal latent interventions

Moment 10 / 10

Challenging Quiz on VAEs and Diffusion

Now probe your grasp of the evidence lower bound, reparameterization, posterior collapse, and the DDPM forward and reverse kernels. Work each item independently before submission.

After submission, we will audit errors against the variational bound and noise schedule, then isolate the failure modes worth revisiting.

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.