Skip to main content
Unsupervised Deep Learning

Diffusion Models and Energy-Based Models

Published: 2026-08-25
Level: postgraduate
Audience: Postgraduate students in machine learning and deep learning

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • Diffusion models — noising forward and learning to undo — covered in Lecture 13
  • Variational autoencoders and the ELBO view — covered in Lecture 1 and previewed in Lecture 4
  • Convolutional autoencoders and transposed convolutions — covered in Lectures 3 and 4
  • Generative adversarial networks — covered in Lecture 1 and extended in Lecture 13
  • Conditional generation with class or text information — covered in Lecture 13
  • Energy ideas borrowed from statistical mechanics — covered in Lecture 1

Generative models try to learn how training data is distributed so we can draw new samples from that distribution. Think of the training data as a set of footprints on a beach: a generative model studies the footprints until it can produce new footprints indistinguishable from the real ones.

This session finishes the diffusion story started previously and adds its fast variant, DDIM (Denoising Diffusion Implicit Model). It also compares all the generative families seen so far — GANs, VAEs, and diffusion — on speed, diversity, and quality. Then it opens a brand-new family: energy-based models, which define probabilities from first principles using an energy function borrowed from statistical physics.

The road ahead:

  1. A quick recap of the forward diffusion process and its closed-form shortcut.
  2. The reverse denoising process — what we train, and why it is tractable only with help from the data point itself.
  3. The training objective, seen as a hierarchical VAE, collapsing to one beautifully simple loss: predict the noise that was added.
  4. The U-Net architecture that plays the role of noise predictor, and how time information enters it.
  5. How generation quality is scored (FID and IS).
  6. DDIM — same training, faster sampling through data prediction and step-skipping.
  7. A side-by-side comparison of VAE, diffusion, and GAN pipelines, including the generative trilemma.
  8. Conditional generation (text-to-image) and latent diffusion (Stable Diffusion).
  9. Energy-based models: what makes a valid density, how the energy formulation works, why comparing beats evaluating, the Ising model, and product of experts.

14.1 Forward Diffusion Recap

14.1.1 Adding Noise Step by Step

Hook: What if the easiest way to learn how to create images was to first learn how to destroy them — one tiny splash of noise at a time?

Start from a training sample . The forward diffusion process adds a small amount of Gaussian noise again and again: add noise to to get , add noise to to get , and so on. After enough steps the signal is gone and only noise remains, so the process ends at a standard normal distribution.

The wider goal behind this is generative modeling itself. We want to estimate , the probability of the data. Everything in this course builds different tools for modeling that probability — GANs, VAEs, flows — and diffusion is one more such tool.

Intuition. Picture a drop of ink in a glass of water. Stir gently once: the ink spreads a little but the blob is still visible. Stir again and again: eventually every trace of where the drop landed is gone and the water looks uniformly mixed. Diffusion does exactly this to an image — each stirring step is a small noise addition, and after enough stirs the original picture is unrecoverable. The analogy breaks only in one useful way: unlike ink, we will be able to compute exactly how much signal survives at any step, in closed form.

One noisy step mixes the previous state with fresh noise. Written per step:

Here is the random noise vector drawn at step , with the same shape as the data (for a color image of height and width , it is a tensor of shape ). The scalar is the noise variance at step , chosen by us before training starts; the collection is called the noise schedule. Define the retention factor : the fraction of the old signal that survives each step. Because appears at every step, it helps to give its running product a name: the cumulative product

Since every factor satisfies , the product shrinks toward zero as grows.

This looks like a recursion that walks , but because Gaussian noise added to Gaussian noise stays Gaussian, the whole chain collapses into one expression in terms of . Here is why, worked out explicitly. Take the first two steps and substitute the first into the second:

A sum of two independent zero-mean Gaussians is itself a zero-mean Gaussian whose variance is the sum of the variances. The combined variance here is . Now check that this is exactly what is missing from full retention: . So the two noise terms fuse into a single equivalent draw :

Reading it aloud: the new sample equals the square root of the cumulative retention coefficient times the original sample, plus the square root of one minus that coefficient times a fresh noise draw. (Notation note: some references write the same equation as using latent-variable names; the content is identical.)

Formalize — the three objects to keep apart:

  • : per-step noise variance (schedule constant, chosen by hand).
  • : per-step retention factor.
  • : cumulative retention after steps.

Every important formula in diffusion is built from these three scalars.

14.1.2 The Closed-Form Distribution

Because the collapsed expression above is a linear function of plus a Gaussian, the conditional distribution of given the original data point is itself Gaussian:

The mean sits at and the covariance comes from . The matrix is the identity covariance matrix, with unit diagonal entries, so it looks like a long row of ones matching the dimension of your image — each pixel gets its own independent share of noise. This distribution is sometimes called the diffusion kernel: given a fixed starting point , it tells you the cloud of possible noisy versions at step .

Worked example. Suppose the schedule is constant with and , and the data is a single pixel . Then , , and the cumulative product is . Jumping straight to step 2 gives mean and variance .

Walking instead: , then . Same mean, and the variance accumulated along the way is . Both routes agree — the jump is exact, not an approximation, because the final answer is mean , variance either way. Sense-check: the variance and less than 1, and the mean shrank toward zero, as expected when the signal keeps being attenuated.

14.1.3 Limit Behavior and the Shortcut

Push very large and the product decays to zero, because you keep multiplying numbers below one. Then the mean term vanishes and:

The signal is destroyed completely; what survives is pure noise with zero mean and unit covariance. Notice the boundary behavior: at there is no noise at all, and at there is no signal at all. Everything between is a smooth blend whose mixing ratio is set by alone.

Visual intuition. Plot time on the horizontal axis and pixel value on the vertical axis. For a single starting point, draw several noisy trajectories: they start together, fan out gradually, drift toward the zero line, and end as an unstructured band around zero. The band's center traces (a decaying curve toward 0) and the band's width traces (a rising curve toward 1). One-sentence takeaway: as time flows left to right, the picture dissolves into noise along a predictable path.

The practical gift is the shortcut: this closed form lets you jump straight to any timestep. You never need to walk through one at a time; you can leap from to any or in one shot. During training this matters enormously — for each training image we pick a random timestep , synthesize in a single line of algebra, and ask the network to denoise it. Without the shortcut, every training example would cost up to sequential noising operations.

Scope: The closed form relies on three assumptions. First, the noise added at each step is Gaussian and independent across steps — that is what lets variances simply add. Second, the process is Markov: each depends only on . Third, the schedule is fixed in advance and the per-step noise must stay small (); if a single step injected huge noise, the reverse step would stop being well-approximated by a Gaussian and everything built later in this lecture would wobble. If any assumption fails — say, correlated noise or a learned schedule that blows up mid-chain — the one-shot jump to is no longer valid and training loses its cheap data augmentation property.

Pitfalls:

  • Mixing up and is the classic trap — even the spoken description in class slid between "alpha" and "alpha bar". Remember: bare belongs to a single step; barred accumulates the product over all steps up to .
  • Treating the noise as a scalar. is a vector (tensor) with the same shape as the image — every pixel gets its own independent noise value.
  • Simulating the chain during training. If you loop to make , you are paying thousands of times more compute than the closed form requires.
  • Forgetting which direction is which. The forward process adds noise and is never learned; it is fixed by the schedule. Learning happens entirely in the reverse direction, covered next.

Recap: Forward diffusion repeatedly blends an image with Gaussian noise; thanks to the closure of Gaussians under addition, the whole chain compresses to one formula , and as the result is pure standard noise.

Bridge: Destruction was easy and needs no learning. The next section asks the hard question: can we run this film backward, from pure noise back to a clean image?

Real-world connection: this forward process doubles as an infinite data augmentation engine. Every training image can be paired with unlimited randomly-noised versions at random timesteps — the same photo becomes thousands of distinct regression targets. That is one reason diffusion training is famously stable compared with GAN training: the network always sees a supervised target (the exact noise added), much like medical-imaging pipelines that train segmentation networks on artificially degraded scans so they learn to restore real ones.

14.2 The Reverse Denoising Process

14.2.1 What We Want to Learn

Hook: Destroying an image took no learning at all — splash noise on it, done. But could we run the film backward: start from static and end up with a photograph no camera ever took?

The reverse process starts at the far end. Draw from the standard Gaussian — remember its dimension matches the image size, or the size of a text embedding, whatever you are generating. Then learn to remove noise step by step. After ample noise removal you should land on an image that looks like it came from the training distribution.

So the object of interest is the reverse transition : given a noisy sample, which slightly cleaner sample produced it?

14.2.2 Intractable Alone, Tractable with the Data Point

Intuition + analogy. Imagine restoring an old, grainy photograph pixel by pixel. If the original photo sits beside you, every restoration step is easy: you know exactly what the clean version should look like, so you can check how much grain to peel off. Take the original away and the same job becomes guesswork — thousands of different originals could plausibly explain the same faded print. The original photo is . With it in hand, denoising is a well-defined problem; without it, it is ambiguous.

Why exactly does removing make things hard? Learning the reverse transition alone stays intractable — no closed form exists without knowing where the data lives. Apply Bayes' rule to the quantity we want:

Every piece on the right involves either the data distribution or the marginal , each computed by averaging over all possible clean images — and we do not know the data distribution; estimating it is the whole problem we started with. So this expression cannot be computed. Knowing fixes it.

Now condition on the data point instead. By Bayes' rule again,

