AI Wiki中文/EN

Generative models: distributions, samples and the jobs between them

生成模型的分类

Compare model families and use exact small distributions to separate likelihood, coverage and sample validity.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Three 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.

Exact distributions, sample validity, finite and infinite losses, and a high-dimensional mixture separate the questions a generative model must answer.
Exact distributions, sample validity, finite and infinite losses, and a high-dimensional mixture separate the questions a generative model must answer.

Classify the computation you need

Probability, density and sampling

Let xx denote an observation and pθp_\theta a model with parameters θ\theta. For a finite discrete space X\mathcal X, each probability lies between zero and one and the probabilities sum to one. For a continuous variable, the density integrates to one instead:

pθ(x)≥0,∑x∈Xpθ(x)=1(discrete),∫pθ(x) dx=1(continuous).p_\theta(x)\ge0,\quad\sum_{x\in\mathcal X}p_\theta(x)=1\quad\text{(discrete)},\qquad\int p_\theta(x)\,dx=1\quad\text{(continuous)}.

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 zz and map it through a learned generator Gθ(z)G_\theta(z). This mapping can generate a sample without returning its normalized density. GAN construction, Section 3

Conditioning means modeling pθ(x∣c)p_\theta(x\mid c) for a supplied context cc, 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, p(c)p(c). 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

FamilyRepresentation and training ideaA question to ask before using it
AutoregressiveMultiply normalized conditional distributions; often optimize their log-likelihoodCan generation afford a sequence of dependent steps?
Latent-variable models, including VAEsIntroduce hidden zz and marginalize it; VAEs optimize a variational lower boundIs the reported objective the marginal likelihood or a bound?
Normalizing flowsTransform a simple continuous distribution invertibly and account for volume changeAre the inverse and Jacobian determinant tractable?
GANsTrain a noise-to-data generator against a discriminatorHow will coverage and downstream usefulness be measured?
Energy-based modelsAssign unnormalized scores and normalize over the spaceHow will the normalization or sampling problem be handled?
Score-based and diffusion modelsLearn information about gradients of noisy data log densities and construct a sampling processWhich 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 ∇xlog⁡p(x)\nabla_x\log p(x), 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 PP is known. The expected negative log-likelihood, in natural-log units called nats, satisfies

L(P,Q)=−∑xP(x)log⁡Q(x)=H(P)+DKL(P∥Q).\mathcal L(P,Q)=-\sum_xP(x)\log Q(x)=H(P)+D_{\mathrm{KL}}(P\Vert Q).

Here H(P)H(P) is entropy and DKL(P∥Q)D_{\mathrm{KL}}(P\Vert Q) is the forward KL divergence. Terms with P(x)=0P(x)=0 contribute zero. If some P(x)>0P(x)>0 but Q(x)=0Q(x)=0, 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 P(000)=P(111)=1/2P(000)=P(111)=1/2. Its entropy is log⁡2\log 2. Matching the three marginal probabilities with an independent model gives

Qind(x)=∏j=13(1/2)xj(1/2)1−xj=1/8.Q_{\mathrm{ind}}(x)=\prod_{j=1}^{3}(1/2)^{x_j}(1/2)^{1-x_j}=1/8.

The independent model’s cross-entropy is log⁡8\log 8, its KL gap is log⁡4\log 4, 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 z∈{1,…,K}z\in\{1,\ldots,K\} select a mixture component with weights πz≥0\pi_z\ge0 summing to one. Within component zz, let bit jj be Bernoulli with parameter θzj\theta_{zj}. For DD bits,

Qπ,θ(x)=∑z=1Kπz∏j=1Dθzjxj(1−θzj)1−xj.Q_{\pi,\theta}(x)=\sum_{z=1}^{K}\pi_z\prod_{j=1}^{D}\theta_{zj}^{x_j}(1-\theta_{zj})^{1-x_j}.

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 Qz(x)Q_z(x) denote the Bernoulli product within component zz. We fit the mixture using the exact weights P(x)P(x) rather than a sampled dataset. During the E-step, the responsibility rxzr_{xz} is the posterior probability of component zz for observation xx; czc_z is its total expected weight:

