PROMETHEUS OS
NATIVE AI OPERATING SYSTEM
[INIT] Prometheus OS loading...
[CORE] Neural interface initializing...
[AI] LLM router connecting...
[MEM] Memory graph loading...
[AGT] Agent chains on standby...
[SEC] Security protocols active...
[NET] Provider mesh established...
[UI] Workspace rendering...
[DONE] All systems nominal.
Welcome to PROMETHEUS OS.
READY · OFFLINE · SECURE · PRIVATE
🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

Generative Models: The Big Picture

Intermediate 18 min· 5 exercises

Explain what a generative model learns and compare the six major families (autoregressive, VAE, GAN, flow, diffusion, energy-based) by their objectives, sampling cost, likelihood and failure modes.

By the end of this lesson you will be able to
  • Explain the difference between learning p(x) and learning p(y|x), and the three abilities a generative model can provide: sampling, density evaluation and representation.
  • Derive the VAE evidence lower bound and explain why the reparameterization trick makes it trainable with backpropagation.
  • Explain the GAN minimax objective, the optimal discriminator, and why mode collapse and instability arise.
  • Compute likelihoods for autoregressive and normalizing-flow models using the chain rule and change of variables.
  • Compare generative families on sample quality, speed, likelihood and stability, and choose an appropriate family for a task.
  • Implement and train a small VAE in PyTorch.

Before this: Probability and Statistics for AI, Information Theory and Loss Functions, Neural Networks and Backpropagation

Generative AI is the part of machine learning that produces new data: images, audio, video, text, molecules, code. Every modern system you have heard of, from chat assistants to text-to-image tools, is built on one of a small number of model families. If you understand what each family learns, how it is trained, and where it breaks, you can read any new paper or product announcement and place it on the map within minutes.

The core idea: learning a distribution

A discriminative model learns p(y∣x)p(y \mid x): given an input xx, how likely is each label yy? A generative model learns p(x)p(x) itself (or p(x∣c)p(x \mid c) for some condition cc such as a text prompt): how probable is this particular image, waveform or sentence among all the data the world could produce?

A useful picture: imagine every possible 64×64 color image as a point in a space with 64×64×3=12,28864 \times 64 \times 3 = 12{,}288 dimensions. Almost all of those points are static. Real photos occupy a thin, curved region (a "manifold") inside that space. A generative model is a map of that region: it tells you where the dense areas are and, crucially, lets you sample new points that land inside it.

Learning p(x)p(x) gives you up to three abilities, and the model families differ in which they provide cheaply:

  1. Sampling: draw new x∼pθ(x)x \sim p_\theta(x), where pθp_\theta is the model distribution with parameters θ\theta.
  2. Density evaluation: compute pθ(x)p_\theta(x) for a given xx (useful for compression, anomaly detection, and comparing models by likelihood).
  3. Representation: obtain a compact latent code zz that describes xx.

Training almost always means making pθp_\theta close to the data distribution pdatap_{\text{data}}. The most common target is maximum likelihood, which is equivalent to minimizing the KL divergence DKL(pdata ∥ pθ)D_{\mathrm{KL}}(p_{\text{data}} \,\|\, p_\theta):

θ∗=arg⁡max⁡θ  Ex∼pdata[log⁡pθ(x)]\theta^* = \arg\max_\theta \; \mathbb{E}_{x \sim p_{\text{data}}}\left[\log p_\theta(x)\right]

The families below are different answers to one hard question: how do you build a pθp_\theta that is flexible enough to describe photographs, yet tractable enough to train and sample?

Family 1: Autoregressive models

Any joint distribution can be factored exactly with the chain rule of probability. Order the dimensions of xx as x1,…,xDx_1, \dots, x_D:

pθ(x)=∏i=1Dpθ(xi∣x1,…,xi−1)p_\theta(x) = \prod_{i=1}^{D} p_\theta(x_i \mid x_1, \dots, x_{i-1})

An autoregressive model is a neural network that outputs each conditional. For text, xix_i are tokens and the network is a causal transformer: this is exactly how large language models work. For images, PixelRNN and PixelCNN (van den Oord et al., 2016) predicted pixels one at a time in raster order; WaveNet (van den Oord et al., 2016) did the same for raw audio samples. Today, images and audio are usually first compressed into discrete tokens by a learned codec (covered in later lessons), and a transformer predicts those tokens.

