Image Generation Fundamentals
Suppose you want a program that draws a face nobody has ever seen. It should still look entirely plausible. There is no formula for "faceness" to plug pixels into directly. Instead, the only tractable path is different. Treat a photograph as one sample from an enormous probability distribution over all possible images. Then teach a model to approximate that distribution well. It should draw new samples from it. This reframing — synthesis as sampling — is the conceptual foundation underneath every modern image generator. This includes the first variational autoencoders and today's diffusion models and adversarial networks. The problem is harder than it looks. Natural images live in an astronomically high-dimensional space. A modest 128×128 RGB image already has ~49,000 dimensions. Yet real images occupy only a thin, structured sliver of that space. This is the "manifold" of things that look like real photos, faces, or objects. A generative model must learn where that sliver is. It gets no explicit description of it. It has only a finite set of example images to work with. Getting this right matters enormously in practice. It underlies image super-resolution, inpainting, and data augmentation for rare classes. It also underlies synthetic training data for autonomous driving and deepfake detection research. Every text-to-image system currently deployed at scale relies on it too. This article builds the vocabulary and mathematics that every later generative model reuses. It covers what it means to model , and why we introduce latent variables . It explains how the decoder and encoder relate to each other. It also covers the fundamental trade-off between models. Some give you an explicit likelihood; others only let you draw samples. We work through two foundational architectures — autoregressive pixel models and the variational autoencoder (VAE). We go into enough algorithmic depth that you could implement a minimal version. We also derive the key inequality (the ELBO) that makes VAEs tractable at all. By the end, you will understand generative modeling differently. It is not a bag of architectures but a single unifying question. Given samples from an unknown , how do you build a model ? It should be easy to sample from. How do you fit so that ? Every later technique — Generative Adversarial Networks for Images and Diffusion Models for Images — answers exactly this question, each in a different way.
- Image generation = learning a probability distribution over pixel arrays and sampling from it, not hand-crafting rules.
- Latent variables compress an image's "content" into a low-dimensional code; a decoder maps image.
- Autoregressive models factor pixel-by-pixel via the chain rule — exact likelihood, but slow sampling.
- Variational autoencoders introduce an encoder and optimize a tractable lower bound (the ELBO) on the true likelihood.
- The reparameterization trick makes sampling differentiable, so the whole system trains end-to-end with backpropagation.
- These ideas — explicit density, latent bottleneck, sampling — set up everything GANs and diffusion models do differently.
Image generation is the problem of learning a sampler for an unknown distribution over pixels, usually by routing that distribution through a compact latent variable that a neural network can decode into an image.
The idea
A grayscale image of size can be viewed as a single point . A dataset of images is then a finite set of samples drawn (we assume) i.i.d. from some unknown, fixed distribution over that space. Generative modeling is the task of constructing a parametric distribution , using only these samples, such that is (a) close to in some useful sense and (b) easy to draw new samples from. This is fundamentally different from Convolutional Neural Networks used for discriminative tasks like classification, where the goal is for a small label set ; here the "label" space is the entire image itself. Because is supported on a thin, curved manifold inside a huge ambient space — most points in look like television static, not photographs — directly parameterizing with a simple distribution (like a single high-dimensional Gaussian) fails badly: it cannot represent the sharp, multi-modal, low-dimensional structure of real images. The standard fix is to introduce a latent variable , with , and to define the image distribution indirectly:
so that . The prior is chosen simple (typically an isotropic Gaussian, ), and all of the complexity of turning "a random low-dimensional code" into "a photorealistic image" is pushed into a learned decoder network . Sampling then reduces to drawing an easy Gaussian vector and pushing it through a neural network — trivial once trained. Two competing families answer the question "how do we fit so this actually works?" Autoregressive models avoid latent variables entirely and instead factor the image likelihood exactly via the chain rule of probability, pixel by pixel. Latent variable models such as the Variational Autoencoder introduce an auxiliary encoder that infers a plausible for each training image, and train encoder and decoder jointly by maximizing a tractable lower bound on the log-likelihood — the Evidence Lower Bound (ELBO). Both give an explicit, trainable density; both are the direct ancestors of the implicit-density approaches (GANs) and iterative-denoising approaches (diffusion) covered elsewhere.
How it works
Autoregressive factorization
Any joint distribution over pixels (raster-scan order, say) can be factored exactly, with no approximation, using the chain rule:
A model like PixelCNN/PixelRNN parameterizes each conditional with a neural network — masked convolutions ensure pixel 's prediction only looks at pixels already generated. Training maximizes the exact log-likelihood by teacher-forcing (feeding true pixel values as context, so training is one parallel forward pass). Sampling, however, must generate pixels strictly in order — sequential network evaluations per image. ```
# Training: exact log-likelihood, fully parallel over pixels function TRAIN_AUTOREGRESSIVE(images, theta): for batch in images: loss = 0 for i in 1..n: # can be vectorized, no sequential dependency context = batch[:, 1..i-1] # true pixels, teacher-forced p_i = NETWORK(context; theta) # predicted distribution over x_i loss += -log p_i[batch[:, i]] backprop(loss); update(theta)
# Sampling: inherently sequential, one pixel unlocks the next function SAMPLE_AUTOREGRESSIVE(theta, n): x = zeros(n) for i in 1..n: p_i = NETWORK(x[1..i-1]; theta) x[i] = draw_from(p_i) return x ```
Latent-variable models and the ELBO
For a latent-variable model, the marginal likelihood is an intractable integral over all of -space. We cannot compute it directly, and gradient ascent on an unknown quantity is impossible. The fix is to introduce an approximate posterior — an encoder network predicting, for each image , a distribution over plausible latents — and to derive a computable lower bound. Start from the (trivial) identity, for any distribution :
The KL term is (KL divergence is always non-negative), so the first term is a lower bound on — the ELBO:
Maximizing simultaneously increases the true likelihood (pushing the bound up) and tightens the bound (making the KL gap between and the true posterior smaller). Both terms are now computable: the reconstruction term is estimated by sampling and decoding; the KL term has a closed form when and are both Gaussian. The remaining obstacle is that is sampled, and backpropagating through a random sampling operation is undefined. The reparameterization trick rewrites the sample as a deterministic, differentiable function of plus external noise:
so gradients flow through normally, and the randomness is isolated in , which requires no gradient. ```
# VAE training step function TRAIN_VAE_STEP(x, phi, theta): mu, log_sigma2 = ENCODER(x; phi) # q_phi(z|x) = N(mu, diag(sigma^2)) epsilon = sample_standard_normal(dim(mu)) z = mu + exp(0.5 log_sigma2) epsilon # reparameterization trick x_hat = DECODER(z; theta) # p_theta(x|z) recon_loss = RECONSTRUCTION_ERROR(x, x_hat) # e.g. Gaussian NLL or BCE per pixel kl_loss = -0.5 * sum(1 + log_sigma2 - mu^2 - exp(log_sigma2)) # closed-form N||N KL loss = recon_loss + kl_loss # negative ELBO (minimize this) backprop(loss) update(phi, theta)
# Sampling new images after training: ignore the encoder entirely function SAMPLE_VAE(theta, d): z = sample_standard_normal(d) x = DECODER(z; theta) return x ```
Complexity & correctness
Autoregressive models. Training cost per image is conditional density evaluations, but because teacher forcing supplies ground-truth context, all predictions can be computed in a single masked-convolution forward pass — training time is work but effectively one parallel pass, i.e. wall-clock roughly sequential steps given enough parallel hardware. Sampling is fundamentally sequential: pixel needs pixels , so generating one image costs sequential network evaluations, each itself or more work depending on receptive field — a real bottleneck for large images (megapixel images can take seconds to minutes to sample). Space is for the running image buffer plus model parameters. Correctness is exact: the chain-rule factorization is an identity, not an approximation, so a perfectly trained autoregressive model recovers exactly in the limit of infinite capacity and data — there is no approximation gap, only estimation error from finite data and finite model capacity.
VAEs. Both training and sampling are network forward passes per image (one encoder pass, one decoder pass), independent of pixel count in terms of sequential steps — a huge sampling-speed advantage over autoregressive models. Space is dominated by the encoder/decoder parameters, , plus for the latent code, . The correctness argument for VAEs is the ELBO derivation itself, which is worth restating as an invariant: for any choice of , at any point during training,
This is not an approximation that might fail; it is an algebraic identity plus the fact that KL divergence is non-negative (itself a consequence of Jensen's inequality applied to the concave function). Gradient ascent on with respect to therefore always pushes a true lower bound on the data likelihood upward. Gradient ascent with respect to tightens the bound by shrinking the KL gap. The tradeoff is that maximizing a lower bound does not guarantee maximizing the true likelihood: if is a poor approximating family (e.g., forced to be Gaussian when the true posterior is multi-modal), the gap can remain large no matter how well are optimized, and samples tend to look characteristically blurry — the model hedges over multiple plausible modes rather than committing to one sharp explanation, because averaging over uncertainty in under a unimodal Gaussian encoder smooths the decoder's output distribution. Both families are honest densities: you can evaluate (or lower-bound) for a given image, unlike GANs, which give no likelihood at all. This is the key trade axis in generative modeling — exact/tractable likelihood versus sample sharpness/speed — that later architectures each resolve differently.
Worked example
Trace a tiny 1-D toy version of the VAE math on a single training image so every number is checkable by hand. Suppose the encoder for image outputs , (so ), and the prior is standard normal, .
Step 1 — KL term (closed form for two Gaussians):
Step 2 — reparameterized sample. Draw (fixed for reproducibility of this trace):
Step 3 — decode. Suppose the (linear, toy) decoder is , and the true pixel value (normalized to ) is .
Step 4 — reconstruction loss (mean squared error as a stand-in for Gaussian NLL):
Step 5 — total loss (negative ELBO) and gradient direction.
Here the reconstruction is already good, but the KL term dominates: the encoder's posterior is fairly confident (, close to the prior's ) but its mean is noticeably off-center from the prior's , and that mismatch is exactly what the KL penalizes. Backpropagating this loss pushes slightly toward (reducing KL) while also adjusting decoder weights to keep near (reducing reconstruction error) — the two loss terms compete, which is precisely the regularization/reconstruction tension that keeps the latent space smooth and sample-able rather than a lookup table of memorized codes.
| Quantity | Symbol | Value |
|---|---|---|
| Encoder mean | 0.600 | |
| Encoder log-variance | −0.500 | |
| Encoder std | 0.7788 | |
| Noise draw | 0.300 | |
| Latent sample | 0.8336 | |
| Decoded pixel | 0.7617 | |
| True pixel | 0.800 | |
| Reconstruction loss | — | 0.00147 |
| KL term | 0.2333 | |
| Total (negative ELBO) | 0.2348 |
At sampling time, after training, we discard the encoder entirely: draw fresh (say ), decode , and that is a brand-new synthetic pixel value produced with no reference image at all — the whole point of the exercise.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Blurry VAE samples | Unimodal Gaussian decoder averages over multiple plausible reconstructions | Use richer decoder likelihoods (mixture, autoregressive decoder), or accept the tradeoff and use adversarial/diffusion losses |
| Posterior collapse | KL term drives , decoder ignores entirely | KL annealing / warm-up, free-bits, weaker decoder capacity |
| Forgetting the reparameterization trick | Directly sampling inside the graph blocks gradient flow to | Always express as a deterministic function of noise and encoder outputs |
| Confusing with the ELBO | ELBO is only a lower bound; treating it as exact likelihood overstates model quality | Report the bound explicitly; remember the gap is |
| Pixel order bias in autoregressive models | Raster-scan order imposes an arbitrary causal structure absent in real images | Use multiple orderings, 2-D masked convolutions (PixelCNN), or attention-based context |
| Evaluating a GAN with autoregressive/VAE metrics | GANs have no tractable likelihood at all | Use sample-based scores (FID, precision/recall) instead of log-likelihood |
Pioneers & history
The mathematical machinery here — variational inference, the ELBO, and its use for training deep generative models with the reparameterization trick — was assembled from decades of Bayesian statistics but crystallized into the modern deep-learning form in the early 2010s.
Origins · 1 minDiederik P. Kingma and how this was discovered
Where this matters
Autoencoder-style latent bottlenecks are the backbone of modern image compression research, anomaly detection (an image that reconstructs poorly is likely out-of-distribution), and representation learning, where the latent code serves as a compact, semantically organized feature for downstream tasks. VAEs specifically power controllable image editing tools, where interpolating in latent space produces smooth morphs between images, and are used inside larger pipelines — notably as the compression stage of latent diffusion models, where a VAE encoder first shrinks an image into a smaller latent grid so the (much more expensive) diffusion process runs there instead of on raw pixels. Autoregressive pixel models inform speech synthesis (WaveNet) and are the direct conceptual ancestor of modern autoregressive text-to-image and token-based image generators, which model images as sequences of discrete visual tokens. Every large-scale text-to-image system in production today — used in design tools, game asset pipelines, synthetic data generation for robotics and autonomous driving, and creative software — traces its core sampling logic back to this same "sample , decode to " or "condition on pixels-so-far" template introduced here, elaborated on by Generative Adversarial Networks for Images (which replace explicit likelihood with an adversarial discriminator) and Diffusion Models for Images (which replace one-shot decoding with many small iterative denoising steps).
Ask the tutor: How does the ELBO objective change when the decoder likelihood is modeled as a mixture distribution instead of a single Gaussian, and why might that fix the blurriness problem?
Why can't we just fit a single high-dimensional Gaussian to model ?
A single Gaussian is unimodal and places most of its probability mass in a smooth blob around the mean, but real images form a highly curved, multi-modal, low-dimensional manifold within pixel space — a cat photo and a car photo are both "real" but very far apart, with almost all points between them looking like meaningless noise. A Gaussian fit to such data would assign high probability to blurry average-like images and to nonsensical interpolations, and low probability to sharp, structured real photos. Latent variable models solve this by keeping the prior on simple (a Gaussian is fine there) while letting a nonlinear decoder network warp that simple space into the complicated image manifold, which is where all the necessary complexity actually belongs.
What exactly is the "gap" between the ELBO and the true log-likelihood?
The gap equals , the KL divergence between your approximate encoder posterior and the true (usually intractable) posterior implied by the generative model itself. If your encoder family could represent the true posterior exactly, this gap would be zero and the ELBO would equal the true log-likelihood. In practice, encoders are restricted to simple families like diagonal Gaussians, so some gap always remains, meaning training via the ELBO always slightly underestimates how good the model's true likelihood could be, and creates pressure toward encoder distributions that are "easy" rather than maximally faithful.
How do autoregressive models and VAEs relate to each other conceptually?
Both give you an explicit, trainable probability density over images, but they factor that density differently. Autoregressive models factor exactly via the chain rule over pixels, with no latent variable and no approximation, at the cost of strictly sequential sampling. VAEs instead route the density through a compact latent and accept an approximation (the ELBO gap) in exchange for one-shot, highly parallel sampling. You can even combine them: some architectures use an autoregressive decoder inside the VAE framework, trading some sampling speed back for sharper reconstructions.
Why is the prior almost always chosen to be a simple isotropic Gaussian?
Choosing makes two things easy: sampling (drawing standard Gaussian noise is trivial and fast) and the KL regularization term in the ELBO, which has a clean closed form only when both and are Gaussian. The actual complexity needed to represent the image manifold is delegated entirely to the nonlinear decoder network, which learns to warp simple Gaussian noise into the highly structured space of realistic images. This division of labor — simple prior, complex decoder — is what keeps training and sampling computationally tractable.
Does a higher ELBO always mean better-looking generated images?
Not necessarily. The ELBO measures a bound on data likelihood under the model, and likelihood is not the same thing as human-perceived visual quality — a model can assign high likelihood to slightly blurry, "safe" average images while a sharper but riskier sample scores lower likelihood if it deviates from the training distribution's density estimate in certain ways. This mismatch between likelihood and perceptual quality is a known limitation of likelihood-based training and is part of the motivation for likelihood-free approaches like GANs, which directly optimize for sample realism as judged by a discriminator rather than for density estimation accuracy.
What does it mean for a generative model to be "likelihood-free," and how does that relate to what's covered here?
A likelihood-free model can produce samples but offers no way to compute or even lower-bound for a given image — you can draw from it but not score it. VAEs and autoregressive models are explicitly not likelihood-free: they are built precisely to give you a tractable (exact or bounded) density, which is why this article frames generation around in the first place. Generative Adversarial Networks are the classic likelihood-free counterpart, replacing density estimation with a discriminator-based training signal, trading interpretability of the likelihood for often sharper samples — a direct foreshadowing of the tradeoffs explored when studying GANs.
Why does the reparameterization trick require the noise to be independent of and ?
Backpropagation computes gradients by differentiating a deterministic computational graph; a stochastic sampling node has no well-defined derivative with respect to the parameters that produced its distribution. By rewriting with drawn from a fixed, parameter-free distribution, all the randomness is pushed into a leaf node that requires no gradient, while and become ordinary differentiable functions inside the graph. This is what allows a single backward pass to update both the encoder and decoder jointly using standard gradient-based optimizers.