and suddenly every factor is known: is the fixed forward step, and both and are closed-form Gaussians from the previous section. Two Gaussians combined this way produce another Gaussian — so the answer has an exact formula:

A concrete taste of the ambiguity: suppose one pixel starts from or from , with per-step retention . Both starting points produce noisy values centered near and — but with Gaussian spread around them. An observation is entirely consistent with either origin; the conditional distribution therefore mixes two very different humps (one near positive values, one near negative), which is why it is not a clean single Gaussian. Fix , however, and only the first hump survives — a tidy Gaussian remains.

Scope: This "tractable with help" structure holds precisely because the forward process is a Markov chain of small Gaussian steps. The catch: during generation you do not have the original data. That unknown is exactly what the network must fill in, and that is the core of diffusion training. We train a generative model that approximates each reverse step, so that at sampling time the missing data point never has to exist in advance.

14.2.3 Parameterizing the Reverse Chain

Set the starting point of the chain as the fixed prior — chosen deliberately to match where the forward process ends, so the two chains meet cleanly in the middle. Then learn a parameterized reverse transition for every step and multiply the chain:

Reading the notation: (theta) is the collection of all network weights being learned, and abbreviates the whole sequence . Each reverse step is written as a Gaussian whose mean vector and covariance come from a network:

Both quantities are time-varying: they change with and depend on the current noisy sample . Why is a Gaussian a fair approximation for the true reverse step? Because the schedule keeps each small, one denoising move covers only a short distance, and over such short distances the messy multi-modal reverse distribution is close to normal — the same reason a short stretch of any smooth curve looks like a straight line. A deep network takes and and estimates the mean (and variance) so that the likelihood of the data is maximized.

Unrolling the product makes sampling concrete — the procedure called ancestral sampling: draw from the prior, sample from , then , continuing down to the final transition . One full generation costs sequential network evaluations.

Trace on a toy chain (). Suppose we have already trained two tiny networks producing scalar means. Generation runs: (1) draw ; imagine the die gives . (2) Feed and into the network; say it outputs mean with variance ; drawing from that Gaussian yields . (3) Feed and ; output mean with variance ; the final draw gives . Each step nudges the value toward wherever the model believes real data lives — after hundreds of such steps on real images, the endpoint lands on a plausible photo. Sense-check: the trajectory moved from a standard-normal draw toward structured values, and every intermediate number stayed finite and moderate.

Visual intuition. Sketch the line from right to left: at the far right, a wide flat bell (pure noise); each leftward arrow passes through a slightly narrower bell whose center drifts away from zero; at the far left, a narrow bell centered on a realistic image. The learned bells are the transitions; their widths shrink as the process approaches clean data because there is less uncertainty about what the image should be.

Pitfalls:

  • Expecting to learn directly. It cannot even be written down without the data distribution; everything learnable flows through the surrogate .
  • Forgetting the prior must match the forward endpoint. If the forward chain ends at , generation must start from — start anywhere else and the reverse network sees inputs from a region it never trained on.
  • Sharing one unconditioned network across all timesteps. Early denoising (mostly noise) and late denoising (mostly image) are very different jobs; ignoring blurs them together.

Recap: The true reverse step is unknowable alone but computable when conditioned on ; training therefore learns Gaussian transitions that imitate that tractable posterior, and generation walks the learned chain from pure noise down to data.

Bridge: We now have the architecture of learning — but what exactly do we optimize? Next section derives the objective and shows it boils down to matching distributions step by step, just like a VAE.

Real-world connection: ancestral sampling through learned Gaussian steps is the engine behind modern image synthesizers — every image produced by tools like Stable Diffusion is the endpoint of exactly such a chain, evaluated sequentially on a GPU cluster. The same reverse-chain machinery also drives medical image reconstruction, where diffusion priors restore MRI scans from partial measurements by iteratively removing corruption guided by a learned model.

14.3 Training Objective: A Hierarchical VAE View

14.3.1 From Likelihood to KL Divergences

Hook: We know what to learn (reverse denoising steps). But what single number do we descend during training — and can it really be something simple like a squared difference?

Training maximizes the log likelihood of the data. Taking turns the long product of transitions into a sum, which is far easier to optimize. Work the variational bound and everything boils down to minimizing Kullback-Leibler (KL) divergence — a measure of how badly two distributions disagree; it is zero when they match and grows the further apart they sit. Concretely: for each step, the learned reverse transition should match the forward posterior .

The derivation mirrors the VAE bound closely. Recall the VAE. One encoder produced a mean and variance, and a KL term pulled the latent distribution toward a standard Gaussian. You sampled from that Gaussian, the decoder reconstructed the data, and the objective maximized the likelihood of the reconstruction. Diffusion follows the same recipe, applied at every step — so think of it as a hierarchical VAE. Instead of one encoder you stack several. Encoder one learns a mean and variance from the data, encoder two conditions on that output, and so on. Decoding then unwinds hierarchically back to the reconstruction.

VAE piece Diffusion counterpart
Encoder , learned Forward process , fixed by the schedule, never learned
One stochastic layer A stack of stochastic layers
Latent , small dimension Latents , same dimension as the data
Prior on Prior
Decoder reconstructs from Reverse chain strips noise back to

One structural twist matters: in a plain VAE both halves train together, but here the encoder is predetermined — so all learned parameters live in the decoder side, which must do the work of tightening the bound.

14.3.2 The Three ELBO Terms

Expanding the bound splits it into three terms. The spoken structure: the reconstruction piece measures going from to , the prior matching piece compares the fully noised sample against the standard Gaussian, and the remaining pieces form the denoising matching term:

(Index note: the sum runs over — the intermediate steps only. The first reverse move into the data, , is separated out as the reconstruction term, and the last forward step is separated out as the prior matching term.) Walk through the pieces:

  • Reconstruction term. Apply the learned reverse step one last time, , and reward it for rebuilding the data. Higher is better. Like a VAE decoder's final output layer, it turns the almost-clean sample back into pixels.
  • Prior matching term. is known in closed form, and after enough noise additions the signal is lost completely — only noise remains — so this term simply checks that the end of the forward chain agrees with the standard Gaussian . No learned parameters here; with a long enough chain it is essentially zero for free, which is why the design insists on enough steps.
  • Denoising matching term. The sum of KL divergences across intermediate steps. Minimizing it forces each learned denoising transition to imitate the tractable forward posterior. This term is trainable, and it is tractable precisely because has a closed form when is available — and during training, always is available, because we hold the training image in our hands.

Minimizing this average divergence teaches the denoising function that takes and returns . That is the key training idea of diffusion. Learning a good maximizes the likelihood of reconstructed training data, so diffusion sits firmly in the likelihood-maximization family, like the DAE and VAE ideas before it.

Scope: This decomposition holds when the forward process is fixed and Gaussian and is large enough that the prior-matching term vanishes. It also means diffusion only ever optimizes a lower bound on the log likelihood — training pushes the bound up, not necessarily the likelihood itself. If someone asks "is the diffusion likelihood exact?", the honest answer is: only its bound is directly optimized.

14.3.3 The Tractable Posterior and Noise Prediction

Everything now hinges on writing down explicitly. Start from Bayes' rule conditioned on the data:

All three factors are closed-form Gaussians from Section 14.1. Multiplying two Gaussian densities in the same variable produces another Gaussian (complete-the-square), so the posterior is itself a Gaussian with a computable mean and variance:

Its mean blends the original data point and the current noisy sample:

Here is the per-step noise variance and , with the cumulative product defined above. (Notation note: some references write the second numerator as ; since , the forms are identical.) Two sanity checks before moving on. Boundary check: set with the convention — the first coefficient becomes and the second becomes zero, so the posterior mean collapses to itself, exactly right for the step adjacent to clean data. Weight check: the two coefficients stay below one, with the leftover mass absorbed by the posterior variance .

Worked example (, single pixel). Reuse the earlier schedule: , , so , , , . Take and an observed noisy sample .

Step 1 — data weight: .

Step 2 — sample weight: .

Step 3 — blend: .

Step 4 — variance: .

So the model believes the intermediate value was about (one standard deviation ). Sense-check: the answer sits between the noisy observation and the clean value , leaning toward the data — precisely what a sensible halfway denoiser should say. Final answer: .

Rather than predicting the mean directly, the usual move is a noise prediction network. Rewrite the mean so the only unknown is the noise that was added. First solve the forward equation for : from ,

Substitute this into the blended mean above and simplify (using and ):

Every quantity except is known at sampling time, so replace the true noise with a network's guess:

The network , with parameters , predicts the noise at every timestep. You find the best by maximizing the likelihood of the training data through the bound above. Why prefer this parameterization? Because the target — the exact noise that was mixed in — is known perfectly at training time, which converts a distribution-matching problem into plain regression.

14.3.4 The Simple Loss

Because both sides of each KL are Gaussians, the KL between them has a closed form: it reduces to (a constant times) the squared distance between the two means plus constants that do not involve . Substituting the reparameterized mean, those surviving squared distances turn out to be weighted copies of one comparison — actual noise versus predicted noise — and dropping the timestep-dependent weights (an empirical choice that works better in practice) leaves the celebrated simple objective:

Here sums squared differences over every pixel channel — for an color image it is a sum over numbers. That is the whole training signal: draw a noisy sample, ask the network what noise was mixed in, and penalize the squared gap.

Worked example (one pixel). Keep , so and . Draw and true noise . Form the input: . Suppose the network, seeing and , outputs . Then . A lazier network guessing suffers — twenty-five times worse. Gradient descent therefore pushes predictions toward the exact injected noise. Sense-check: perfect prediction would give , and any error shows up squared, punishing big misses hardest.

