Text-to-image generation: conditional structure and sampling budgets
文本生成图像
Generate coherent finite images and separate conditional dependence from best-of-many selection.
text-to-imageA description selects a distribution
“Draw a horizontal line” leaves its height unspecified. A generator should be able to produce different valid heights while respecting orientation. Returning the average of all valid pictures can erase the line; drawing each pixel independently can scatter the ink. Both failures confuse a distribution of coherent images with independent local averages.
Text-to-image generation models visual outputs conditioned on language. The initial DALL-E paper models text and discrete image tokens autoregressively after learning a visual codebook. Latent diffusion instead denoises a compressed image representation under conditioning. These describe distinct routes through the task, not a single universal model or a history of every named product. Start with PixelCNN, latent diffusion and CLIP.
Conditioning must preserve dependencies
Let c be an encoded description and x an image. A conditional generator targets p(x|c). If an encoder converts images to discrete tokens z and a decoder maps tokens back to images, the conditional distribution can be expressed as:
Some decoders receive c and others do not. A lossy codec limits what can be recovered regardless of how accurately the token prior is modeled. This decomposition is a model definition; it does not assert that an approximate learned codec reproduces the real image distribution exactly.
An autoregressive prior factors the joint token law in a declared order:
Previous target tokens are supplied during teacher-forced training and sampled during generation. Causal masking must prevent access to future targets. DALL-E’s §2.1–2.2 uses a dVAE with a Gumbel-based relaxation, then fixes that codec and models text/image tokens jointly. Its weighted text/image training objective is more specific than the conditional negative log-likelihood written above; do not confuse its dVAE with a VQ-VAE simply because both produce discrete codes.
A diffusion route constructs noisy latents, learns a conditional denoiser, and runs a reverse sampler:
A common conditioning operation gives visual states the queries and text states the keys and values:
The noise schedule, prediction parameterization, conditioning interface and numerical sampler are separate choices. The LDM method provides a concrete compressed-space design. Stronger classifier-free guidance changes the effective generation rule; it does not merely make the same conditional distribution cheaper to sample.
Our finite example makes the dependency issue exact. There are eight 4×4 binary images: four horizontal rows and four vertical columns. Given “horizontal”, the true distribution is uniform over the four rows. For a pixel prefix h, the next-pixel probability comes from summing complete-image probabilities compatible with that prefix:
The denominator must be positive. A zero-mass prefix is outside the declared support; silently supplying a fallback probability would change the model. The calculation uses the model’s possible images, not a future pixel from a particular target image.
Under the horizontal condition every pixel has marginal probability 1/4 of being on. Nevertheless, treating those marginals independently almost never draws a valid row:
Matching each pixel’s frequency does not match image structure. Exact conditional ancestral sampling recovers the four coherent modes; a fixed mean image or independent-pixel sampler does not.
Sample every pixel under a finite conditional law
Save as text_to_image.py, using Python 3.12 and NumPy 1.26.4. The program declares the eight-image distribution, updates compatible probability mass after each sampled bit, checks the chain rule and measures an independent-pixel baseline. Prompts are a three-label vocabulary: horizontal, vertical and unspecified. This is an exact finite generator, not natural-language parsing, learned image synthesis or a pretrained-model call.
For B sampled images, L pixels and S support images, the vectorized sampler costs O(BLS) with O(BS+BL) working storage. Here L=16 and S=8. Enumerating support is infeasible for natural images; a learned autoregressive network or denoiser replaces that explicit table. Neural training, attention caches and codec cost are outside this finite example.
"""Original exact conditional autoregression over eight synthetic 4x4 bar images."""
import json
import numpy as np
def images():
rows=np.repeat(np.eye(4),4,axis=1).reshape(4,4,4)
return np.r_[rows,rows.transpose(0,2,1)].reshape(8,16).astype(int)
def probabilities(prompt):
if prompt not in ['horizontal','vertical','unspecified']:raise ValueError('Use the declared three-label vocabulary')
p=np.ones(8)/8
if prompt=='horizontal':p=np.r_[np.ones(4)/4,np.zeros(4)]
elif prompt=='vertical':p=np.r_[np.zeros(4),np.ones(4)/4]
return p
def next_probability(prefix,prompt):
prefix=np.asarray(prefix)
if prefix.ndim!=1 or len(prefix)>15 or not np.isin(prefix,[0,1]).all():raise ValueError('Binary prefix of at most15 pixels required')
x=images();p=probabilities(prompt);keep=np.all(x[:,:len(prefix)]==prefix,axis=1);weight=p*keep
if weight.sum()==0:raise ValueError('Prefix outside conditional support')
return float(weight@x[:,len(prefix)]/weight.sum())
def sequence_probability(bits,prompt):
bits=np.asarray(bits)
if bits.shape!=(16,) or not np.isin(bits,[0,1]).all():raise ValueError('A binary 4x4 image is required')
product=1.
for i,bit in enumerate(bits):
if product==0:return 0.
p=next_probability(bits[:i],prompt);product*=p if bit else 1-p
return float(product)
def sample(prompt,count=4096,seed=31):
probabilities(prompt)
if not isinstance(count,int) or isinstance(count,bool) or not 1<=count<=20000:raise ValueError('Invalid sample count')
rng=np.random.default_rng(seed);x=images();mass=np.broadcast_to(probabilities(prompt),(count,8)).copy();result=np.zeros((count,16),int)
for i in range(16):
p=(mass@x[:,i])/mass.sum(axis=1);bit=rng.random(count)<p;result[:,i]=bit;mass*=x[None,:,i]==bit[:,None]
return result
def independent_valid_mass(prompt):
p=probabilities(prompt);x=images();pixel=p@x;joint=np.prod(np.where(x==1,pixel,1-pixel),axis=1)
return float(joint[p>0].sum())
def reranked_orientation_probability(budget):
if not isinstance(budget,int) or isinstance(budget,bool) or not 1<=budget<=30:raise ValueError('Invalid candidate budget')
return 1-2.**(-budget)
def demo():
x=images();draws=sample('horizontal');counts=[int(np.all(draws==row,axis=1).sum()) for row in x]
return dict(images=x.reshape(8,4,4).tolist(),horizontal_sequence_probabilities=[sequence_probability(row,'horizontal') for row in x],sample_counts=counts,conditional_nll=float(np.log(4)),unconditional_nll=float(np.log(8)),independent_valid_mass=independent_valid_mass('horizontal'),perfect_orientation_reranker={str(k):reranked_orientation_probability(k) for k in [1,2,4,8]},scope='Exact finite conditional law and ancestral pixel sampler; prompt is a label lookup, not a natural-language encoder, learned transformer or diffusion model.')
if __name__=='__main__':print(json.dumps(demo(),indent=2))
With seed 31, 4,096 horizontal samples give row counts [1017,1035,1015,1029] and no vertical images. Each valid horizontal image has probability .25, conditional negative log-likelihood log(4)=1.386294, and unconditional negative log-likelihood log(8)=2.079442. The difference log(2) is the orientation information supplied by the prompt, not a gain measured on natural captions.
Candidate selection adds another budget. If an unconditional sampler produces the requested orientation with probability .5 and a perfect orientation checker selects a matching candidate whenever one exists among K independent draws:
The probabilities for budgets 1,2,4,8 are .5,.75,.9375,.99609375. This checker is perfect only by construction. DALL-E’s Figure 3 caption identifies its displayed examples as contrastively selected from 512 candidates; those visual comparisons are not a one-sample budget. Our formula explains the general selection effect without reproducing that experiment.
A coherent image may still disobey the request
A real description can bind colors to objects, specify counts or relations, and leave many details open. A model can draw plausible objects while mixing up which is red or what is left of what. Image realism, text agreement, diversity and preservation of rare constraints require separate evaluation. A learned similarity score is a proxy, not an exhaustive semantic specification.
Declare sampling steps, guidance scales, seed policy, resolution, number of candidates and ranking method. Compare baselines with equal budgets or report the budget difference. Test compositions absent from the evaluation examples rather than inferring composition from separate object recognition. A split that leaks near-duplicate images can misrepresent novelty.
The eight-image table cannot generate an unseen kind of shape. Its exact support and perfect orientation checker make arithmetic transparent while excluding the hard learning problem. For changing an existing image rather than drawing a fresh one, see generative image editing; for an additional spatial condition, see ControlNet.
Distinguish marginal pixels, modes and budgets
- Calculation. What is the probability that the first pixel is on given “horizontal”, and what is the second pixel’s probability after observing that first pixel on? Answer: Initially .25. The first on pixel identifies the top row, so the next pixel is on with probability one. Under “vertical”, the same prefix identifies the left column and the next pixel is off.
- Prediction. Why does the independent-pixel baseline have the correct brightness at each location but almost no valid images? Answer: It preserves single-pixel marginals while discarding the dependence that turns four on pixels into one whole row. Its valid mass is only about .000495.
- Boundary. The conditional table assigns zero mass to an all-on image. What should its sequence probability be? Answer: Zero. Once an incompatible next bit has zero probability, the full product is zero; the sampler must not invent probability for an impossible prefix.
- Transfer. A reranked system gets .9375 orientation success. Can it claim that its underlying generator improved over a .5 baseline? Answer: Not from that number alone. Four independent baseline draws plus a perfect checker already give 1−(.5)⁴=.9375. Separate model changes from candidate-budget and selection changes.
Read the codec, conditional model and selection rule separately
The DALL-E paper’s §2.1–2.2 and Figure 3 support the discrete-token route and its stated selection budget; PDF page 3 was visually checked. The LDM v2 method sections support the compressed diffusion route, reusing the precise source version and limited reading already recorded in the preceding group. The pixel generator, calculations and exercises are original; neither paper’s image benchmark was reproduced.
Make a prediction, then check
Do correct independent pixel marginals guarantee a coherent image?
Learning objectives
- Factor a conditional visual distribution.
- Compare autoregression and diffusion interfaces.
- Explain why correct pixel marginals are insufficient.
- Account for candidate-selection budgets.
Prerequisites & connections
Explore related knowledge →References
- Zero-Shot Text-to-Image Generation (ICML2021)
Aditya Ramesh; Mikhail Pavlov; Gabriel Goh; Scott Gray; Chelsea Voss; Alec Radford; Mark Chen; Ilya Sutskever · 2021 - High-Resolution Image Synthesis with Latent Diffusion Models (v2 HTML)
Robin Rombach; Andreas Blattmann; Dominik Lorenz; Patrick Esser; Björn Ommer · 2022
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked DALL-E2021 selected section2/2.1/2.2 and best-of512 caption; reused the unchanged LDM v2 source and previously read method sections. Seven paired equations and four explained exercises; original eight-image exact autoregressive oracle, chain rule, impossible prefixes, seeded sampling, pixel-marginal failure and independently enumerated candidate selection. Three labels are not natural-language understanding or neural image training.
- Single AI author checked DALL-E2021 selected section2/2.1/2.2 and best-of512 caption; reused the unchanged LDM v2 source and previously read method sections. Seven paired equations and four explained exercises; original eight-image exact autoregressive oracle, chain rule, impossible prefixes, seeded sampling, pixel-marginal failure and independently enumerated candidate selection. Three labels are not natural-language understanding or neural image training.
- Four computed SVG variants per topic. Thirteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. English spacing correction and initial test-mixin discovery error preserved. Full article acceptance recorded separately.
Source locations checked:
- Zero-Shot Text-to-Image Generation (ICML2021) · Read selected2/2.1/2.2: dVAE Gumbel relaxation, fixed codec and autoregressive prior; Figure3 best-of512 caption and PDF page3 viewed. No image benchmark reproduction.
- High-Resolution Image Synthesis with Latent Diffusion Models (v2 HTML) · Read official HTML Sections3.1-3.3 compression, latent objective and cross-attention. First2021-12-20; read v2 dated2022-04-13, CVPR2022. No PDF/full supplement or benchmark review. Projection dimensions independently derived.
Related topics