Generative models: distributions, samples and the jobs between them
生成模型的分类
Compare model families and use exact small distributions to separate likelihood, coverage and sample validity.
generative-modelsThree fair bits can still make the wrong patterns
Suppose a device emits either 000 or 111, equally often. A model notices that each position contains 1 in half of the observations, then samples three independent fair bits. Every position has the right marginal frequency. Yet six of its eight possible outputs never occur in the device. Learning how parts vary together is central to generative modeling.
A generative model represents a distribution over possible observations. Depending on its construction, we may be able to draw samples, evaluate probabilities or densities, infer hidden variables, or complete an observation given a condition. These operations have different computational costs; supporting one does not automatically make the others easy. The opening of Deep Learning, Chapter 20, makes this distinction between explicit distribution evaluation and operations such as sampling. Distribution representations
Our three-bit example is small enough to enumerate completely. We will compare an independent model, a latent-variable mixture and a model that memorizes only one valid output. The comparisons separate distribution fit, coverage and a declared validity rule without asking a reader to judge generated images by appearance.
Classify the computation you need
Probability, density and sampling
Let denote an observation and a model with parameters . For a finite discrete space , each probability lies between zero and one and the probabilities sum to one. For a continuous variable, the density integrates to one instead:
A uniform distribution on an interval of width 0.1 has density 10 there. The interval has probability one; any single point has probability zero. Comparing raw density numbers across different units or different data encodings is therefore hazardous. The program records this elementary example as analytic constants, not as a numerical integration experiment.
Sampling specifies how randomness becomes an observation. In a mixture, draw a component and then its observation. In an autoregressive model, draw successive coordinates from conditional distributions. In the original GAN construction, draw noise and map it through a learned generator . This mapping can generate a sample without returning its normalized density. GAN construction, Section 3
Conditioning means modeling for a supplied context , such as a text prompt, a class label or observed image pixels. A model of that conditional need not also model the frequency of contexts, . State which object you learned before interpreting a likelihood or comparing systems.
A map of the main families
The families below organize assumptions and computational tradeoffs. They overlap: a latent-variable model can use an autoregressive decoder, for example. Stanford CS236 covers these families as separate routes through the same probabilistic problem. Course coverage
| Family | Representation and training idea | A question to ask before using it |
|---|---|---|
| Autoregressive | Multiply normalized conditional distributions; often optimize their log-likelihood | Can generation afford a sequence of dependent steps? |
| Latent-variable models, including VAEs | Introduce hidden and marginalize it; VAEs optimize a variational lower bound | Is the reported objective the marginal likelihood or a bound? |
| Normalizing flows | Transform a simple continuous distribution invertibly and account for volume change | Are the inverse and Jacobian determinant tractable? |
| GANs | Train a noise-to-data generator against a discriminator | How will coverage and downstream usefulness be measured? |
| Energy-based models | Assign unnormalized scores and normalize over the space | How will the normalization or sampling problem be handled? |
| Score-based and diffusion models | Learn information about gradients of noisy data log densities and construct a sampling process | Which noise schedule, solver and step count produced the result? |
For the standard continuous flow change-of-variables construction, input and output have equal dimension, the transformation is invertible, and density evaluation includes an absolute Jacobian determinant. More general constructions require their own conditions. Flow representation and change of variables
For a VAE, the inference distribution approximates a latent posterior; the ELBO falls below the marginal log-likelihood by a posterior KL gap under its stated support conditions. A good lower-bound value is not an exact likelihood computation. Latent variables and variational bound
A score is a vector field approximating , rather than a scalar density value. Song’s account explains score matching, problems in low-density regions, and training across multiple noise scales before sampling. This is a guide to what the model learns, not a claim that every sampler has identical behavior. Scores, sampling and noise scales
The table is a navigation map. Our executable comparison below implements finite distributions and a small mixture; it does not train these six neural model families. The diffusion article and neural energy-model article develop their own mechanisms.
What maximum likelihood actually rewards
Assume for now that the true finite distribution is known. The expected negative log-likelihood, in natural-log units called nats, satisfies
Here is entropy and is the forward KL divergence. Terms with contribute zero. If some but , the cross-entropy and KL are infinite. With a dataset, an empirical average estimates the expectation; fitting that average does not itself establish generalization. See maximum likelihood for this distinction.
In our example . Its entropy is . Matching the three marginal probabilities with an independent model gives
The independent model’s cross-entropy is , its KL gap is , and only one quarter of its outputs satisfy the all-equal rule. Correct marginals leave the dependence between coordinates unspecified.
A hidden component restores dependence
Let select a mixture component with weights summing to one. Within component , let bit be Bernoulli with parameter . For bits,
Each component is normalized, so the weighted mixture is normalized. Bits are independent given the component, but need not be independent after summing over it. With equal weights and all three component parameters set to 0.1 or 0.9, each endpoint receives 0.365 and each of the other six states receives 0.045.
Let denote the Bernoulli product within component . We fit the mixture using the exact weights rather than a sampled dataset. During the E-step, the responsibility is the posterior probability of component for observation ; is its total expected weight:
The following update requires for every component. Our positive initial weights and keep the component probabilities and expected weights positive. The M-step updates the weights and the expected bit frequencies. In this teaching implementation, each bit parameter is constrained to :
For fixed responsibilities, the Bernoulli log objective is concave in each bit parameter; clipping its unconstrained optimum gives the optimum within that interval. Starting from feasible parameters, these E/M steps do not decrease the objective in exact arithmetic. They can reach a local optimum and do not certify the best mixture globally. The EM article develops the underlying bound.
The initial parameters must obey the same constraint. For example, initial values 0.25 and 0.75 are outside the allowed box when . Our code clips the initialization as well as subsequent updates; a test exposed the missing initial projection in an earlier draft of the program.
Compare distribution error with a declared sample rule
Total variation compares the whole finite distributions, while validity depends on a chosen subset :
Here . A memorizer that always emits 000 has validity one and total variation one half. It assigns zero probability to 111, so its NLL under is infinite. A rule checker can approve every sample while the model omits an entire mode.
Likelihood and sample quality can also separate in high dimensions. For a good distribution , an arbitrary noise distribution , and , define . Pointwise,
Thus adding a large noise component costs at most nats per observation, or that value divided by dimension when reporting a per-coordinate score. This is the mixture argument discussed by Theis and colleagues; it does not say that likelihood is useless. It says to measure the property the application needs. Mixture counterexample, Equations 11–12
For an exact binary illustration, take , put equally on the two all-equal strings, set uniform over all strings, and use . Then
The all-equal sample mass is about 0.01, while the extra NLL per coordinate is about 0.03598 nats. Choosing the noise component 99% of the time is not identical to producing an invalid string 99% of the time: the noise component can also emit either valid endpoint, with a very small probability. These are invented binary rules, not measurements of human visual preference.
Enumerate every outcome before scaling up
Save the following complete program as generative.py and run it with Python 3.12 and NumPy 1.26.4. It needs no data download, network connection or pretrained weights. The state order is binary lexicographic order, from 000 through 111.
"""Original finite-distribution laboratory; NumPy only, no learned media model."""
import itertools,json
import numpy as np
def states(d=3):
if type(d) is not int or not 1<=d<=10:raise ValueError('Use one to ten binary variables')
return np.array(list(itertools.product([0,1],repeat=d)),float)
def probabilities(p,size=None):
a=np.asarray(p)
if a.dtype.kind not in 'fiu' or a.ndim!=1 or not 1<=len(a)<=1024 or (size is not None and len(a)!=size) or not np.isfinite(a).all() or np.any(a<0) or not np.isclose(a.sum(),1,atol=1e-12,rtol=0):raise ValueError('Use a finite normalized nonnegative probability vector')
return a.astype(float)
def bernoulli(theta):
t=np.asarray(theta)
if t.dtype.kind not in 'fiu' or t.ndim!=1 or not 1<=len(t)<=10 or not np.isfinite(t).all() or np.any((t<0)|(t>1)):raise ValueError('Invalid Bernoulli parameters')
x=states(len(t));return np.prod(np.where(x==1,t,1-t),axis=1)
def independent(p,d=3):
x=states(d);p=probabilities(p,len(x));return bernoulli(p@x)
def mixture(weights,theta):
w=probabilities(weights);t=np.asarray(theta)
if t.ndim!=2 or t.shape[0]!=len(w) or not 1<=len(w)<=8:raise ValueError('Use up to eight aligned mixture components')
components=np.array([bernoulli(row) for row in t]);return w@components
def metrics(p,q,valid):
p=probabilities(p);q=probabilities(q,len(p));v=np.asarray(valid)
if v.dtype.kind!='b' or v.shape!=p.shape:raise ValueError('An explicit boolean validity label is required')
positive=p>0;missing=positive&(q==0);entropy=float(-p[positive]@np.log(p[positive]))
nll=None if missing.any() else float(-p[positive]@np.log(q[positive]))
return dict(nll=nll,kl=None if nll is None else nll-entropy,entropy=entropy,total_variation=float(abs(p-q).sum()/2),valid_mass=float(q[v].sum()),support_failure=bool(missing.any()))
def fit_mixture(p,d=3,steps=40,floor=.05):
x=states(d);p=probabilities(p,len(x))
if type(steps) is not int or not 0<=steps<=200 or type(floor) not in (int,float) or not .001<=floor<.5:raise ValueError('Invalid constrained EM settings')
w=np.array([.5,.5]);t=np.clip(np.array([np.full(d,.25),np.full(d,.75)]),floor,1-floor);history=[]
for step in range(steps+1):
component=np.array([bernoulli(row) for row in t]);joint=component*w[:,None];q=joint.sum(axis=0)
history.append(float(-p@np.log(q)))
if step==steps:break
responsibility=(joint/q).T;counts=(p[:,None]*responsibility).sum(axis=0)
t=np.clip((responsibility.T@(p[:,None]*x))/counts[:,None],floor,1-floor)
w=counts/counts.sum()
return dict(weights=w,theta=t,distribution=mixture(w,t),history=history)
def sample(q,count=2000,seed=17):
q=probabilities(q)
if type(count) is not int or not 1<=count<=20000 or type(seed) is not int or not 0<=seed<2**32:raise ValueError('Invalid sampling bounds')
ids=np.random.default_rng(seed).choice(len(q),size=count,p=q);return np.bincount(ids,minlength=len(q))/count
def high_dimensional_mix(d=128,alpha=.01):
if type(d) is not int or not 2<=d<=1024 or type(alpha) not in (int,float) or not 0<alpha<=1:raise ValueError('Invalid mixture settings')
# True distribution: equal mass on all-zero and all-one strings.
# Noise component: uniform over all 2**d strings; compute analytically.
endpoint=alpha*.5+(1-alpha)*2.**(-d)
return dict(dimension=d,good_component_probability=alpha,valid_sample_mass=2*endpoint,nll=-np.log(endpoint),excess_nll_per_dimension=(-np.log(endpoint)-np.log(2))/d,bound_per_dimension=-np.log(alpha)/d)
def clean(value):
if isinstance(value,dict):return {k:clean(v) for k,v in value.items()}
if isinstance(value,(list,tuple)):return [clean(v) for v in value]
if isinstance(value,np.ndarray):return value.tolist()
if isinstance(value,np.generic):return value.item()
return value
def demo():
x=states();p=np.zeros(8);p[[0,7]]=.5;valid=(x.sum(axis=1)==0)|(x.sum(axis=1)==3)
fitted=fit_mixture(p);q=independent(p);memorizer=np.eye(8)[0]
models={'truth':p,'independent':q,'latent_mixture':fitted['distribution'],'memorizer':memorizer}
return clean(dict(states=x,truth=p,models=models,metrics={k:metrics(p,v,valid) for k,v in models.items()},mixture=fitted,sampled=sample(fitted['distribution']),high_dimensional=high_dimensional_mix(),density_example=dict(interval_width=.1,density=10.,interval_mass=1.,single_point_mass=0.),scope='Exact invented binary distribution and constrained two-component EM; validity means all bits equal, not visual quality. No real-data benchmark.'))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The default constrained EM run uses two components, 40 updates and . Its first update already reaches the constrained endpoint solution: component parameters 0.05 and 0.95 with equal weights. Further identical updates do not count as further improvement. Each valid endpoint receives 0.42875, total valid mass is 0.8575, and NLL is approximately 0.8468813, compared with 2.0794415 for the independent model.
The memorizer’s nll and kl are null in JSON, accompanied by support_failure: true. This encoding means that there is no finite result because the model misses positive true probability. Plotting either value as zero would reverse the conclusion. The sampled field is a seeded empirical histogram; the exact distribution remains the reference.
For states, components and EM updates, enumeration and fitting take approximately arithmetic work, with main working arrays. The code caps dimension at ten and components at eight. These bounds make the example inspectable; the exponential state space is precisely why realistic generative models need structure. The 128-dimensional counterexample is computed analytically and never allocates states.
Choose a model around the job
For a tiny categorical space, start with empirical counts and a documented smoothing rule. For structured data, compare an independent baseline with one that captures the dependencies relevant to the task. A learned model should earn its complexity through evidence: held-out distribution fit, coverage of important cases, conditional behavior, resource use or usefulness in a specified application.
Data representation is part of the model. Pixels, tokens, waveforms and latent codes change the sample space and the meaning of a likelihood. Conditioning, length normalization and dequantization also change what is being scored. Report those choices before comparing numbers across systems.
Our experiment knows the true distribution and trains on its exact weights. It isolates mechanisms but tests no real-world generalization. A finite model’s validity rule does not stand in for semantic correctness, originality, privacy or usefulness. Real evaluations need appropriate test data and separate checks for those requirements.
Predict a failure before running the code
- Correct marginals, wrong joint. Why does the independent three-bit model generate a valid string only one quarter of the time? What is its forward KL gap?
Answer: It gives all eight strings probability 1/8, and only 000 and 111 are valid. Their total is 2/8. Under the true distribution, the NLL is and entropy is , so the gap is . Inspecting one coordinate at a time cannot detect this failure.
- A perfect-looking memorizer. A model always emits 000. Compute validity, total variation and the behavior of NLL under the true distribution.
Answer: Validity is one. Half the true mass must move from 111 to 000, so total variation is one half. The model gives 111 zero probability despite its true mass of one half, making NLL infinite. The program records null together with a support-failure flag, not a zero loss.
- A constrained mixture update. With equal component weights and bit parameters 0.25/0.75, what responsibility does the lower-parameter component receive at 000? Why does the default next bit parameter become 0.05?
Answer: Its posterior weight is . By symmetry its expected one-frequency is 1/28. This is below the lower bound 0.05, so the constrained optimum is 0.05. The other component reaches 0.95; starting outside a tighter box must be corrected before invoking the monotonicity argument.
- A small score difference. For the 128-bit mixture with , bound the extra NLL per bit and estimate the probability of a valid sample. Does one number determine the other for arbitrary models?
Answer: The bound is nats per bit. The valid mass is . This construction demonstrates separation; it does not provide a universal conversion from a likelihood difference into a validity rate.
Follow the assumptions into the next family
The next step is to select which difficult operation a model makes manageable. Autoregressive factorization makes a joint probability accessible through conditionals. Latent-variable models make hidden structure explicit while introducing marginalization. Flows impose invertibility to keep track of density. GAN and score-based routes give different training and sampling constructions. Read each method together with its inference cost and evaluation protocol.
The sources below support the specified overview claims; the small distribution, derivations and code are original teaching examples. The course syllabus calibrates coverage, while the cited method notes and papers support the individual mechanisms. No course figures, assignments, upstream code or model weights are reproduced.
Make a prediction, then check
A model always generates a valid training pattern. Must its likelihood be good?
Learning objectives
- Distinguish probability evaluation, density, sampling and conditioning.
- Compare six model families by representation and computational tradeoffs.
- Derive and test a constrained Bernoulli-mixture update.
- Construct examples separating likelihood, coverage and validity.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning, Chapter 20: distribution representations and autoregressive networks
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - A note on the evaluation of generative models (v3)
Lucas Theis; Aäron van den Oord; Matthias Bethge · 2016 - Generative Adversarial Nets (v1): sampling construction
Ian J. Goodfellow; Jean Pouget-Abadie; Mehdi Mirza; Bing Xu; David Warde-Farley; Sherjil Ozair; Aaron Courville; Yoshua Bengio · 2014 - CS236 Fall 2023: generative model syllabus
Stanford CS236 course staff · 2023 - CS236 notes: latent variables and the variational bound
Aditya Grover and course contributors - CS236 notes: change of variables and normalizing flow representation
Aditya Grover and course contributors - Generative Modeling by Estimating Gradients of the Data Distribution
Yang Song · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked scoped textbook, GAN and Theis mixture arguments plus VAE/flow/score author notes. Nine paired equations and four explained exercises; original exact binary distributions, constrained EM, support failure and likelihood/validity counterexamples. Six-family overview does not claim six implementations or real-data performance.
- Verified rational independent-product probabilities, NLL/KL/TV, support-failure None semantics, constrained EM feasibility and first update, and analytic128-bit mixture bound. Four bilingual explained exercises match actual results.
- Four computed SVGs bind exact bilingual MDX. The two-topic group passed11 numeric/encoding checks and12 isolated language/width cases with four fallback fonts; four representative final screenshots inspected by the AI author. English mobile title overflow corrected with original figures and failed browser evidence preserved. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- Deep Learning, Chapter 20: distribution representations and autoregressive networks · Read chapter opening, Section20.10 introduction and20.10.7; current HTML is not a historical cutoff snapshot. Not the full chapter or its figures.
- A note on the evaluation of generative models (v3) · Read abstract/introduction opening and Section3.2 mixture argument, Equations10–12; inspected PDF page5. v3 dated2016-04-24, first2015-11-05. No image experiment or full Parzen evaluation replicated.
- Generative Adversarial Nets (v1): sampling construction · Read selected Section2 categorization and Section3 generator mapping/objectives; inspected PDF page2. First version2014-06-10; no convergence proof or benchmark replication.
- CS236 Fall 2023: generative model syllabus · Read lecture topic rows as a coverage map only; no slides, videos or assignment solutions inspected.
- CS236 notes: latent variables and the variational bound · Read Representation and Learning Directed Latent Variable Models through the ELBO/posterior-gap explanation (web lines26–107). No full gradient-estimation or implementation review; figures not reused.
- CS236 notes: change of variables and normalizing flow representation · Read change-of-variables definition and standard flow requirements (web lines11–56), not all later architectures or experimental claims.
- Generative Modeling by Estimating Gradients of the Data Distribution · Read score matching/Langevin, low-density pitfalls and multiple-noise-scale introduction (web lines58–90). No later SDE/ODE likelihood derivation or image experiments reviewed.
Related topics