Pitfalls:

  • Confusing what is predicted. The network never outputs during training; it outputs the noise . The previous-step sample is assembled afterward from schedule constants.
  • Expecting a hard classification target. The target is continuous — this is regression, and the loss surface is smooth, which is why diffusion training is stable.
  • Recomputing by looping. Always use the closed form to build training inputs.
  • Forgetting the conditioning on . The same input value needs different corrections at different steps; a network blind to cannot represent that.

Exam note: Be ready to walk the chain "likelihood → ELBO → three terms → Gaussian KL → squared noise loss". The punchline to remember: the entire diffusion objective collapses to predicting the noise that was added, scored by squared error — and the ELBO's denoising sum runs over intermediate steps only.

Recap + bridge: Training is supervised noise regression; generation will run the same network in reverse. Next question: which architecture should play for images?

Real-world connection: this "predict the corruption" recipe is used far beyond art generation — seismic imaging teams train networks on synthetic noise-corrupted signals to denoise field recordings, and speech-enhancement systems regress the additive noise spectrum of phone calls. Diffusion models industrialized the idea: the corruption is a controlled Gaussian whose exact value is always known, giving unlimited perfectly-labeled regression targets.

14.4 The U-Net Noise Prediction Network

14.4.1 Quick CNN Recap

Which network plays the role of ? The answer is the U-Net architecture, and since not everyone had met it, the session backed up briefly.

Q: Who has already met the U-Net architecture? A: Mostly classmates from the computer vision course recognized it; everyone else asked for a recap, so the baseline CNN picture came first. A CNN takes an image, runs it through convolutional layers with max pooling in between, and ends in fully connected layers. All the convolution filters and the dense head train together. The whole stack then recognizes one label for the entire image.

That is image-level classification. Diffusion needs something else: at every denoising step we must transform an entire image-shaped tensor into another image-shaped tensor — a per-pixel job. A classification head that squashes everything into one label throws away exactly the spatial layout diffusion must preserve.

14.4.2 How U-Net Relates to the Convolutional Autoencoder

A U-Net is built from convolution layers, arranged like a deep convolutional autoencoder. Convolution filters press the input down from a high-dimensional image into a small latent representation. Transposed convolutions (learned upsampling layers that stretch feature maps back by inserting zeros and applying filters) then expand it back to the original size. You can fairly view a U-Net as a special case of that autoencoder family. The goals differ, though:

Dimension Convolutional autoencoder U-Net
Output goal Copy each input pixel (reconstruction) Transform each pixel to meet a condition
Typical target Same image, compressed then rebuilt Per-pixel labels or per-pixel corrections
Success measure Low reconstruction error Correct value at every pixel
Diffusion role Compresses images into latents (latent diffusion, later) Predicts the noise tensor

When to pick which: reach for an autoencoder when you want a compact representation of an image; reach for a U-Net when you want an image-sized answer computed from an image-sized input.

Originally the U-Net was built for biomedical image processing, where the task was segmentation: split an image into groups of pixels. Picture a photo where a cat sits on a sofa. A trained U-Net assigns every cat pixel a cat label, the sofa region a sofa label, and everything else a background label — pixel-level answers rather than one caption for the whole picture. The same "answer at every pixel" property is precisely what noise prediction needs: the noise added to pixel is a number attached to , so the predictor must speak in pixels too.

14.4.3 Down Path, Up Path, and Skip Connections

Shape-wise, an input image is — height , width , and channels for color. The down path applies max pooling or strided convolutions, shrinking spatial size while building a compact representation at the bottleneck. As space shrinks, the number of channels typically grows, trading resolution for semantics. The up path then uses transposed convolutions to grow the map back to full pixel-level resolution while channels shrink again.

Shape trace on a small example. Take a noisy image. Down path: pooling plus convolution steps carry it through , then , reaching a bottleneck near . Up path: each transposed convolution doubles the sides — back to , then — until the output returns to : one predicted noise value per color channel per pixel, exactly the tensor needed for the loss . Sense-check: first spatial dimension in equals last spatial dimension out; only the meaning of each pixel changed.

The signature move is the skip connection: feature maps from the down path are concatenated with the corresponding up-path layers, tying the paired layers together. Each level thereby carries coarse semantic information and fine spatial detail at once. Why is that pairing essential? The bottleneck compresses so hard that fine details (exact edge positions, individual whiskers) cannot survive the trip down and back on their own; the skips give them a shortcut around the squeeze. That is what makes pixel-sharp outputs possible. Attention mechanisms can also be bolted onto the U-Net for extra power, but the core stays fixed: a bundle of ordinary convolution layers plus matching transposed convolutions that transform every pixel.

Intuition: think of the two paths as a summary writer and an editor. The down path writes an increasingly compressed summary of the scene ("a cat on a sofa, warm lighting"); the up path re-expands that summary into full-resolution form. The skip connections hand the editor the original working notes at every paragraph, so no concrete detail gets paraphrased away.

Inside diffusion training, this network estimates . Feed it ; subtract its scaled noise estimate to get ; feed that in again with the next time value; repeat until .

14.4.4 Time Conditioning Through Sinusoidal Embeddings

One requirement is easy to miss: the network must know which denoising step it is on. Early steps face a nearly pure-noise canvas and should make broad structural guesses; late steps face nearly finished images and should fix fine grain. The same input values demand different answers at different times, so time must enter the computation. The fix is to embed the scalar time — a fully connected layer turns, say, into a vector. That embedding goes in as a condition to every block of the U-Net. Next round, the embedding for enters, and so on down to the last step. One shared network serves all timesteps — training and storing thousands of separate networks would be hopeless.

Typically the time representation uses sinusoidal positional embeddings, the same device used to encode position in attention models, as covered in the deep neural networks material. For an embedding vector of width , the values are fixed sines and cosines at geometrically spaced frequencies:

Fast-varying components separate neighboring timesteps; slow-varying ones keep distant timesteps distinct. The embedding rides along with the image through the whole network — usually added to the feature maps at every stage, so every layer can consult the clock.

Pitfalls:

  • Feeding the raw integer instead of an embedding: a single number varying from 1 to 1000 dominates activations and is useless as a conditioning signal compared with a rich vector encoding.
  • Expecting different networks per timestep. The standard design shares one U-Net across all ; only the embedding changes between calls.
  • Confusing U-Net skips with ResNet additions. U-Net skip paths concatenate encoder features onto decoder features; residual connections inside blocks add tensors of the same shape.

Recap: The U-Net is an hourglass-shaped, fully convolutional network whose downsampling path summarizes, whose upsampling path re-expands, and whose skip connections preserve pixel-level detail — ideal for mapping a noisy image to an equally sized noise estimate, with a sinusoidal time embedding telling it how much denoising remains.

Bridge: With architecture and loss fixed, we need scorecards: how do we know generated images are actually good? Two metrics answer that next.

Real-world connection: beyond its original home in cell microscopy segmentation (where it delineated cell boundaries in microscope imagery), the U-Net is now the computational workhorse inside every major diffusion-based image generator — and variants run in medical imaging pipelines for organ contouring in radiotherapy planning, where pixel-exact outputs are a clinical requirement, not a luxury.

14.5 Measuring Generation Quality: FID and IS

14.5.1 Two Scores to Watch

Hook: A generator can pour out ten thousand images that all look like perfect golden retrievers — flawless pictures, zero variety. How would a number catch that failure?

Trained with the squared noise loss, diffusion models reach very low FID scores and reasonably high inception scores. Both metrics appeared already in the GAN material and in your assignments, and they answer different questions.

  • FID (Fréchet Inception Distance): smaller is better. A small FID signals that the output spread is genuinely diverse and is not collapsing onto a few modes — it is not the result of mode collapse.
  • IS (Inception Score): bigger is better. A high IS says the generated images are of high quality and sit close to the images the model trained on.

Keep the pairing in mind when you tune generative systems: one score polices diversity, the other polices fidelity, and a strong model needs both.

How do they work, mechanically? Both lean on a fixed pretrained ImageNet classifier called Inception.

  • Inception Score. Each generated image is classified. Two things should hold at once: each individual image should produce a peaked class distribution — the picture looks confidently like one thing — while averaged over the whole generated set, the class distribution should be flat, meaning every class appears about equally often. The score combines both demands into one number:

where is the number of generated images and . The KL divergence inside is large exactly when per-image predictions are sharp but the overall mix is spread out; exponentiating turns it into a friendlier multiplicative scale.

  • Fréchet Inception Distance. Instead of looking at images one at a time, FID asks whether the cloud of generated images resembles the cloud of real images. Both clouds are passed through Inception, described by their mean vectors and covariance matrices in its feature space, and the distance between the two Gaussians is computed with the closed-form Fréchet distance. If the two clouds overlap well, FID is small; if the generator covers only part of the real cloud (mode collapse) or produces blurry off-manifold points, FID grows.