Worked example. A toy model generates three binary values. It predicts p(x1=1)=0.6p(x_1{=}1) = 0.6, then p(x2=0∣x1=1)=0.3p(x_2{=}0 \mid x_1{=}1) = 0.3, then p(x3=1∣x1=1,x2=0)=0.8p(x_3{=}1 \mid x_1{=}1, x_2{=}0) = 0.8. The probability of the sequence (1,0,1)(1, 0, 1) is

0.6×0.3×0.8=0.144,0.6 \times 0.3 \times 0.8 = 0.144,

so its negative log-likelihood is −ln⁡0.144=1.938-\ln 0.144 = 1.938 nats, or 1.938/ln⁡2=2.7961.938 / \ln 2 = 2.796 bits. Training minimizes the average of exactly this quantity over the dataset.

Strengths: exact likelihood, very stable training (it is just cross-entropy), and they scale predictably with data and compute. Weaknesses: sampling is sequential, so generating DD elements needs DD network evaluations (mitigated by KV caching and parallel decoding tricks); the fixed ordering is arbitrary for images; and errors can compound because each step conditions on the model's own earlier outputs.

Family 2: Variational autoencoders (VAEs)

Kingma and Welling introduced the VAE in "Auto-Encoding Variational Bayes" (2013). The idea is a latent-variable model: first draw a low-dimensional code zz from a simple prior p(z)=N(0,I)p(z) = \mathcal{N}(0, I), then generate xx from a decoder pθ(x∣z)p_\theta(x \mid z). The marginal likelihood is

pθ(x)=∫pθ(x∣z) p(z) dz,p_\theta(x) = \int p_\theta(x \mid z)\, p(z)\, dz,

which is intractable for a neural decoder because you cannot integrate over all zz. The VAE adds an encoder (inference network) qϕ(z∣x)q_\phi(z \mid x) with parameters ϕ\phi that guesses which codes could have produced xx. Using Jensen's inequality you get the evidence lower bound (ELBO):

log⁡pθ(x)  ≥  L(θ,ϕ;x)=Eqϕ(z∣x)[log⁡pθ(x∣z)]⏟reconstruction  −  DKL ⁣(qϕ(z∣x) ∥ p(z))⏟regularization\log p_\theta(x) \;\ge\; \mathcal{L}(\theta, \phi; x) = \underbrace{\mathbb{E}_{q_\phi(z \mid x)}\left[\log p_\theta(x \mid z)\right]}_{\text{reconstruction}} \;-\; \underbrace{D_{\mathrm{KL}}\!\left(q_\phi(z \mid x) \,\|\, p(z)\right)}_{\text{regularization}}

The gap between the two sides is exactly DKL(qϕ(z∣x) ∥ pθ(z∣x))D_{\mathrm{KL}}(q_\phi(z \mid x) \,\|\, p_\theta(z \mid x)), so the bound is tight when the encoder matches the true posterior. Maximizing the ELBO trains both networks at once: the first term asks the decoder to reconstruct xx from codes the encoder proposes; the second keeps the encoder's codes close to the prior so that sampling z∼N(0,I)z \sim \mathcal{N}(0, I) at generation time lands somewhere the decoder understands.

The reparameterization trick

The encoder outputs a mean μϕ(x)\mu_\phi(x) and standard deviation σϕ(x)\sigma_\phi(x) for a diagonal Gaussian. We need gradients of an expectation over zz with respect to ϕ\phi, but sampling is not differentiable. The trick is to move the randomness outside the network:

z=μϕ(x)+σϕ(x)⊙ϵ,ϵ∼N(0,I)z = \mu_\phi(x) + \sigma_\phi(x) \odot \epsilon, \qquad \epsilon \sim \mathcal{N}(0, I)

where ⊙\odot is element-wise multiplication. Now zz is a deterministic, differentiable function of ϕ\phi given ϵ\epsilon, so ordinary backpropagation works and gradient estimates have low variance.

For a diagonal Gaussian encoder and standard normal prior, the KL term has a closed form per latent dimension jj:

DKL=∑j12(μj2+σj2−1−ln⁡σj2)D_{\mathrm{KL}} = \sum_j \tfrac{1}{2}\left(\mu_j^2 + \sigma_j^2 - 1 - \ln \sigma_j^2\right)

