Generative Modeling: Learning Data Distributions
Suppose you have a million photographs of human faces. You want a machine that can produce new, never-seen faces. These faces should be indistinguishable from real ones. No labels tell you "this is a face" versus "this is not". You only have samples. This is the generative modeling problem. Given data drawn from some unknown distribution , learn a model. This model must capture that distribution well enough to generate new samples. It should also evaluate how likely new data is, or both. Generative modeling matters because most of the world's data is unlabeled. The ability to model underlies image synthesis and speech synthesis. It also underlies drug-molecule design, anomaly detection, data augmentation, compression, and simulation of physical systems. A model that truly understands has implicitly learned the structure of the domain. It learns which pixel patterns look like faces. It learns which amino-acid sequences fold into stable proteins. It learns which sentences are fluent English. This is qualitatively different from Supervised Learning. There, a model only learns a conditional mapping . The big picture is a fork in the road. Do you model the density explicitly? Then you can write down (or approximate) its formula and compute probabilities. Or do you only build a mechanism that produces samples? This is called an implicit model. It never computes a likelihood. Explicit models split further into two types. Some have tractable likelihoods (autoregressive models, normalizing flows). Others have only an approximate or bounded likelihood (Variational Autoencoders, diffusion models). Implicit models are typified by Generative Adversarial Networks. They sidestep likelihood computation entirely. They are trained via an adversarial game or other sampling-based objective. This article builds the conceptual scaffolding for later topics. It covers precise definitions of explicit vs. implicit density. It covers the likelihood-based training principle. It covers the sampling-based alternative. Every later architecture specializes and extends this scaffolding. This includes VAEs, GANs, normalizing flows, and diffusion models.
- Generative models learn from samples, enabling synthesis, density estimation, and anomaly detection.
- Explicit density models write down (exactly or approximately); implicit density models only sample from it.
- Explicit models split into tractable likelihood (autoregressive, normalizing flows) and approximate likelihood (VAEs, diffusion, via bounds).
- Maximum likelihood estimation (MLE) is the dominant training principle for explicit models: maximize .
- Sampling-based / adversarial objectives (GANs) train a generator without ever evaluating , using a discriminator as a learned critic.
- The choice of paradigm trades off sample quality, likelihood tractability, training stability, and sampling speed.
A generative model is any function or process trained so that samples it produces — or probabilities it assigns — match an unknown data distribution, and the central design choice is whether that distribution's density is computed explicitly, approximated, or never computed at all.
The idea
A generative model is a probabilistic model , parameterized by (e.g., neural network weights), trained on samples so that approximates . This contrasts with discriminative models, which learn directly and are indifferent to the marginal structure of . Generative models can be used for three related but distinct tasks: density estimation (compute or bound for a given ), sampling (draw new ), and representation learning (extract a low-dimensional code that explains ). The taxonomy in this article rests on one axis: how the model relates to the likelihood function .
Explicit density, tractable likelihood. The model defines via a formula that can be evaluated exactly in closed form (or with a cheap forward pass). Two major families achieve this:
- Autoregressive models factor the joint distribution using the chain rule of probability,
and parameterize each conditional with a neural network (e.g., PixelRNN, PixelCNN, GPT-style transformers over tokens). Every factor is a normalized distribution over one variable, so the product is automatically normalized — no partition function to worry about.
- Normalizing flows transform a simple base density (e.g., a standard Gaussian) through an invertible, differentiable map , and use the change-of-variables formula
Both families allow exact log-likelihood computation, so training reduces to plain maximum likelihood.
Explicit density, approximate likelihood. The model posits latent variables with , but this integral is intractable to compute exactly for expressive decoders . Instead of the true likelihood, training maximizes a tractable lower bound on it — the evidence lower bound (ELBO) in Variational Autoencoders, or a denoising-based bound in diffusion models. You never compute exactly, only a certified bound on .
Implicit density. The model provides only a sampling procedure — typically for a simple noise distribution and a neural network — with no tractable expression for at all. Generative Adversarial Networks are the canonical example: a generator and discriminator are trained jointly so that 's samples become indistinguishable from real data according to , an objective that requires no likelihood evaluation whatsoever. The training principle splits along the same lines. Likelihood-based training (MLE or its bound) directly optimizes a probabilistic objective and gives you calibrated density values as a byproduct. Sampling-based / adversarial training optimizes an objective defined purely in terms of samples — often a divergence estimated implicitly through an auxiliary discriminator or a two-sample test — and never yields a usable .
How it works
Regardless of family, generative model training follows a common template: define a parametric object that can produce or score samples, define a loss connecting model and data, and optimize by gradient descent. Below are the two canonical mechanisms — MLE for explicit models, and adversarial training for implicit ones — laid out as algorithms, followed by a diagram placing all four families on the same map.
Mechanism 1 — Maximum Likelihood Training (explicit density). The population objective is to minimize the Kullback–Leibler divergence from data to model,
which is estimated with the empirical average over the training set — this is maximum likelihood estimation. ``` Algorithm: Maximum-Likelihood Training of an Explicit Density Model Input: dataset D = {x_1, ..., x_n}, model p_theta with tractable log p_theta(x) Output: fitted parameters theta 1. Initialize theta randomly 2. repeat until convergence: 3. sample a minibatch B ⊂ D of size m 4. compute batch log-likelihood: L(theta) = (1/m) sum_{x in B} log p_theta(x) 5. compute gradient g = ∇_theta L(theta) # exact if likelihood is tractable 6. theta ← theta + eta g # gradient ASCENT on log-likelihood 7. return theta
# For autoregressive models: log p_theta(x) = sum_i log p_theta(x_i | x_
# in one forward pass with a causal mask (teacher forcing).
# For normalizing flows: log p_theta(x) = log p_Z(f_theta^{-1}(x)) + log|det J_{f_theta^{-1}}(x)|,
# requiring f_theta invertible with a tractable Jacobian determinant.
# For latent-variable models (VAE/diffusion): replace step 4 with a lower bound ELBO(theta, phi) ≤ log p_theta(x),
# introducing an auxiliary inference network with parameters phi, and ascend the bound instead. ```
Mechanism 2 — Adversarial (sampling-based) training (implicit density). ``` Algorithm: Adversarial Training of an Implicit Generative Model Input: dataset D of real samples, noise prior p(z), generator G_theta, discriminator D_phi Output: fitted generator parameters theta 1. Initialize theta, phi randomly 2. repeat until convergence: 3. sample minibatch of real data {x_1,...,x_m} ~ D 4. sample minibatch of noise {z_1,...,z_m} ~ p(z) 5. fake samples: x̂_j = G_theta(z_j) 6. # --- discriminator step: push D toward distinguishing real vs. fake --- 7. phi ← phi + eta_D ∇_phi [ (1/m) sum_i log D_phi(x_i) + (1/m) sum_j log(1 - D_phi(x̂_j)) ] 8. # --- generator step: push G to fool the (updated) discriminator --- 9. re-sample noise, recompute x̂_j = G_theta(z_j) 10. theta ← theta + eta_G ∇_theta [ (1/m) sum_j log D_phi(x̂_j) ] # non-saturating variant 11. return theta
# No log p_theta(x) is ever computed. D_phi acts as a learned, implicit density-ratio estimator:
# at the Nash equilibrium, D*(x) = p_data(x) / (p_data(x) + p_theta(x)), which is exactly 1/2 everywhere
# iff p_theta = p_data, tying the adversarial game to Jensen–Shannon divergence minimization. ``` The diagram below places the four families on a single map along the explicit/implicit and tractable/approximate axes, showing how each foreshadowed architecture fits.
Complexity & correctness
Time and space complexity by family. Autoregressive models. Training likelihood for a -dimensional input costs sequential conditional evaluations, but with masked architectures (causal convolutions, causal attention) all conditionals are computed in parallel in one forward pass, giving work but sequential depth relative to during training. Sampling, however, is inherently sequential: generating requires , so sampling costs sequential network evaluations — this asymmetry (fast parallel training, slow sequential sampling) is a defining, and honest, limitation of autoregressive models. Normalizing flows. Density evaluation costs one forward (or inverse) pass through plus the log-determinant of a Jacobian, which is in general. Practical flow architectures (coupling layers, autoregressive flows) constrain so the Jacobian is triangular, reducing the determinant to — the product of diagonal entries. This architectural constraint is what makes flows tractable at all; it is a real restriction on expressiveness, not a free lunch. VAEs. One forward pass through encoder and decoder costs (network-dependent), and the ELBO is computed with a single Monte Carlo sample of via the reparameterization trick, adding negligible overhead. Sampling is a single decoder forward pass — network evaluations, much faster than autoregressive sampling. GANs. One generator forward pass produces a sample, network evaluations — the fastest sampling of any family discussed. Training cost per step is one discriminator pass plus one generator pass, but the number of steps to convergence is empirically much less predictable, since there is no monotone loss to track.
Why maximum likelihood is the correct objective (explicit models). Minimizing over is equivalent to maximizing , since
and the first term does not depend on . Because with equality iff almost everywhere (Gibbs' inequality), driving the KL to its minimum value of zero — which MLE does asymptotically, as , under standard regularity conditions and a sufficiently expressive model class — is provably the right target. The empirical average is an unbiased Monte Carlo estimator of , so gradient ascent on the sample average is a consistent estimator of the population optimum by the law of large numbers.
Why the ELBO is a valid surrogate (approximate-likelihood models). For any latent-variable model with variational posterior ,
Since the KL term is non-negative, the ELBO is a certified lower bound on the true log-likelihood for every ; maximizing it maximizes a guaranteed floor on the quantity we actually care about, and the gap closes as approaches the true posterior.
Why the adversarial game targets the right divergence. At a fixed generator, the optimal discriminator is (this is the Bayes-optimal classifier between the two distributions, derivable by maximizing the discriminator's expected log-likelihood pointwise). Substituting back into the value function shows the generator's objective becomes, up to a constant, , the Jensen–Shannon divergence. Since with equality iff the distributions coincide, the global minimum of the generator's loss (given an optimal discriminator) is achieved exactly when — this is the theoretical justification for adversarial training, though it assumes an idealized, fully-optimized discriminator at every step, which practical alternating gradient descent only approximates.
Honest tradeoffs. Tractable-likelihood models give calibrated probabilities and stable, well-understood training (plain gradient ascent on a scalar objective) but pay for it — autoregressive sampling is slow, and flows require restrictive invertibility constraints that can limit expressiveness. Approximate-likelihood models relax the invertibility constraint but only optimize a bound, so the model may be penalized less for missing modes than a true likelihood would penalize it (a known failure mode of posterior-collapse in VAEs). Implicit models sample fastest and can produce the sharpest, most realistic outputs, but they lose density evaluation entirely, offer no direct measure of overfitting or mode coverage, and their non-convex minimax training can oscillate or collapse (mode collapse) rather than converge.
Worked example
Consider a toy dataset of 2-D points and three candidate ways to model : an autoregressive factorization, a flow, and an implicit sampler. Suppose we observe points:
Step 1 — Autoregressive model. Factor . Suppose after training, the model assigns
| 0 | 0.30 | 0 | 0.9 |
| 1 | 0.45 | 1 | 0.5 |
| 1 | 0.45 | 2 | 0.4 |
| 2 | 0.25 | 3 | 0.7 |
The exact joint log-likelihood of the dataset is computed by simple multiplication and summation — no integral, no approximation:
This is an exact number — the defining feature of the autoregressive/flow family. Gradient ascent adjusts the conditional tables (or network weights producing them) directly on this quantity.
Step 2 — Latent-variable model (VAE-style). Now suppose instead with a 1-D Gaussian latent . We cannot integrate this exactly for a neural decoder, so we instead compute the ELBO for point using an encoder and prior :
The KL term between two Gaussians has a closed form:
If the reconstruction term (estimated with one sampled via reparameterization, ) evaluates to, say, , then . This is not — it is guaranteed to be less than or equal to the true (uncomputable) log-likelihood. Training maximizes this quantity, trusting the bound's tightness rather than exactness.
Step 3 — Implicit model (GAN-style). Here there is no likelihood step at all. A generator maps to ; suppose maps to . We never compute . Instead, the discriminator scores it: (closer to 0 = "looks fake," closer to 1 = "looks real"). Training updates to push this score toward and updates to keep distinguishing real points (which score near ) from generated ones — the entire signal is comparative, sample-vs-sample, never a probability of the data. The contrast is the whole lesson: identical dataset, three fundamentally different notions of what "fitting the distribution" even means numerically.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Confusing a bound (ELBO) with the true likelihood | The ELBO is often reported as "the log-likelihood" in papers/code, hiding the KL gap | Always state whether a number is exact or a lower bound; monitor the encoder-posterior KL term separately |
| Assuming flows can model any distribution | Invertibility + tractable Jacobian forces restrictive layer designs (e.g., coupling layers keep half the dimensions unchanged per layer) | Stack many flow layers / use expressive coupling functions; understand the architectural constraint, not just the theorem |
| Treating GAN loss as a convergence signal | The minimax objective is not monotone; generator and discriminator losses can oscillate even as sample quality improves | Track sample quality metrics (FID, precision/recall) and mode coverage, not raw loss curves |
| Ignoring sequential sampling cost of autoregressive models | Parallel training (teacher forcing) hides the fact that generation is inherently step-by-step | Budget sequential passes for sampling; consider caching or non-autoregressive alternatives if latency matters |
| Mode collapse in implicit models | Generator finds a small region of output space that reliably fools the current discriminator | Use architectural/training fixes (minibatch discrimination, alternative divergences, gradient penalties); track diversity metrics explicitly |
Pioneers & history
The generative modeling paradigm draws on a century of probability and statistics, crystallized into deep learning through a sequence of foundational papers connecting neural networks to explicit and implicit density estimation.
Origins · 1 minIan J. Goodfellow and how this was discovered
Where this matters
Explicit autoregressive models power large language models: every modern text generator (GPT-family and successors) is, at its core, an autoregressive density model over tokens trained by maximum likelihood, exactly the mechanism described above. Normalizing flows are used in scientific simulation (lattice field theory, molecular conformer generation) where exact density evaluation is required for downstream physics calculations, and in some fast, invertible audio vocoders. Variational Autoencoders and their descendants underlie representation learning pipelines, anomaly detection systems, and are a core building block inside modern latent diffusion image generators (compressing images into a latent space before the diffusion process operates). Generative Adversarial Networks, despite training instability, remain widely used for fast, high-resolution image synthesis, super-resolution, image-to-image translation, and data augmentation in domains such as medical imaging where labeled data is scarce. Diffusion models, which combine the variational/approximate-likelihood viewpoint with an iterative sampling procedure, currently dominate state-of-the-art image, video, and audio generation systems (e.g., large-scale text-to-image and text-to-video systems), and represent the natural next architecture built directly on the concepts introduced here.
Ask the tutor: How does the reparameterization trick make the ELBO differentiable with respect to the encoder's parameters?
What is the difference between a generative model and a discriminative model?
A generative model learns (an approximation to) the joint or marginal distribution of the data, or , and can therefore be used to sample new data or evaluate how likely a given input is. A discriminative model learns only the conditional needed to predict a label from an input, and typically cannot generate new 's or assess whether an input is unusual. Generative models are strictly attempting a harder problem — modeling the full data distribution — which is why they support tasks discriminative models cannot, like synthesis and anomaly detection, but they can also be more difficult to train well, especially in high dimensions with complex, multimodal distributions.
Why can't we always compute the exact likelihood for latent-variable models like VAEs?
The likelihood is , an integral over all possible latent values that explain . When is parameterized by a deep neural network, this integral has no closed form and cannot be computed by quadrature in reasonable time for continuous, high-dimensional . Instead, we introduce an approximate posterior and optimize the Evidence Lower Bound, which is tractable via Monte Carlo sampling and the reparameterization trick, and which is provably a lower bound on the true (unreachable) log-likelihood.
Are GANs strictly better than likelihood-based models because they produce sharper images?
Not strictly better — they trade one set of strengths for another. GANs often produce sharper, more realistic-looking samples partly because their adversarial loss does not penalize the generator for placing zero probability mass on regions of the true data distribution (a behavior related to mode-seeking vs. mode-covering divergences), whereas likelihood-based training tends to spread probability mass more conservatively to avoid catastrophically low likelihood on any training point. This can make GAN samples look crisper but at the cost of reduced diversity (mode collapse), unstable non-convex minimax training, and the complete absence of a usable density function for tasks like anomaly detection or exact model comparison.
What does "tractable likelihood" actually require architecturally?
For autoregressive models, tractability requires only that each conditional factor be a normalized distribution (e.g., softmax over discrete values, or a Gaussian/mixture density for continuous ones), so the chain-rule product is automatically a valid, normalized joint density. For normalizing flows, tractability requires the transformation to be invertible with a Jacobian whose determinant can be computed cheaply — typically enforced by restricting layers to triangular Jacobians (coupling layers, autoregressive flows), so the determinant reduces to a product of diagonal entries computable in rather than the generic cost of a dense determinant.
How does maximum likelihood estimation connect to the Kullback–Leibler divergence?
The KL divergence from the true data distribution to the model, , expands into the negative entropy of the data (a constant, independent of ) minus the expected log-likelihood under the model. Since the constant term doesn't affect optimization, minimizing this KL divergence over is exactly equivalent to maximizing , which is estimated in practice by the empirical average — the maximum likelihood objective. This equivalence is why MLE is often described as "distribution matching" rather than merely a statistical estimation heuristic.
Why does the adversarial training objective correspond to Jensen–Shannon divergence rather than KL divergence?
Substituting the Bayes-optimal discriminator back into the GAN value function algebraically reduces it to , a fact that follows directly from the definition of Jensen–Shannon divergence as an average of two KL divergences to the mixture distribution. This derivation, given in the original GAN paper, is what licenses calling GAN training "divergence minimization" despite never computing any density: the discriminator's role is precisely to make that divergence's gradient estimable through samples alone.
Which family should I use if I need exact density values, e.g., for anomaly detection?
Prefer autoregressive models or normalizing flows, since both provide an exact, computable for any input, letting you flag low-likelihood points as anomalies with a principled threshold. VAEs can approximate this with the ELBO, but since the ELBO is only a lower bound (with an unknown, input-dependent gap), likelihood-based anomaly scores derived from it can be biased or miscalibrated across different types of inputs. GANs are generally unsuitable for this task directly, since they provide no likelihood at all — anomaly detection with GANs typically requires auxiliary tricks like reconstruction error through an inverted generator, which is an indirect and less theoretically grounded proxy.