Property IS FID
Direction Higher is better Lower is better
What it rewards Confident, varied classifications Statistical match to real data in feature space
Mode collapse caught? Only weakly (one good example per class suffices) Yes — collapsed clouds sit far from the real cloud
Needs real reference data? No (uses classifier's label space) Yes (compares against a real-image sample)
Typical reading "Are these nice, recognizable pictures?" "Does this model reproduce the whole data distribution?"

One-sentence rule for choosing: use IS for a quick read on sample recognizability, trust FID when diversity versus the real distribution matters — and report both when you can.

14.5.2 What the Loss Buys You

The ELBO-driven loss pushes the network to reproduce image details faithfully. That is the basic loop of reverse diffusion training: sample something from the standard Gaussian, peel off noise step by step, and drive the process so the likelihood of the denoised, generated data is maximized. Because every training target is a supervised regression problem, nothing in this loop fights back the way an adversarial discriminator does — which is why diffusion models reached state-of-the-art FID numbers without the instability GANs are famous for.

A fair caveat from the metric literature: both scores judge through Inception's eyes. Whatever information the classifier's features discard cannot influence either number, so a model could score well while failing on details Inception never measures. That is why qualitative eyeballing still accompanies every quantitative claim.

Pitfalls:

  • Reversing the directions: FID lower is better; IS higher is better. Mixing these up flips every conclusion.
  • Reading IS as proof of diversity: a model producing one realistic specimen per class can post a high IS while being thoroughly repetitive.
  • Comparing FID across different feature extractors or sample sizes: the numbers are only comparable under matching evaluation setups.

Exam note: Expect a short conceptual question: know which metric rewards diversity (FID, lower is better — it detects mode collapse) and which rewards quality/fidelity (IS, higher is better), and remember diffusion models achieve low FID and high IS thanks to the stable noise-regression loss.

Recap + bridge: We can now certify that the trained denoiser generates good, diverse images. Next: making generation fast — the motivation behind DDIM.

Real-world connection: any team deploying generative models in production tracks FID across releases to catch silent regressions — stock-photo generators, game-asset pipelines, and data-augmentation engines all gate updates on FID not worsening, because a mode-collapsed model quietly shrinks the creative range of everything built on top of it.

14.6 Alternate Parameterization: DDIM

14.6.1 Predicting Data Instead of Noise

Hook: Training taught one network to name the noise inside any corrupted image. If it can do that, can we also make it hand back the clean image hidden underneath — and skip most of the ladder on the way down?

Everything so far predicted noise. An alternate parameterization predicts the original data instead. The training process stays the same — same forward noising, same network, same squared loss on noise — but generation can take a shortcut. Once the network outputs , rearrange the forward equation to recover an estimate of the clean image. Start from the closed form and solve for : subtract the noise term from both sides, then divide by its coefficient:

Because you hold both and the predicted noise, you can compute this estimate at any step — and that unlocks jumping. Instead of marching you can hop . Fewer denoising steps means faster generation. This implicit, stepped variant is the DDIM — Denoising Diffusion Implicit Model. Training is identical for the probabilistic and implicit variants; at generation time DDIM uses data prediction, which also makes the trajectory more deterministic — run the same starting noise twice and you land on essentially the same image, unlike the fully stochastic chain.

Worked example of the recovery step (one pixel). Reuse familiar numbers: , so , . The observed sample is and the network claims . Then

The true starting value was : the estimate lands within using nothing but the noisy sample and the network's noise guess. Sense-check: the answer should sit near plausible pixel values and closer to clean data than was — and it does. Final answer: .

14.6.2 Training Algorithm

This is a loop you could code in an afternoon — which is a large part of why diffusion took over.

Purpose: teach one shared U-Net to name the exact noise mixed into any image at any corruption level. Inputs: training images ; schedule constants (so follow); batch size. Outputs: parameters of the noise predictor .

The procedure, step by step:

  1. Draw a training sample from the dataset.
  2. Pick a timestep uniformly at random from .
  3. Draw Gaussian noise . Treat it as a vector with the same dimension as the image — not a scalar.
  4. Form the noisy sample with the closed form, , and ask the U-Net for its guess .
  5. Minimize over all U-Net parameters .

It really is a regression problem: estimate the exact noise that got mixed in. Cost note: each iteration costs one forward pass, one backward pass, and one closed-form noising — no sequential unrolling, which is why training is cheap relative to sampling.

14.6.3 Sampling Algorithm

Generation runs the loop in reverse:

  1. Sample .
  2. For : prepare a noise vector with image dimension — sample it fresh when ; set at the final step .
  3. Combine the U-Net output with to compute , then repeat with the new sample.
  4. Stop at .

Why zero the last ? The final transition should commit to a single clean image rather than shake the result one more time — after all the refinement, extra randomness would only blur the finish. Notice the rhythm: the U-Net consumes , emits a noise estimate, that estimate plus produces , and the same trained U-Net runs again on the cleaner input, all the way down.

With the DDIM variant, the same skeleton runs over a sub-sequence of timesteps (the hop list above), each update built from the recovered ; because updates are deterministic, large hops stay accurate enough to keep quality high while cutting the number of U-Net calls by an order of magnitude or more.

Trace of two sampling rounds (, toy scalars). Start: draw from the standard normal. Round 1 (): the network sees and outputs ; with giving , suppose the update yields . Round 2 (): network outputs ; fresh gives . Final round (): is forced to ; the network outputs and the update commits to — the finished "image". Every number stayed moderate and drifted away from pure-noise scale toward data scale, exactly as intended.

14.6.4 The Speed Trade-Off

Honesty demands acknowledging the weakness: image generation with diffusion is slow. Anyone who has asked a chatbot to edit an uploaded image has felt the wait, because such tools lean on diffusion-like incremental refinement. The vanilla formulation is nearly a Markov chain — each removal depends on the immediately preceding step, so means a thousand sequential passes through a heavy network, and sequential passes cannot be parallelized across time. DDIM softens this by skipping steps, but iteration remains inherent. One-shot generators do not pay this cost — more on that in a moment.

Scope and pitfalls:

  • Aggressive skipping degrades quality. Hop lists are tuned; jumping too far assumes trajectories are straighter than they are, producing artifacts.
  • Sampling cost scales with steps × network size. A bigger U-Net multiplies every one of those sequential calls.
  • Do not confuse parameterization with training change. DDIM trains identically; only the sampling rule changes. An exam answer claiming "DDIM uses a different loss" is wrong.

Recap: Same training, smarter decoding: by recovering a clean-image estimate from any noisy sample, DDIM turns denoising into deterministic leaps over a sub-sequence of timesteps — trading a little stochasticity for a large speedup.

Bridge: Speed is one corner of a triangle of desiderata. Next we line up VAEs, GANs, and diffusion against all three corners at once.

Real-world connection: every consumer tool that edits an uploaded photo through a chatbot feels this trade-off directly — the wait you experience is a stack of sequential denoising calls on a server GPU. Engineering teams ship DDIM-style samplers precisely because cutting 1000 calls to 20–50 turns seconds-long waits into something interactive.

14.7 Comparing the Generative Families

14.7.1 VAE Pipeline

Hook: Three families, three philosophies of turning randomness into images. Before ranking them, hold each pipeline in your head as a two-minute story.

Given data, the encoder learns a latent distribution; minimizing KL divergence keeps that distribution close to a standard Gaussian. Sampling then draws

— the learned mean plus the learned standard deviation times a noise draw ; the symbol is elementwise multiplication and the resulting lives in a compact latent space you chose at design time. The decoder maps to a reconstruction . Training maximizes the likelihood of the reconstruction while the KL term holds the latent space well-behaved — every region decodes into something plausible, so any fresh draw is usable.

14.7.2 Diffusion Pipeline

Start from data , add noise repeatedly until reaching total noise — a Gaussian. Then learn the reverse process: a noise prediction network trained by likelihood-based fitting, so that whatever it finally spits out has maximal data probability. Sampling begins at a draw from the normal distribution, and because each run draws a different sample, applying noise reduction to different draws yields different outcomes. The defining structural fact: that starting draw has the same dimension as the image itself — nothing is compressed anywhere along the way.

14.7.3 GAN Pipeline

Feed a small random code into the generator; train a discriminator to tell generated samples from training data. Generation happens in one shot: the code passes through a stack of convolution layers and the full image emerges at once. No likelihood, no iterative refinement — just a straight conveyor belt from noise vector to picture.

14.7.4 The Latent-Dimension Question

Then came a question that trips people up — and shows up in interviews:

Q: What separates the three z values used by diffusion, VAE, and GAN? A: They differ in dimension relative to the data. All three are random draws, so randomness is not the distinguishing feature — the viewpoint to adopt is size.

Q: Suppose the data is 128 by 128. What is the dimension of z in each model? A: For the GAN you start from a small code, around or — the familiar generator input. Resize it to something like , and let convolution layers grow it into the full image. Diffusion matches the image size: its noise sample lives at the full resolution, just like a flow model. The VAE uses whatever latent size you chose at design time, and that is typically a much smaller dimension than the original.

Worked example — growing a GAN image from a code. Data target: . Start from a code . Step 1: a dense layer expands the 100 numbers into values, reshaped as a tiny feature map of size with 512 channels. Steps 2–6: five transposed-convolution blocks each double width and height while halving-ish the channels: . Sense-check: spatial sides went by repeated doubling, and the final tensor has exactly image shape. Final answer: a 100-dimensional code becomes a image in six layers — contrast that with diffusion, whose "code" at the same task is already a full tensor of noise.

Q: Which one surprises people? A: Diffusion. Its latent dimension equals the data dimension — only the distribution changes, from data to pure noise — while GAN and VAE codes are compact. Remember this contrast; short interview rounds love it.

The mental model to keep: diffusion never compresses — it only transports the distribution. A GAN squeezes all image variety into a hundred numbers; a VAE squeezes it into a chosen few dozen; diffusion keeps every pixel slot busy at all times and merely moves what fills those slots from "structured picture" to "static" and back.

14.7.5 The Generative Trilemma

Line up the families on three desirable axes — this trio is known as the generative trilemma:

  1. Fast sampling — generate quickly, not sequentially.
  2. Mode coverage — high diversity across outputs.
  3. High sample quality — high inception score, low FID.

No family holds all three:

Family Fast sampling Mode coverage Sample quality Training stability
GAN Yes — one shot through the generator Poor — classic mode collapse High Fragile
VAE Yes — one draw plus decode Decent Plain VAEs struggle on sharp images Stable
Diffusion No — many sequential steps High High (low FID, high IS) Stable

Read row by row: GAN: high-quality samples plus fast sampling, but mode coverage is generally poor — the classic mode collapse problem. VAE: fast sampling (just draw from the learned latent Gaussian and decode) plus decent mode coverage, but plain VAEs struggle to produce high-quality images. Hierarchical VAEs push quality up, and discrete VAEs such as VQ-VAE help when generating class-specific data. Diffusion: great quality and high diversity, but slow sampling — good quality demands many steps.

Add a fourth axis beyond the trilemma: training stability. Diffusion training — learning to remove noise — is a stable, well-behaved optimization. VAE training is stable too. GANs are the fragile ones: getting the loss to descend smoothly, asymptotically, is notoriously difficult there. Stability does not affect the generated output directly; it affects whether the training process behaves while you create the model. That distinction matters in practice: an unstable run may never deliver any output worth scoring, however good its theoretical ceiling.

Pitfalls:

  • Answering "they're all random draws, so they're the same." Randomness is shared; dimension relative to data is the separator.
  • Claiming diffusion compresses images. It does not — latents equal data size; compression belongs to VAE/GAN codes and, separately, to latent diffusion's autoencoder stage covered later.
  • Forgetting stability is about training, not outputs. A stable loss curve does not guarantee beautiful images, and vice versa.

Exam note: Expect assignment-related questions in the final exam, and know the latent-dimension comparison cold — it is a favorite short-interview question. Also be ready to explain which trilemma corner each family gives up and why training stability separates diffusion and VAE from GANs.

Recap + bridge: Each family buys two trilemma corners by sacrificing the third. Diffusion's sacrifice is speed — so the next section attacks speed directly with conditioning tricks and latent spaces.

Real-world connection: production teams pick families by constraint, not fashion — game studios needing thousands of texture variants per second lean on GAN-style one-shot generation despite tuning pain, while advertising pipelines that can wait seconds per asset choose diffusion for its diversity guarantees; VQ-VAE-style discrete latents power token-based generators where class control matters most.

14.8 Conditional Generation and Latent Diffusion

14.8.1 Conditioning on Text

Hook: Unconditional generation is a slot machine — pull the lever, take whatever falls out. How do we steer the machine so it builds the picture we asked for?

Everything above generates unconditionally. For text-to-image generation, encode the text document into an embedding and inject that embedding as a condition into the denoising network at every step — conditional diffusion sampling. Mechanically it mirrors the time signal you already know: just as a sinusoidal vector tells each U-Net block when in the schedule it is working, a text-embedding vector tells each block what is being built. The two vectors travel together through all steps.

Start from several different draws of the same Gaussian with the same prompt and you get different images, because the noise samples themselves differ. The prompt fixes the destination region of the data distribution; the starting noise picks which point inside that region you visit. Same sentence, ten seeds, ten distinct pictures — all matching the words. And since outputs are color images, the process starts from three channels, not one.

Worked example — one prompt, two seeds. Prompt: "a red umbrella on wet asphalt." Encode it into an embedding vector (say ). Run A starts from seed noise : after denoising, the umbrella stands left-of-center with reflections running diagonally. Run B uses the identical prompt but seed : now the umbrella sits right-of-center, shot from a lower angle. Both satisfy the condition because every denoising step was guided by the same ; they differ because every intermediate sample descended from a different initial static pattern. Sense-check: conditioning constrains what appears, randomness chooses which version.

14.8.2 Latent Diffusion and Stable Diffusion

Every diffusion model discussed so far ran on the original image. Latent diffusion, as the name suggests, first encodes the original image into a latent space much smaller than the pixel space. It then runs the entire diffusion process there, and a decoder maps the result back to images. Concretely, a picture on the order of pixels might live in a latent grid on the order of — treat both sizes as illustrative magnitudes rather than exact specifications; the point is that each side shrinks by more than an order of magnitude.

Why does this help so much? Count the work. The pixel image holds about spatial positions; the latent grid holds about . Every convolution sweeps over positions and every self-attention layer compares pairs of positions, so shrinking the grid by tens of times per side slashes computation per step by similar orders — and since generation runs that cost once per timestep, the savings multiply across the whole chain. Doing the whole denoising conversation in that small space therefore cuts computation sharply while improving both generation speed and output quality — an excellent trade-off between performance and computational cost. Quality improves too because the autoencoder has already stripped out imperceptible high-frequency detail, letting the diffusion network spend its capacity on structure that actually matters. The design is also flexible: swap or adjust the autoencoder input to serve different tasks.

Scope: Latent diffusion assumes a good pretrained autoencoder exists for your data type — the diffusion half inherits any blindness or artifacts of its encoder-decoder pair. Fine textures the autoencoder discards cannot be recovered later, so the compression factor must stay moderate. It also adds a second trained component to maintain: train the autoencoder first, freeze it, then run diffusion inside its latents.

Real-world: state-of-the-art text-to-image systems build on this recipe — named examples included DALL-E and Meta's models. Stable Diffusion performs diffusion in the latent space of pretrained autoencoders, cutting computational load significantly without compromising performance — which is why a consumer GPU can run it at home. The same machinery extends to video: generate a sequence of frames from a text prompt, following the exact pattern used for images — a topic reserved for the closing session.

Recap: Two upgrades complete the practical recipe: inject a prompt embedding alongside the timestep to steer generation, and run the whole diffusion process inside a compressed latent space to make it affordable.

Bridge: Diffusion defines probabilities implicitly, through a chain. Next we meet a family that writes probabilities directly from first principles — energy-based models.

Real-world connection: open-source image tools owe their accessibility to latent diffusion — compressing before diffusing is what lets hobbyists synthesize images on laptops instead of data-center clusters, and the same trick now powers on-device photo editors that upscale, inpaint, and restyle pictures without ever uploading them.

14.9 Energy-Based Models: Modeling Probabilities from First Principles

14.9.1 Why Another Family?

Hook: Every generative model so far arrived holding a ready-made shape — Gaussian bells, mixtures of bells, latent codes. What if we refused all prefabricated shapes and built probabilities from bare first principles?

Energy-based models trace back to principles of statistical mechanics — the physics discipline that describes how particle states distribute across energies. The physics stays in the background here; what matters is what the framework offers generative modeling. Every family studied so far estimates probabilities, usually after committing, explicitly or implicitly, to a parametric form: Gaussian models, mixture of Gaussians, and friends. An energy-based model hands you an extremely flexible way of defining probabilities from first principles.

Intuition + analogy. Think of a landscape with hills and valleys scattered freely across a map, and imagine sprinkling sand over it from far above: sand settles thickly in valleys, thinly on peaks, nowhere at all beyond the map's edge. If you now read the sand height at each location as an unnormalized probability, the landscape itself becomes a distribution — no formula template demanded. Energy-based models sculpt exactly such landscapes with neural networks, then convert heights into honest probabilities. Where the analogy strains: real sand piles up in one configuration; probabilities need careful total-mass bookkeeping, which is precisely the next topic.

14.9.2 What Makes a Function a Valid Density?

The doorway question, put to the room:

Q: What two conditions turn any function into a valid PDF? A: A first guess was that being a continuous function qualifies — not enough. Second guess: the total area equals one. Third: the values are nonnegative. Both of the last two are required, and nothing else is. A function is a probability density when its values stay nonnegative over the entire range and the area under the curve equals one; for discrete variables, the masses over all outcomes sum to one.

The continuity guess deserves its moment of respect — it sounds plausible because every density we had met was smooth. But plenty of continuous functions integrate to two, or minus three, or infinity; and plenty of perfectly legal densities have jumps (the uniform density on leaps from 0 to 1 at both ends). Continuity is not required, and having it would not help anyway. The misconception dissolves once you see what probability actually uses about a density: only areas. Negative values would let areas cancel, breaking "probabilities live in ", and a total area other than one breaks the guarantee that some outcome occurs. Nothing else can go wrong — so nothing else is required.

Once only those two rules constrain you, the space of candidate distributions explodes — you are free to consider almost anything.

14.9.3 Manufacturing Valid Densities

Nonnegativity is cheap to guarantee:

  • Square any function: squares cannot go negative.
  • Exponentiate any function: always, whatever sign takes.
  • Take a modulus: absolute values are nonnegative by definition.

Take any nonnegative candidate and divide by its own area to force the second condition:

Here collects the tunable parameters and the denominator — a single positive number, assuming the integral exists and is finite — rescales whatever numerator you chose so the total area becomes exactly one. Verify directly:

This quotient is always a valid density — nonnegative above, unit area below. The catch is feasibility: sampling from it, and even evaluating that integral, may not be doable unless the normalizing constant has a closed form. Classic families earn their place by having one:

  • Gaussian kernel: is always positive, and its integral equals in one dimension — the familiar normalizing constant, which is why a proper Gaussian carries the factor out front.
  • Exponential distribution: (antiderivative , which vanishes at and equals at 0), so the normalized density on integrates to one.

Worked example — build a density from scratch. Choose the arbitrary function on the range and zero elsewhere. Step 1 — nonnegativity: everywhere. Step 2 — find the area: . Step 3 — normalize: for . Check the area: . Bonus check — a sub-interval probability: . Sense-check: values near 3 dominate the mass, so the region below half the range should hold little probability — and 0.125 confirms it. Final answer: on , a perfectly valid density manufactured from an arbitrary polynomial.

Any parameterized family whose area can be integrated analytically into a constant works as a generative family. You can also chain several valid densities together to sculpt more complex ones, provided each ingredient individually satisfies the two rules. And once a density is parameterized, the likelihood principle applies — fit by maximizing likelihood as always.

14.9.4 The Extra Condition for Generation

Using a density as a generative model adds one demand beyond the two validity rules: sampling from it should be simple. A perfectly valid density you cannot draw from is useless for synthesis — knowing the exact shape of a mountain range is worthless if you cannot throw a dart that lands somewhere on it in proportion to sand depth. Extreme flexibility plus easy sampling — that combination is the whole promise of energy-based models.

Scope: The normalization quotient demands a finite, strictly positive denominator: if diverges or equals zero, no density results. On unbounded ranges, growth of matters — polynomials like diverge on but behave perfectly on bounded ranges, while exponentially decaying choices stay integrable everywhere. When the analytic constant is unavailable, evaluation and fitting need approximations — the very difficulty energy-based methods are named for confronting.

Pitfalls:

  • Requiring continuity — the classroom's first guess. Jumps are allowed; only nonnegativity and unit area matter.
  • Normalizing over the wrong range. needs different constants on versus ; always recompute the area for the support you actually use.
  • Conflating "can evaluate" with "can sample". They are separate abilities, and generation needs the second.

Recap: Two rules — nonnegative values, total area one — admit nearly any function as a density; dividing any nonnegative candidate by its own area manufactures validity on demand. The open problem is doing arithmetic with the resulting object: evaluating its constant and drawing samples from it.

Bridge: Energy-based models accept that challenge head-on with one elegant construction. Next section writes down their canonical form.

Real-world connection: this normalize-by-the-area trick underlies density estimation in anomaly monitoring — industrial inspection systems score sensor readings under flexible learned densities where no Gaussian assumption fits, and the same two-rules-first mindset governs how Bayesian statisticians define priors on unusual parameters like correlation matrices.

14.10 The Energy-Based Model Formulation

14.10.1 Definition, Partition Function, Energy

Hook: Take any function that scores inputs — higher means more plausible. One mathematical wrapper turns it into an honest probability distribution. What could that wrapper be?

The energy-based form wraps any scored function into a probability:

Here are the learnable parameters, is the scorer (any real-valued function of the input), and is a scalar normalizing constant; it guarantees stays between 0 and 1. The numerator alone only promises positivity — exponentials never go negative — so this is exactly the two-rules recipe of the previous section, with exponentiation supplying rule one and division by supplying rule two.

is none other than the partition function from statistical physics. There it tracks how particle states distribute over energies. The negated scorer carries a special name: the energy, written . In that language the same law reads : low-energy configurations are common, high-energy ones rare. The reading is intuitive: configurations with low energy — meaning high — are more likely, since the probability grows exactly when is large. Push the intuition to the extremes: if one configuration hoards all the probability, you get a fully deterministic outcome — its probability one, everything else zero; if outcomes share equally, each carries probability . Working with log probability is natural here because the logarithm shrinks the range of very large numbers to a manageable scale — taking logs turns into , where products became sums.

14.10.2 Strengths and Difficulties

The strength: extreme flexibility — pretty much any function you like, including an arbitrary neural network. No invertibility constraints like flows, no Gaussian shapes like classic density estimation. The difficulties come in threes:

  1. Sampling is hard. Easy only when the integral admits an analytic solution — otherwise drawing samples from requires iterative approximation schemes.
  2. Evaluating and optimizing the likelihood is hard, because computing numerically scales exponentially with dimension. For a discrete variable with binary pixels there are states to sum over: at , that is already about terms — no computer enumerates them. With images — hundreds of dimensions, even into the thousands, and truly huge at 4K scale — that integral becomes hopeless.
  3. Feature learning is limited, though adding latent variables can help.

Hold those two hard problems down and you gain a versatile tool able to model very complex data reasonably well.

Worked example — three toy states. Let the input have three possible values with scores , , . Step 1 — exponentiate: , , . Step 2 — partition function: . Step 3 — normalize: , , . Sense-check: the three probabilities sum to and each lies in . Final answer: the score gap of 4 between and becomes a likelihood ratio of — small score differences amplify dramatically through the exponential.

14.10.3 Compare, Do Not Evaluate

Here is the escape hatch. The partition function is a constant — the same constant — inside two probabilities you want to compare, so it cancels:

No anywhere. Individual probabilities may be out of reach, yet ranking two candidates costs almost nothing — just evaluate the scorer twice and subtract. Many practical tasks need exactly that — comparison rather than evaluation — and those tasks can use energy-based models directly.

A first-semester memory proves the pattern:

Q: Which basic machine learning model decided classes by comparing probabilities without ever evaluating them? A: Naive Bayes. Given some attributes, you ask whether an object belongs to class one or class two. The posterior for each class is proportional to a product of terms, and the denominator — the joint probability of the attributes — never gets computed. Whichever class gives the larger proportional value wins the object. The shared, hard-to-evaluate evidence term drops out exactly the way does here.

Notice how deep the parallel runs: Naive Bayes' skipped denominator is a sum over all attribute combinations — a partition function in disguise. You have been exploiting cancellation since your first classifier.

14.10.4 Tasks Built on Comparison

Real-world: anomaly detection — compare the probability a trained model assigns to a real sample against a test sample. If the ratio lands much greater than one, the test point is an anomaly. A ratio near one (or lower) says the test point behaves like genuine data.

Worked example — the anomaly decision rule. A model trained on healthy machine vibrations gives a typical recording score ; a suspect recording scores . The ratio is — vastly greater than one, so flag the suspect as anomalous. A second suspect recording scores : the ratio is , near one, so treat it as genuine. Sense-check: the verdict depends only on score gaps, never on absolute probabilities — which is fortunate, because those absolutes were never computable.

Real-world: object recognition and classification — given five candidate classes, compare the joint probability of the image with each class hypothesis: cat, dog, and so on. Assign the winning label; no absolute probability required. The same comparison pattern serves sequence labeling, part-of-speech tagging (does this word belong to this tag?), and image retrieval with a trained model. Wherever relative rankings suffice, energy-based models fit.

Pitfalls:

  • Insisting on computing before using the model. For comparison tasks the constant never matters — skip it by construction.
  • Forgetting the exponential amplifies gaps. A modest raw-score difference of 3 is a twentyfold likelihood ratio; calibrate thresholds on ratios, not raw differences, when interpreting strength of evidence.
  • Assuming sampling difficulty equals evaluation difficulty. They fail for different reasons: sampling needs the shape of the whole landscape; evaluation needs one intractable number.

Exam note: Remember the trio of difficulties (sampling, likelihood via exponentially-expensive , limited feature learning) and the escape hatch: ratios cancel the partition function, exactly as Naive Bayes cancels its evidence term.

Recap + bridge: Energy-based models define flexible distributions whose arithmetic is blocked by one intractable constant — and most useful tasks need only comparisons, which survive the block. Next: the oldest concrete instantiation, the Ising model.

Real-world connection: fraud and intrusion detection systems run this exact playbook — a model scores transactions or network events, and alerts fire whenever a new event's relative score collapses against the typical band; nobody ever needs the absolute probability, only the damning gap.

14.11 The Ising Model

14.11.1 Setup: Recovering Corrupted Binary Images

Hook: Before neural networks touched images, physicists studying magnets left us a model that still restores corrupted pictures today. It needs only pixels that are black or white.

Among the earliest energy-based models stands the Ising model. It handles deliberately simple data: a 3 by 3 patch of an image whose pixels hold only zeros and ones — no 8-bit gray levels. Imagine the true patch (the clean pixels) and a corrupted observation , degraded perhaps by the camera that captured it. The task: recover the true pixels from the corrupted ones using the energy-based machinery.

Two structural assumptions drive the model:

  1. Local corruption. The observed value at pixel depends only on the true value at that same pixel — no cross-pixel corruption coupling. Noise flips pixels independently.
  2. Neighborhood agreement. Neighboring true pixels tend to share values, because correlation in a physical scene runs high — colors rarely change abruptly except at edges, so nearby values stay close.

The second assumption carries real content: it says clean images occupy a smooth corner of all possible patches. A patch of pure noise violates neighborhood agreement everywhere; a photo of a wall satisfies it almost everywhere. That prior belief is what lets the model outvote a corrupted pixel using its neighbors' testimony.

14.11.2 Energy Form and Recovery

Write the joint probability of true and observed pixels as an exponential of summed interaction terms:

Here runs over all pixel sites and each ordered neighbor pair contributes once. The function is a potential — a score table assigning points to value combinations. The first sum encodes observation-versus-truth at every site : reward when the reconstruction matches what the camera saw. The second rewards agreeing neighbors. No three-way or global terms appear — every factor touches either one site's truth-versus-observation or one pair of neighboring truths, which is precisely the "no cross terms" structure of the classical model. Because everything lives inside an exponential of sums, this is an energy-based distribution of exactly the Section 14.10 form, with the energy gathering penalty terms from mismatches and disagreements.

Recovery then asks for the most probable truth: maximize . Since the observation is fixed during restoration, , and dividing by the constant cannot reorder candidates — so equivalently maximize the joint , choosing suitable potential functions along the way. Notice the partition-function escape hatch at work: the normalizing constant never enters the argument, because argmax ignores constants. Solving that maximization returns the restored image values.

Worked example — three pixels in a row. Take a 1D strip with sites 1–2–3, observed values — suppose the middle reading is corrupted. Potentials: when the reconstruction matches the observation at site , else 0; for each adjacent pair that agrees, else 0. Score every candidate by :

Candidate Matches Agreeing pairs Total
3 0 3 20.1
2 2 6 403.4
1 2 5 148.4
2 1 4 54.6
2 1 4 54.6
1 1 3 20.1
1 1 3 20.1
1 0 1 2.7

The winner is : flipping the suspicious middle zero costs one point of data agreement but gains two points from each newly agreeing neighbor pair — net gain three. Sense-check: an isolated odd pixel surrounded by agreement is more plausibly corruption than structure, and the arithmetic agrees. Final answer: restore . Had the middle observation been backed by its own agreeing companions, the data terms would have won instead — the model weighs evidence, never blindly smooths.

Pitfalls:

  • Forgetting that -terms are fixed at recovery time. Only varies; terms involving only would be constants.
  • Setting smoothing too strong. If neighbor agreement dominates data evidence, genuine edges get erased — thin structures (a one-pixel line) look like noise to the smoother.
  • Assuming the joint must be normalized before optimizing. Constants cancel in argmax; normalization matters only when you want actual probability values.

Recap: The Ising model packs two intuitions — observations reflect their own pixel's truth, and neighbors agree — into an exponential family over binary patches; restoration means finding the highest-scoring configuration, with all normalizing constants irrelevant to the search.

Bridge: One expert scored our patch here. What if several independent experts each scored the same input, and we multiplied their opinions? That construction comes next.

Real-world connection: the same pairwise-potential machinery powers Markov random field methods used in medical image denoising and satellite imagery cleanup — restoring binary land-cover maps where sensor dropouts must be repaired without erasing real field boundaries — and, historically, it modeled ferromagnetism, where atomic spins align with neighbors exactly like agreeing pixels.

14.12 Product of Experts

14.12.1 Many Experts, One Probability

Hook: A committee where every member holds veto power behaves very differently from one where the majority rules. Multiplying probabilities builds the veto committee — and that turns out to be exactly what controllable generation needs.

Suppose you have trained several scoring models — call them , , . They can be anything: a flow model, a PixelCNN, even a nondifferentiable scorer. Treat each one as an expert that independently judges how likely an input is. The product of experts multiplies their judgments and normalizes:

Here indexes the experts, is once again a normalizing constant, and each is an unnormalized opinion score.

Two views make the construction transparent. In log space, taking logs turns the multiplication into addition:

So a product of experts is itself an energy-based model whose total energy is the sum of the individual expert energies — every expert adds its own penalty terms, and bad news accumulates additively. In set-theory language, multiplying densities carves out the intersection of what the experts consider plausible; each new expert shrinks the surviving region rather than broadening it.

The behavior is logical AND: the combined probability is high only when every expert votes confidently; if even one expert outputs zero, the whole product collapses to zero. Compare that with a mixture of Gaussians, where probabilities are summed — an OR-flavored combination: one enthusiastic expert suffices to lift a mixture's mass at some point, while a product demands unanimity. Product of experts has powered varied image-generation variants precisely because AND-composition sculpts sharp, specific requirements.

Property Product of experts Mixture of Gaussians
Combination rule Multiply Add (weighted)
Logic AND — all constraints hold OR — any component suffices
Effect of one zero vote Whole distribution dies there Other components still cover it
Resulting support Sharp intersection of expert regions Broad union of blobs
Best for Enforcing simultaneous attributes Covering diverse modes

When to pick which: multiply when requirements must co-occur; mix when alternatives are acceptable.

14.12.2 Attribute-Controlled Faces

Real-world: face generation by attribute composition. Take an expert for "young", an expert for "female", an expert for "smiling" — multiply them and sample. The outputs are young, female, smiling faces, because all three expert scores must be simultaneously high. Swap in an expert for wavy hair and the attribute list grows arbitrarily. Complex, controllable generation falls out of multiplying simple opinions.

Worked example — the veto in numbers. Two candidate faces, three experts. Face A scores young , female , smiling ; face B scores young , female , smiling . Products: A: ; B: . Face B wins on two of three individual opinions — yet loses overall by a factor of ten, because its near-zero female score vetoes everything else. Sense-check: this matches the committee intuition — one strong rejection outweighs several endorsements. Final answer: the sampler concentrates on faces like A, where no attribute score sags.

Pitfalls:

  • Feeding uncalibrated experts into the product. One expert scoring systematically ten times larger than the others dominates every decision; normalize or rescale opinions before multiplying.
  • Expecting sampling to be easy. The product's normalizer inherits the usual intractability — though for comparing candidates the same ratio trick as Section 14.10 cancels it, since is common to all.
  • Stacking contradictory experts. "Young" and "grey-haired" multiply toward a vanishing distribution; conflicting requirements yield empty support rather than a compromise.

Recap: Multiplying independent expert scores builds an AND-shaped distribution — additive energies, intersecting supports — that turns simple binary judgments into rich, controllable generation targets.

Bridge: How would we ever train such products so real samples outscore impostors? That question drives restricted Boltzmann machines and contrastive divergence, the next stop on this thread — after which the course turns to NLP and vision applications mixing the models covered so far.

Real-world connection: attribute-composed face synthesis anticipated today's controllable generation APIs — stock-image tools let designers request "smiling woman in her twenties with curly hair" by combining attribute models multiplicatively, and the same AND-composition idea reappears in classifier-guided diffusion, where a guidance term pushes every denoising step toward the requested condition.

Exam Guidance Summary

  • Expect assignment-related questions in the final exam. Assignments double as exam preparation material, so finish yours thoroughly — the concepts you implemented are the concepts most likely to reappear on paper.
  • Assignment marks reserve points for tuned runs producing reasonable results — submitting code that merely runs without sensible output leaves marks on the table. Treat tuning as part of the graded task: adjust learning rates, schedules, and training time until samples actually look sensible.
  • The latent-dimension comparison across diffusion, VAE, and GAN is a favorite short-interview question; know it cold. One-line version: GAN and VAE codes are compact (roughly 100 numbers for a 128×128 image), while diffusion's noise draw matches the full image resolution.
  • Be ready to explain the generative trilemma: which family delivers fast sampling, which delivers diversity, which delivers quality, and why training stability separates diffusion and VAE from GAN. Practice naming which corner each family sacrifices and why.
  • Know which metric rewards diversity (FID, lower is better) and which rewards quality (IS, higher is better); expect a short conceptual question on them.
  • Understand why DDIM exists: the speed motivation and the data-prediction trick that permits skipping steps. Being able to write from the forward closed form is the core skill here.

A practical revision order: first memorize the three forward-process constants (, , ) and the closed form built from them; then rehearse the loss-collapse story (ELBO → Gaussian KLs → squared noise error); finally drill the comparison tables — families versus trilemma corners, FID versus IS — since those map directly onto short-answer questions.

Key Industry Applications

  • Conversational image editing: tools in the ChatGPT ecosystem modify uploaded images through diffusion-like reverse processes, which is why their generation feels slow — iterative denoising is inherent. DDIM-style step-skipping is the standard remedy shipping in production samplers.
  • Biomedical imaging: U-Net originated in biomedical image segmentation, assigning every pixel a segment label; the same architecture now powers diffusion noise prediction — one design serving both clinical contouring tools and creative generators.
  • Text-to-image systems: DALL-E and Meta's generators build on latent diffusion, and Stable Diffusion runs diffusion in the latent space of pretrained autoencoders for speed without quality loss — the reason consumer GPUs can synthesize images at home.
  • Text-to-video: sequences of frames generated from text prompts extend latent diffusion frame by frame, turning the image recipe into a temporal one.
  • Anomaly detection: energy-based comparison of sample probabilities flags outliers in industrial machine monitoring and fraud screening — the ratio test needs no partition function at all.
  • Recognition, tagging, retrieval: classification among candidate classes, part-of-speech tagging, sequence labeling, and image retrieval all reduce to probability comparisons suited to energy-based models — wherever ranking suffices, absolute probabilities can stay uncomputed.
  • Attribute-controlled media: product-of-experts compositions generate faces meeting simultaneous attribute demands — young, female, smiling, wavy-haired — by construction; the AND-composition idea echoes in today's guided-diffusion conditioning tricks.

UDL Lecture 14 notes · Diffusion Models and Energy-Based Models

Unsupervised Deep Learning· postgraduate· 2026-08-25

Sections Breakdown

114.1 Forward Diffusion Recap

Step-by-step noising, the closed-form jump to any timestep, and the limit to pure Gaussian noise.

214.2 The Reverse Denoising Process

Why the reverse transition needs the data point, and how learned Gaussian reverse steps chain into ancestral sampling.

314.3 Training Objective: A Hierarchical VAE View

The ELBO split into reconstruction, prior matching, and denoising terms, collapsing to squared noise regression.

414.4 The U-Net Noise Prediction Network

U-Net down and up paths, skip connections, and sinusoidal time embeddings for the noise predictor.

514.5 Measuring Generation Quality: FID and IS

What FID and IS measure, their directions, and how mode collapse shows up in each score.

614.6 Alternate Parameterization: DDIM

Predicting clean data instead of noise so sampling can skip timesteps, plus training and sampling algorithms.

714.7 Comparing the Generative Families

VAE, diffusion, and GAN pipelines compared by latent dimension, generative trilemma corners, and training stability.

814.8 Conditional Generation and Latent Diffusion

Text-embedding conditioning at every denoising step and latent diffusion inside a pretrained autoencoder space.

914.9 Energy-Based Models: Modeling Probabilities from First Principles

The two rules for valid densities and how normalizing by area manufactures them on demand.

1014.10 The Energy-Based Model Formulation

The energy-based formulation, partition function costs, and comparison tasks that cancel it out.

1114.11 The Ising Model

Restoring corrupted binary patches with pairwise potentials over data agreement and neighborhood smoothness.

1214.12 Product of Experts

Multiplying expert scores into an AND-shaped distribution for attribute-controlled generation.

Postgraduate students in machine learning and deep learning

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

Forward Diffusion Recap

Must-know: Forward diffusion has a closed form: q(x_t|x_0) = N(sqrt(abar_t) x_0, (1-abar_t) I) with abar_t = prod alpha_s, so training can jump to any timestep without simulating the chain.

⚠ Top pitfall: Confusing per-step alpha_t = 1 - beta_t with the cumulative product bar_alpha_t; also treating the noise epsilon as a scalar instead of an image-shaped tensor.

Self-check: With beta_1 = 0.1 and beta_2 = 0.2, what are the mean and variance of x_2 given x_0 = 1? (Mean sqrt(0.72) ~ 0.849, variance 0.28.)

Connects to: The Reverse Denoising Process; Training Objective: A Hierarchical VAE View.

The Reverse Denoising Process

Must-know: q(x_{t-1}|x_t) is intractable because Bayes' rule needs the unknown marginals q(x_{t-1}) and q(x_t); conditioning on x_0 makes every factor a known closed-form Gaussian, so the network learns p_theta to imitate that posterior.

⚠ Top pitfall: Trying to learn q(x_{t-1}|x_t) directly, or starting generation from a prior that does not match the forward chain's endpoint N(0, I).

Self-check: Why is q(x_{t-1}|x_t,x_0) computable while q(x_{t-1}|x_t) is not?

Connects to: Forward Diffusion Recap; Training Objective: A Hierarchical VAE View.

Training Objective: A Hierarchical VAE View

Must-know: The ELBO has three parts (reconstruction at t=1, prior matching q(x_T|x_0)||N(0,I), denoising matching summed over t=2..T); because both sides of each KL are Gaussians, training reduces to the simple squared-error noise regression loss.

⚠ Top pitfall: Thinking the network predicts x_{t-1} during training (it predicts the noise), or misquoting the ELBO sum range (intermediate steps t=2..T only).

Self-check: State the tractable posterior mean tilde_mu_t as a blend of x_0 and x_t, and the reparameterized mean mu_theta in terms of epsilon_theta.

Connects to: Forward Diffusion Recap; The Reverse Denoising Process; The U-Net Noise Prediction Network; Alternate Parameterization: DDIM.

The U-Net Noise Prediction Network

Must-know: U-Net = down path (pooling/strided convs, shrinking space, growing channels) + up path (transposed convolutions) + concatenating skip connections that pair coarse semantics with fine spatial detail; one shared network serves all timesteps via sinusoidal time embeddings added at every block.

⚠ Top pitfall: Feeding raw integer t instead of an embedding, or confusing U-Net concatenating skips with ResNet-style additions.

Self-check: Why does diffusion need a per-pixel architecture rather than a classifier CNN?

Connects to: Training Objective: A Hierarchical VAE View; Measuring Generation Quality: FID and IS; Alternate Parameterization: DDIM.

Measuring Generation Quality: FID and IS

Must-know: FID lower is better (diversity, detects mode collapse); IS higher is better (quality/fidelity); diffusion models reach very low FID and high IS because the noise-regression loss trains stably.

⚠ Top pitfall: Reversing the metric directions or reading a high IS as proof of diversity.

Self-check: Which metric would flag a generator that makes one perfect golden retriever and nothing else?

Connects to: The U-Net Noise Prediction Network; Comparing the Generative Families.

Alternate Parameterization: DDIM

Must-know: DDIM exists for speed: rearranging x_t = sqrt(abar_t) x_0 + sqrt(1-abar_t) epsilon gives x_hat_theta = (x_t - sqrt(1-abar_t) eps_theta)/sqrt(abar_t), which permits jumping over timesteps; training is unchanged and z is zeroed at the final step.

⚠ Top pitfall: Claiming DDIM changes the training loss (it does not — only sampling), or injecting noise at the final sampling step.

Self-check: Given x_t = 0.320, abar_t = 0.72, and predicted noise -0.9, compute x_hat_theta (~0.94).

Connects to: Training Objective: A Hierarchical VAE View; The U-Net Noise Prediction Network; Comparing the Generative Families.

Comparing the Generative Families

Must-know: For 128x128 data: GAN z is ~100x1 or 128x1 (resized to 4x512 then grown by convolutions), diffusion's noise draw is full 128x128 like a flow model, VAE's z is a chosen small latent. Trilemma: GAN = fast+quality, poor coverage; VAE = fast+decent coverage, weak plain quality; diffusion = quality+coverage, slow.

⚠ Top pitfall: Saying all three z's are 'just random' — the separator is dimension relative to the data; also claiming diffusion compresses images.

Self-check: Which trilemma corner does each family sacrifice, and which extra axis separates GANs from diffusion and VAEs?

Connects to: Measuring Generation Quality: FID and IS; Alternate Parameterization: DDIM; Conditional Generation and Latent Diffusion.

Conditional Generation and Latent Diffusion

Must-know: Conditional sampling = prompt embedding added to every U-Net block alongside the time embedding; latent diffusion encodes images (~1000x600) into small latent grids (~40x60, illustrative magnitudes) before diffusing — big compute cuts with no quality loss; Stable Diffusion is the canonical system.

⚠ Top pitfall: Forgetting that different seeds with the same prompt give different images (the noise draw differs), or treating the illustrative latent sizes as exact specs.

Self-check: Why does latent diffusion improve both speed and quality?

Connects to: The U-Net Noise Prediction Network; Comparing the Generative Families; Energy-Based Models: Modeling Probabilities from First Principles.

Energy-Based Models: Modeling Probabilities from First Principles

Must-know: Two conditions for a valid PDF: nonnegative values everywhere and total area one — nothing else (continuity not required). Normalize any nonnegative f by its own integral; Gaussian kernel normalizer sqrt(2*pi*sigma^2) and exponential integral 1/lambda are the classic closed forms.

⚠ Top pitfall: Guessing continuity is required, or normalizing over the wrong support range.

Self-check: Normalize f(x) = x^2 on [0,3]. (Answer: p(x) = x^2/9.)

Connects to: The Energy-Based Model Formulation; The Ising Model.

The Energy-Based Model Formulation

Must-know: p_theta(x) = exp(F_theta(x))/Z_theta with Z the partition function and -F the energy; computing Z scales exponentially with dimension (2^d states for d binary pixels); ratios cancel it: p(x)/p(x') = exp(F(x) - F(x')).