Worked example. A 2-dimensional latent with μ=(0.5,−1.0)\mu = (0.5, -1.0) and σ=(1.0,0.5)\sigma = (1.0, 0.5):

  • Dimension 1: 12(0.25+1−1−ln⁡1)=0.125\tfrac{1}{2}(0.25 + 1 - 1 - \ln 1) = 0.125
  • Dimension 2: 12(1+0.25−1−ln⁡0.25)=12(0.25+1.386)=0.818\tfrac{1}{2}(1 + 0.25 - 1 - \ln 0.25) = \tfrac{1}{2}(0.25 + 1.386) = 0.818
  • Total KL =0.943= 0.943 nats.

If the decoder's reconstruction log-likelihood for this xx (estimated with one sample of zz) is −12.30-12.30, the ELBO is −12.30−0.943=−13.24-12.30 - 0.943 = -13.24, and the training loss is its negative, 13.2413.24.

Strengths: fast single-pass sampling, a meaningful latent space, a likelihood bound, stable training. Weaknesses: with simple Gaussian decoders, samples tend to be blurry because the reconstruction term behaves like mean-squared error, which averages over plausible outputs. Posterior collapse (the encoder ignores xx and the KL term goes to zero) is common when the decoder is powerful. The modern role of VAEs is mostly as compressors: the latent space of Stable Diffusion is a VAE (trained with extra perceptual and adversarial losses), and VQ-VAE (van den Oord et al., 2017) replaced the Gaussian latent with a discrete codebook, which is the ancestor of today's image and audio tokenizers.

Family 3: Generative adversarial networks (GANs)

Goodfellow et al. (2014) proposed training two networks against each other. A generator GG maps noise z∼p(z)z \sim p(z) to a sample G(z)G(z). A discriminator DD outputs the probability that its input is real. They play a minimax game:

min⁡Gmax⁡D  V(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼p(z)[log⁡(1−D(G(z)))]\min_G \max_D \; V(D, G) = \mathbb{E}_{x \sim p_{\text{data}}}\left[\log D(x)\right] + \mathbb{E}_{z \sim p(z)}\left[\log\left(1 - D(G(z))\right)\right]

For a fixed generator with sample distribution pgp_g, the optimal discriminator is

D∗(x)=pdata(x)pdata(x)+pg(x).D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_g(x)}.

For example, at a point where pdata(x)=0.3p_{\text{data}}(x) = 0.3 and pg(x)=0.1p_g(x) = 0.1, D∗(x)=0.3/0.4=0.75D^*(x) = 0.3 / 0.4 = 0.75. Substituting D∗D^* back shows the generator is minimizing 2 JSD(pdata ∥ pg)−log⁡42\, \mathrm{JSD}(p_{\text{data}} \,\|\, p_g) - \log 4, where JSD is the Jensen–Shannon divergence; the global optimum is pg=pdatap_g = p_{\text{data}}, where D∗=1/2D^* = 1/2 everywhere and V=−log⁡4V = -\log 4. In practice, the generator is trained with the "non-saturating" loss −log⁡D(G(z))-\log D(G(z)) instead, because log⁡(1−D(G(z)))\log(1 - D(G(z))) has vanishing gradients early in training when DD easily rejects fakes.

GANs produced the sharpest images of the late 2010s (the StyleGAN line from NVIDIA is the best-known example) because the discriminator acts as a learned perceptual loss rather than pixel-wise error.

Failure modes

  • Mode collapse: the generator finds a few outputs that fool the current discriminator and produces only those, covering a small part of the data distribution. The adversarial objective does not directly penalize missing modes.
  • Training instability: it is a two-player game, not a single minimization. Gradients can oscillate, the discriminator can overpower the generator (vanishing generator gradients), and results are sensitive to architecture, learning rates and batch size. Remedies include Wasserstein GAN losses with gradient penalties, spectral normalization, two-timescale learning rates and careful architecture choices, but none make GANs as plug-and-play as likelihood training.
  • No likelihood: you cannot evaluate pg(x)p_g(x), which makes model comparison depend on sample-based metrics such as FID.

GANs remain important as components: adversarial losses sharpen VAE decoders and neural audio codecs, and GAN vocoders such as HiFi-GAN convert spectrograms to waveforms in many speech systems.