rxz=πzQz(x)∑k=1KπkQk(x),cz=∑xP(x)rxz.r_{xz}=\frac{\pi_z Q_z(x)}{\sum_{k=1}^K\pi_kQ_k(x)},\qquad c_z=\sum_xP(x)r_{xz}.

The following update requires cz>0c_z>0 for every component. Our positive initial weights and 0<ϵ<1/20<\epsilon<1/2 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 [ϵ,1−ϵ][\epsilon,1-\epsilon]:

πznew=cz,θzjnew=clip⁡ ⁣(∑xP(x)rxzxjcz,ϵ,1−ϵ).\pi_z^{\mathrm{new}}=c_z,\qquad\theta_{zj}^{\mathrm{new}}=\operatorname{clip}\!\left(\frac{\sum_xP(x)r_{xz}x_j}{c_z},\epsilon,1-\epsilon\right).

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 ϵ=0.4\epsilon=0.4. 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 V\mathcal V:

TV⁡(P,Q)=12∑x∣P(x)−Q(x)∣,Valid⁡(Q;V)=∑x∈VQ(x).\operatorname{TV}(P,Q)=\frac12\sum_x|P(x)-Q(x)|,\qquad\operatorname{Valid}(Q;\mathcal V)=\sum_{x\in\mathcal V}Q(x).

Here V={000,111}\mathcal V=\{000,111\}. A memorizer that always emits 000 has validity one and total variation one half. It assigns zero probability to 111, so its NLL under PP 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 PP, an arbitrary noise distribution UU, and 0<α≤10<\alpha\le1, define R=αP+(1−α)UR=\alpha P+(1-\alpha)U. Pointwise,

R(x)≥αP(x)⟹log⁡R(x)≥log⁡P(x)+log⁡α⟹L(P,R)−H(P)≤−log⁡α.R(x)\ge\alpha P(x)\quad\Longrightarrow\quad\log R(x)\ge\log P(x)+\log\alpha\quad\Longrightarrow\quad\mathcal L(P,R)-H(P)\le-\log\alpha.

Thus adding a large noise component costs at most −log⁡α-\log\alpha 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 D=128D=128, put PP equally on the two all-equal strings, set UU uniform over all strings, and use α=0.01\alpha=0.01. Then

R(0D)=R(1D)=α/2+(1−α)2−D,R({0D,1D})=α+(1−α)21−D.R(0^D)=R(1^D)=\alpha/2+(1-\alpha)2^{-D},\qquad R(\{0^D,1^D\})=\alpha+(1-\alpha)2^{1-D}.

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 ϵ=0.05\epsilon=0.05. 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 S=2DS=2^D states, KK components and TT EM updates, enumeration and fitting take approximately O(TSKD)O(TSKD) arithmetic work, with O(SD+SK)O(SD+SK) 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 21282^{128} 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

  1. 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 log⁡8\log 8 and entropy is log⁡2\log 2, so the gap is log⁡4\log 4. Inspecting one coordinate at a time cannot detect this failure.

  1. 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.

  1. 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 (0.75)3/[(0.75)3+(0.25)3]=27/28(0.75)^3/[(0.75)^3+(0.25)^3]=27/28. 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.

  1. A small score difference. For the 128-bit mixture with α=0.01\alpha=0.01, 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 log⁡(100)/128≈0.03598\log(100)/128\approx0.03598 nats per bit. The valid mass is 0.01+0.99 2−127≈0.010.01+0.99\,2^{-127}\approx0.01. 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?

Choose one answer

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

  1. Deep Learning, Chapter 20: distribution representations and autoregressive networks
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. A note on the evaluation of generative models (v3)
    Lucas Theis; Aäron van den Oord; Matthias Bethge · 2016
  3. 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
  4. CS236 Fall 2023: generative model syllabus
    Stanford CS236 course staff · 2023
  5. CS236 notes: latent variables and the variational bound
    Aditya Grover and course contributors
  6. CS236 notes: change of variables and normalizing flow representation
    Aditya Grover and course contributors
  7. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.