⚠ Top pitfall: Believing you must evaluate Z before using the model — comparison tasks never need it.

Self-check: Scores F(a)=2, F(b)=0: what is p(a)/p(b) and which constant vanished? (e^2 ~ 7.39; Z cancelled.)

Connects to: Energy-Based Models: Modeling Probabilities from First Principles; The Ising Model; Product of Experts.

The Ising Model

Must-know: Two assumptions: local corruption (observation depends only on its own pixel's truth) and neighborhood agreement (scenes are smooth); P(y,x) ∝ exp(sum of data potentials + neighbor potentials), and restoration = argmax over y since x is fixed and constants cancel.

⚠ Top pitfall: Over-weighting smoothing so real edges get erased, or trying to normalize before optimizing.

Self-check: Observed strip (1,0,1) with match bonus 1 and pair bonus 2: which candidate wins and why? ((1,1,1): smoothing outvotes the lone zero.)

Connects to: Energy-Based Models: Modeling Probabilities from First Principles; The Energy-Based Model Formulation; Product of Experts.

Product of Experts

Must-know: Product of experts p(x) = (1/Z) prod_k expert_k(x): logical AND — one zero vote collapses everything; mixtures sum (OR). In log space the product is a sum of expert energies.

⚠ Top pitfall: Mixing uncalibrated experts whose scales differ, or stacking contradictory experts yielding empty support.

Self-check: Face A scores (0.9, 0.8, 0.7), face B scores (0.98, 0.05, 0.95): which wins under a product and why? (A: 0.504 vs 0.047 — one low vote vetoes.)

Connects to: The Energy-Based Model Formulation; The Ising Model.

Exam Guidance Summary

Must-know: Assignments are exam preparation (tuning is graded); know the latent-dimension comparison cold, the trilemma corners per family, FID lower-is-better vs IS higher-is-better, and DDIM's data-prediction speed trick.

⚠ Top pitfall: Submitting assignment code that runs but produces unreasonable samples - tuning points are graded.

Self-check: Which metric rewards diversity and which rewards quality?

Connects to: Measuring Generation Quality: FID and IS; Alternate Parameterization: DDIM; Comparing the Generative Families.

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.