Family 4: Normalizing flows

A flow builds pθ(x)p_\theta(x) from an invertible, differentiable function fθf_\theta that maps data xx to a latent z=fθ(x)z = f_\theta(x) with a simple density pZp_Z. The change-of-variables formula gives an exact likelihood:

log⁡pθ(x)=log⁡pZ ⁣(fθ(x))+log⁡∣det⁡∂fθ(x)∂x∣\log p_\theta(x) = \log p_Z\!\left(f_\theta(x)\right) + \log \left| \det \frac{\partial f_\theta(x)}{\partial x} \right|

The Jacobian determinant accounts for how fθf_\theta stretches or compresses volume. Worked 1D example: let x=2z+1x = 2z + 1 with z∼N(0,1)z \sim \mathcal{N}(0, 1), so f(x)=(x−1)/2f(x) = (x - 1)/2 and ∣df/dx∣=1/2|df/dx| = 1/2. At x=3x = 3, z=1z = 1, pZ(1)=0.2420p_Z(1) = 0.2420, so p(x=3)=0.2420×0.5=0.1210p(x{=}3) = 0.2420 \times 0.5 = 0.1210.

Computing a D×DD \times D determinant costs O(D3)O(D^3), so flows use layers with triangular Jacobians. Coupling layers (RealNVP, Dinh et al. 2016; Glow, Kingma and Dhariwal 2018) split xx into halves and transform one half with a scale and shift computed from the other; the log-determinant is just the sum of the log-scales. Rezende and Mohamed (2015) popularized the term "normalizing flow" for variational inference.

Strengths: exact likelihood, exact inversion, one-pass sampling. Weaknesses: the invertibility constraint forces the latent to have the same dimension as the data and limits architecture, so pure flows have lagged in sample quality. The ideas live on, however, in continuous-time flows and flow matching, which train a neural ODE velocity field and now power several leading image and video generators (see the diffusion lesson).

Family 5: Diffusion models

Diffusion models (Sohl-Dickstein et al., 2015; made practical by Ho, Jain and Abbeel's DDPM, 2020) define a fixed forward process that gradually adds Gaussian noise to data until nothing is left but noise, then train a network to reverse it one small step at a time. Each reverse step is an easy denoising problem, so training is a simple regression loss, stable and scalable. Sampling starts from pure noise and runs the learned denoiser for tens of steps. The training objective is a reweighted ELBO, so diffusion models also give likelihood bounds.

Diffusion (and its close relative flow matching) is the dominant approach for images, video and much of audio as of November 2026. Its main weakness is sampling cost: many network evaluations per sample, which a whole research area of fast samplers and distillation works to reduce. The next lesson covers it in depth.

Family 6: Energy-based models (briefly)

An energy-based model (EBM) assigns a scalar energy Eθ(x)E_\theta(x), low for realistic data, and defines

pθ(x)=exp⁡(−Eθ(x))Zθ,Zθ=∫exp⁡(−Eθ(x)) dx.p_\theta(x) = \frac{\exp(-E_\theta(x))}{Z_\theta}, \qquad Z_\theta = \int \exp(-E_\theta(x))\, dx.

The partition function ZθZ_\theta is intractable, which makes both likelihood training and sampling hard; sampling typically uses Markov chain Monte Carlo such as Langevin dynamics, which repeatedly steps along −∇xEθ(x)-\nabla_x E_\theta(x) plus noise. EBMs are conceptually important because the gradient of the log-density, ∇xlog⁡p(x)=−∇xE(x)\nabla_x \log p(x) = -\nabla_x E(x), does not depend on ZθZ_\theta. That quantity is the score, and learning the score directly is exactly what score-based diffusion models do. In that sense diffusion is the practical descendant of energy-based thinking.

Comparison

The table summarizes typical behavior; individual models can deviate.

FamilySample qualitySampling speedLikelihoodTraining stabilityTypical use today
AutoregressiveHigh (with tokenizers)Slow, sequentialExactVery stableText, audio tokens, some image systems
VAEModerate, often blurryFast, one passLower boundStableLatent compressors, tokenizers
GANHigh, sharpFast, one passNoneUnstableVocoders, codec/decoder losses, fast distilled generators
Normalizing flowModerateFast, one passExactStableDensity estimation, scientific modeling
Diffusion / flow matchingVery highSlow (many steps), improvableBound (or exact via ODE)StableImages, video, audio
Energy-basedVariableSlow (MCMC)UnnormalizedHardResearch, compositional modeling

A well-known framing is the "generative trilemma": high quality, fast sampling and mode coverage are hard to get simultaneously. GANs are fast and sharp but drop modes; VAEs and flows are fast with coverage but lower quality; diffusion has quality and coverage but is slow. Much of the last few years of research is about escaping that triangle, for example distilling diffusion models into few-step generators.

Code: a small VAE in PyTorch

This VAE learns the two-moons dataset (2D points), small enough to train on a CPU in seconds. It shows the encoder, reparameterization, closed-form KL and sampling.

import torch, torch.nn as nn
from sklearn.datasets import make_moons

X = torch.tensor(make_moons(4000, noise=0.05)[0], dtype=torch.float32)

class VAE(nn.Module):
    def __init__(self, d=2, h=64, k=2):
        super().__init__()
        self.enc = nn.Sequential(nn.Linear(d, h), nn.ReLU(), nn.Linear(h, 2 * k))
        self.dec = nn.Sequential(nn.Linear(k, h), nn.ReLU(), nn.Linear(h, d))
    def forward(self, x):
        mu, logvar = self.enc(x).chunk(2, dim=-1)
        eps = torch.randn_like(mu)
        z = mu + torch.exp(0.5 * logvar) * eps          # reparameterization
        return self.dec(z), mu, logvar

model = VAE()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for step in range(3000):
    x = X[torch.randint(0, len(X), (256,))]
    xhat, mu, logvar = model(x)
    recon = ((xhat - x) ** 2).sum(-1).mean()           # Gaussian decoder, fixed variance
    kl = 0.5 * (mu**2 + logvar.exp() - 1 - logvar).sum(-1).mean()
    loss = recon + 0.1 * kl                             # beta-weighted ELBO (beta = 0.1)
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 1000 == 0:
        print(step, round(recon.item(), 4), round(kl.item(), 4))

with torch.no_grad():
    samples = model.dec(torch.randn(500, 2))            # generate: z ~ N(0, I)
print(samples[:5])

The 0.1 weight on the KL term makes this a β-VAE with β < 1: it trades a looser prior match for sharper reconstructions. With β = 1 on such a tiny model, samples typically smear into a blurry cloud that also fills the gap between the moons, a direct view of the VAE blurriness problem. Plot samples for both settings to compare (details vary by seed).

Common pitfalls

  • Comparing likelihoods across families carelessly. Bits-per-dimension from a flow and an ELBO from a VAE are not directly comparable (one is exact, one is a bound), and likelihood correlates poorly with perceptual quality: a model can have excellent likelihood and ugly samples, or vice versa.
  • Assuming sharp samples mean good coverage. A GAN can produce beautiful images while ignoring half the classes. Always check diversity (recall-style metrics, per-class counts, nearest-neighbor checks against training data).
  • Forgetting the KL weight. Reported "VAE" results often use β ≠ 1 or KL annealing. Copying the architecture without the schedule leads to posterior collapse or blurry output.
  • Using pixel MSE as the only loss for anything that must look realistic. Pixel losses average; perceptual and adversarial losses are why modern latent autoencoders look crisp.
  • Treating memorization as generalization. Large generative models can reproduce near-copies of training examples. Deduplicate training data and test for near-duplicates of outputs.

In practice

Production systems as of November 2026 combine families rather than pick one. A typical image or video generator is a VAE-style autoencoder (trained with perceptual and adversarial losses) that compresses pixels into latents, plus a diffusion or flow-matching transformer that generates those latents. Text and code generation is autoregressive. Speech and music systems often use a codec (an autoencoder with vector quantization and GAN losses) whose tokens are generated by an autoregressive transformer, sometimes with a diffusion or flow stage on top. When you evaluate a new system, ask four questions: what is the representation (pixels, continuous latents, discrete tokens)? Which family generates it? How many network evaluations does one sample cost? How was quality measured, and does that metric capture diversity?

Key takeaways

  • A generative model learns the data distribution p(x) (or p(x|c)), which can provide sampling, density evaluation and latent representations, though no family gives all three cheaply.
  • Autoregressive models factor p(x) with the chain rule and train with plain cross-entropy, giving exact likelihoods and stable training at the cost of sequential sampling.
  • VAEs maximize the ELBO, a reconstruction term minus a KL regularizer, made trainable by the reparameterization trick; today they mainly serve as latent compressors.
  • GANs train a generator against a discriminator; they give sharp, fast samples but no likelihood and suffer from mode collapse and unstable training.
  • Diffusion and flow-matching models dominate image, video and much audio generation because they train stably with a regression loss and cover the data well, though sampling needs many steps.
  • Real systems combine families, for example an autoencoder for compression plus a diffusion transformer or autoregressive model for generation.

Terms in this lesson

Generative model
A model that represents a probability distribution over data, p(x) or p(x|c), from which new samples can be drawn.
Evidence lower bound (ELBO)
A tractable lower bound on log p(x) equal to the expected reconstruction log-likelihood minus the KL divergence between the approximate posterior and the prior.
Reparameterization trick
Writing a random latent as a deterministic function of model outputs and independent noise (z = mu + sigma * epsilon) so gradients can flow through sampling.
Mode collapse
A GAN failure in which the generator produces only a small subset of the data's variety because that subset fools the discriminator.
Normalizing flow
A generative model built from invertible transformations whose exact likelihood follows from the change-of-variables formula.
Score
The gradient of the log-density with respect to the data, grad_x log p(x), which does not depend on the normalizing constant.
Posterior collapse
A VAE failure in which the encoder's output matches the prior regardless of input, so the latent carries no information.
Partition function
The normalizing constant Z in an energy-based model that makes exp(-E(x))/Z integrate to one; usually intractable.

Check your understanding

  1. 1.

    Which quantity does a VAE maximize during training?

  2. 2.

    At a point x where p_data(x) = 0.2 and the generator's density p_g(x) = 0.6, what is the optimal GAN discriminator output D*(x)?

  3. 3.

    You need to score how unusual each incoming sensor reading is with an exact density, and sample quality is secondary. Which family fits best?

  4. 4.

    Why does the reparameterization trick help train VAEs?

  5. 5.

    An autoregressive model assigns probabilities 0.5, 0.4 and 0.5 to the three tokens of a sequence. What is the sequence's negative log-likelihood in bits?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    A VAE encoder outputs μ=(0,2)\mu = (0, 2) and σ=(0.5,1)\sigma = (0.5, 1) for one input. Compute the KL divergence to N(0,I)\mathcal{N}(0, I). If the one-sample reconstruction log-likelihood is −20.0-20.0, what is the ELBO?

    Show solution

    Per dimension, 12(μ2+σ2−1−ln⁡σ2)\tfrac{1}{2}(\mu^2 + \sigma^2 - 1 - \ln \sigma^2).

    • Dim 1: 12(0+0.25−1−ln⁡0.25)=12(−0.75+1.3863)=0.3181\tfrac{1}{2}(0 + 0.25 - 1 - \ln 0.25) = \tfrac{1}{2}(-0.75 + 1.3863) = 0.3181.
    • Dim 2: 12(4+1−1−0)=2.0\tfrac{1}{2}(4 + 1 - 1 - 0) = 2.0.

    KL =2.3181= 2.3181 nats. ELBO =−20.0−2.3181=−22.32= -20.0 - 2.3181 = -22.32 nats, so the loss is 22.3222.32.

  2. Exercise 2Core

    A 1D flow maps data to latent with z=f(x)=3x−6z = f(x) = 3x - 6 and z∼N(0,1)z \sim \mathcal{N}(0,1). Compute p(x)p(x) at x=2x = 2 and at x=2.5x = 2.5. Explain why the factor 3 appears.

    Show solution

    ∣df/dx∣=3|df/dx| = 3. At x=2x = 2: z=0z = 0, pZ(0)=0.3989p_Z(0) = 0.3989, so p(x)=0.3989×3=1.1968p(x) = 0.3989 \times 3 = 1.1968. At x=2.5x = 2.5: z=1.5z = 1.5, pZ(1.5)=0.1295p_Z(1.5) = 0.1295, so p(x)=0.1295×3=0.3886p(x) = 0.1295 \times 3 = 0.3886.

    The map stretches xx-space by a factor of 3 when going to zz; equivalently, data are concentrated in an interval 3 times narrower than the latent, so density in xx is 3 times higher. A density above 1 is fine for continuous variables.

  3. Exercise 3Core

    Your team must choose a generative approach for each case and justify it in one sentence: (a) a 2 ms-latency generator of synthetic sensor traces on an edge device; (b) a photorealistic product-image generator where quality matters most and a few seconds per image is acceptable; (c) a compression codec where you need exact code lengths.

    Show solution

    (a) A GAN or a distilled one-step generator: single forward pass, and some loss of diversity is acceptable for synthetic traces (monitor for mode collapse). (b) A latent diffusion or flow-matching model: best quality and coverage, and the multi-step cost fits the time budget. (c) An autoregressive model or normalizing flow: both give exact likelihoods, and −log⁡2p(x)-\log_2 p(x) is the ideal code length under entropy coding.

  4. Exercise 4Challenge

    Show that for a fixed generator, the GAN value function V(D,G)V(D,G) is maximized by D∗(x)=pdata(x)/(pdata(x)+pg(x))D^*(x) = p_{\text{data}}(x)/(p_{\text{data}}(x)+p_g(x)), and that substituting D∗D^* gives V=−log⁡4+2 JSD(pdata∥pg)V = -\log 4 + 2\,\mathrm{JSD}(p_{\text{data}}\|p_g).

    Show solution

    Write V=∫[pdata(x)log⁡D(x)+pg(x)log⁡(1−D(x))] dxV = \int [p_{\text{data}}(x) \log D(x) + p_g(x) \log(1 - D(x))]\,dx. For each xx, maximize alog⁡y+blog⁡(1−y)a \log y + b \log(1-y) over y∈(0,1)y \in (0,1) with a=pdata(x)a = p_{\text{data}}(x), b=pg(x)b = p_g(x). The derivative a/y−b/(1−y)=0a/y - b/(1-y) = 0 gives y=a/(a+b)y = a/(a+b), and the second derivative is negative, so this is the maximum.

    Substitute, with m=(pdata+pg)/2m = (p_{\text{data}} + p_g)/2:

    V=Epdata[log⁡pdata2m]+Epg[log⁡pg2m]=−2log⁡2+DKL(pdata∥m)+DKL(pg∥m)V = \mathbb{E}_{p_{\text{data}}}[\log \tfrac{p_{\text{data}}}{2m}] + \mathbb{E}_{p_g}[\log \tfrac{p_g}{2m}] = -2\log 2 + D_{\mathrm{KL}}(p_{\text{data}}\|m) + D_{\mathrm{KL}}(p_g\|m).

    Since JSD=12[DKL(pdata∥m)+DKL(pg∥m)]\mathrm{JSD} = \tfrac{1}{2}[D_{\mathrm{KL}}(p_{\text{data}}\|m) + D_{\mathrm{KL}}(p_g\|m)], V=−log⁡4+2 JSDV = -\log 4 + 2\,\mathrm{JSD}. JSD is non-negative and zero only when pg=pdatap_g = p_{\text{data}}, so the generator's optimum is the data distribution.

  5. Exercise 5Challenge

    Modify the lesson's VAE code to track posterior collapse: report the average KL per latent dimension, and run with β=1\beta = 1 and β=0.1\beta = 0.1. What do you expect, and why?

    Show solution

    Add per-dimension KL logging:

    kl_dim = 0.5 * (mu**2 + logvar.exp() - 1 - logvar).mean(0)  # shape (k,)
    if step % 1000 == 0:
        print(step, [round(v, 3) for v in kl_dim.tolist()])
    

    Wrap training in a function taking beta and use loss = recon + beta * kl. Expected: with β=1\beta = 1, the KL penalty is strong relative to the small reconstruction error on 2D data, so one or both dimensions drift toward KL ≈0\approx 0 (collapsed: they carry no information) and reconstructions approach the data mean, giving blurry samples. With β=0.1\beta = 0.1, both dimensions keep substantial KL because encoding information is cheap, reconstructions are sharp, but samples from N(0,I)\mathcal{N}(0,I) may land in regions the decoder never saw because the aggregate posterior no longer matches the prior. Exact numbers vary by seed.

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026