Latent diffusion: compression, scale and what a decoder cannot recover
潜空间扩散
Separate codec error from generation using a linear Gaussian baseline and explicit cross-attention dimensions.
latent-diffusionGenerate in a smaller space—but account for what was removed
A 256×256 RGB image contains 196,608 scalar values. A 32×32 representation with four channels contains 4,096: 48 times fewer scalars. That arithmetic is attractive, but a smaller representation is useful only if its decoder can recover the information the task needs.
Rombach and colleagues’ latent diffusion work, first posted in December 2021 and published at CVPR 2022, separates perceptual compression from generative modelling. An autoencoder first learns an image representation; a diffusion model then learns its distribution. This is a family of methods, not a synonym for every later Stable Diffusion release. Read autoencoders, DDPM and attention first.
Two stages, two different errors
Let the encoder E map an image to a spatial latent z, and let D reconstruct an image from that latent. A downsampling factor f reduces each spatial axis:
The factor f² counts spatial positions, not total scalar values. For f=8 and c=4 these ratios are 64 and 48 respectively. Neither is a measured end-to-end speedup: encoder, decoder, denoiser width, attention, hardware and number of sampling steps also matter.
Section 3.1 uses a perceptual reconstruction loss and a patch adversarial objective, with either mild KL regularization or a vector-quantization variant. Pure pixel MSE encourages a different notion of similarity. The paper’s two-dimensional latent is not automatically a flattened sequence of discrete tokens; in its VQ variant quantization is absorbed into the decoder.
Once the codec is trained, the diffusion stage corrupts encoded examples and predicts their noise:
The fixed author implementation freezes the first-stage model during this stage. A decoder that discarded a feature cannot be assumed to restore the particular feature that was present in the input. A learned decoder may produce plausible detail, but plausibility is different from recovering lost information.
Compression error can be measured by D(E(x)) on held-out images. Generative error concerns the distribution of sampled latents and decoded samples. Compare both: a perfect latent sampler can still inherit an inadequate codec, while excellent reconstructions do not establish that the latent generator covers the data distribution.
Latent scale changes the meaning of a noise schedule
Some implementations rescale encoded latents by a scalar k and undo that rescaling before decoding. For a centred latent coordinate with variance vz:
A scale constant belongs to a particular codec and training setup; it is not a universal definition of latent diffusion. The source supports a supplied factor or initial standard-deviation rescaling. One global variance normalization is also not whitening: different coordinates may retain different variances and correlations.
Queries come from the image features
A conditioning encoder produces M context tokens, while a denoiser layer has N spatial tokens. Using row-vector conventions, let H be N×dh and C be M×dc. A cross-attention layer uses:
Each spatial query chooses a weighted combination of context values. The rows sum to one; the number of output tokens stays N. These dimensions are derived for the stated row convention and cross-checked against the author attention implementation, rather than copied mechanically from a differently arranged formula. The paper’s conditional objective trains the denoiser together with an appropriate conditioning encoder; particular products can freeze or replace that encoder.
A linear codec exposes an irrecoverable error
Save as latent_diffusion.py with Python 3.12 and NumPy 1.26.4. This original four-dimensional Gaussian example fits the optimal population PCA subspace from a known covariance. It is an analytical linear compression baseline, not the paper’s perceptual autoencoder. The eigenvalues are 4, 1, .09 and .01; retaining the first two gives a directly checkable reconstruction error:
The code scales the retained coordinates, executes an exact Gaussian reverse chain in that latent space, decodes samples, and runs a small cross-attention calculation. Its denoiser is supplied analytically; no U-Net, perceptual loss, discriminator or image training is hidden behind an interface. Starting from the true terminal Gaussian deliberately isolates codec and scaling effects from terminal-prior mismatch.
For D-dimensional dense covariance, the population eigendecomposition costs O(D³); projecting N points to r dimensions costs O(NDr). The vectorized teaching chain takes O(TNr) time and O(Nr+Tr) storage. Cross-attention’s score and value products cost O(NMdk+NMdv), excluding projections, and a conventional materialized score matrix uses O(NM) storage per head. These are mechanism-specific costs, not a hardware benchmark.
"""Original population-PCA codec and exact Gaussian latent reverse chain."""
import json
import numpy as np
Q=np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]],float)/2
EIGEN=np.array([4.,1.,.09,.01]);MEAN=np.array([1.,-.5,.25,0.])
COV=(Q*EIGEN)@Q.T
def codec(rank=2):
if type(rank) is not int or not 1<=rank<=4:raise ValueError('Rank must be1..4.')
values,vectors=np.linalg.eigh(COV);order=np.argsort(values)[::-1][:rank]
basis=vectors[:,order];variance=values[order];scale=1/np.sqrt(variance.mean())
return basis,variance,float(scale)
def encode(x,rank=2):
x=np.asarray(x,float)
if x.ndim!=2 or x.shape[1]!=4 or not np.all(np.isfinite(x)):raise ValueError('Finite N by4 input required.')
basis,_,scale=codec(rank);return ((x-MEAN)@basis)*scale
def decode(z,rank=2,undo_scale=True):
basis,_,scale=codec(rank);z=np.asarray(z,float)
if z.ndim!=2 or z.shape[1]!=rank or not np.all(np.isfinite(z)):raise ValueError('Finite matching latent required.')
return (z/(scale if undo_scale else 1))@basis.T+MEAN
def latent_sample(count=16384,rank=2,seed=61):
if type(count) is not int or not 1<=count<=65536:raise ValueError('Count1..65536 required.')
_,v,scale=codec(rank);v=v*scale**2
beta=np.linspace(.01,.2,24);alpha=1-beta;a=np.cumprod(alpha);previous=np.r_[1,a[:-1]]
vt=a[:,None]*v+1-a[:,None];vp=previous[:,None]*v+1-previous[:,None]
rng=np.random.default_rng(seed);z=rng.normal(size=(count,rank))*np.sqrt(vt[-1])
# Exact Gaussian reverse conditionals, including the positive final variance.
for t in range(23,-1,-1):
z=z*(np.sqrt(alpha[t])*vp[t]/vt[t])+rng.normal(size=z.shape)*np.sqrt(beta[t]*vp[t]/vt[t])
return z
def attention(query,context,wq,wk,wv):
q=np.asarray(query)@wq;k=np.asarray(context)@wk;v=np.asarray(context)@wv
logits=q@k.T/np.sqrt(q.shape[1]);weights=np.exp(logits-logits.max(axis=1,keepdims=True));weights/=weights.sum(axis=1,keepdims=True)
return weights@v,weights
def demo():
basis,var,scale=codec();z=latent_sample();x=decode(z);projector=basis@basis.T
covariance=projector@COV@projector
rng=np.random.default_rng(3);query=rng.normal(size=(4,2));context=rng.normal(size=(3,5))
y,w=attention(query,context,rng.normal(size=(2,3)),rng.normal(size=(5,3)),rng.normal(size=(5,2)))
return dict(reconstruction_squared_error_by_rank={str(k):float(EIGEN[k:].sum()) for k in [1,2,3,4]},scale=scale,scaled_latent_variances=(var*scale**2).tolist(),decoded_covariance_eigenvalues=np.linalg.eigvalsh(covariance).tolist(),sample_mean=x.mean(axis=0).tolist(),sample_covariance_error=float(np.max(abs(np.cov(x,rowvar=False,bias=True)-covariance))),wrong_scale_covariance_multiplier=scale**2,spatial_reduction=8**2,element_reduction=(256*256*3)/(32*32*4),attention_shape=list(y.shape),attention_row_sums=w.sum(axis=1).tolist())
if __name__=='__main__':print(json.dumps(demo(),indent=2))
Ranks 1, 2, 3 and 4 give total squared reconstruction errors 1.1, .1, .01 and zero. At rank 2 the scalar normalization is .6324555320; the latent variances become 1.6 and .4, whose average is one. They have not both become one.
Even with the exact latent sampler, decoded covariance has only two nonzero eigenvalues, 4 and 1. The discarded .09 and .01 directions do not reappear. With 16,384 samples and seed 61, the maximum covariance-entry sampling error is about .03113. Forgetting to undo the scale multiplies centred decoded covariance by .4. The cross-attention example maps four image-feature tokens and three context tokens to four two-dimensional outputs, with normalized attention rows.
Compression is a task choice
Pixel errors, perceptual similarity and semantic usefulness need not agree. Text, small structures or other task-critical details can be damaged by a codec that works well on a different objective. Our PCA ordering makes lost variance explicit; it does not claim that low variance always means low perceptual importance.
Latent MSE is not generally pixel MSE, and a noninvertible codec does not provide an ordinary change-of-variables image likelihood. A diffusion model fitted to encoded training examples can also fail on unusual prompts or latent regions. Codec quality, conditioning, guidance, sampling and evaluation must be assessed together. The article covers the original method’s selected architecture, not the training data or capabilities of later named products.
Separate compression, scaling and generation
- Size. Why is the scalar reduction 48 rather than 64 in the opening example? Answer: Spatial area falls by 64, but channels rise from 3 to 4. The scalar ratio is 64·3/4=48; neither number alone is a runtime speedup.
- Hand calculation. What error remains with a perfect rank-two codec for eigenvalues 4, 1, .09 and .01? Answer: Total expected squared error .1, or .025 per original coordinate. It remains even if latent generation is exact.
- Boundary. Does a single scale giving average latent variance one whiten the latent? Answer: No. The example retains variances 1.6 and .4; whitening would normalize directions separately and address covariance.
- Method choice. Reconstructions are good but generated samples lack a class. Which stage should be investigated first? Answer: The latent distribution model, conditioning and sampling coverage, while checking codec performance on that class. Good average reconstructions alone cannot establish generative coverage.
Inspect the boundary between the two stages
Read Sections 3.1–3.3, then follow first-stage freezing, scaling and decoding and the cross-attention projections. The paper was read through its official v2 HTML; no claim is made of inspecting its full PDF, supplementary objective or image benchmarks. The original NumPy example is a transparent baseline for information loss, not a recreation of the authors’ image system.
Make a prediction, then check
Does exact latent sampling restore discarded codec directions?
Learning objectives
- Separate compression and distribution modelling.
- Derive spatial and scalar reduction ratios.
- Check latent scaling and decoding.
- Trace cross-attention dimensions.
Prerequisites & connections
Explore related knowledge →References
- High-Resolution Image Synthesis with Latent Diffusion Models (v2 HTML)
Robin Rombach; Andreas Blattmann; Dominik Lorenz; Patrick Esser; Björn Ommer · 2022 - ldm-stages method reference at a506df5
CompVis/latent-diffusion contributors · 2022 - ldm-attention method reference at a506df5
CompVis/latent-diffusion contributors · 2022
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked LDM v2 sections3.1-3.3 and fixed CompVis stage/scaling/cross-attention code. Six paired equations and four explained exercises; original population PCA codec and exact Gaussian latent reverse chain, rank error, scalar normalization, inverse-scale omission and attention dimensions. No perceptual autoencoder or image benchmark training.
- Single AI author checked LDM v2 sections3.1-3.3 and fixed CompVis stage/scaling/cross-attention code. Six paired equations and four explained exercises; original population PCA codec and exact Gaussian latent reverse chain, rank error, scalar normalization, inverse-scale omission and attention dimensions. No perceptual autoencoder or image benchmark training.
- Four computed SVG variants per topic. Eleven numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Mobile-title and cost-axis corrections preserved. Full article acceptance recorded separately.
Source locations checked:
- 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.
- ldm-stages method reference at a506df5 · Read 478-507,542-550,706-713: latent std scaling, frozen codec, scaled encoding and inverse scale. MIT license read. Fixed public commit; reference only, no copied/executed code.
- ldm-attention method reference at a506df5 · Read 152-191: query/context projections, head reshape, softmax rows and value product. MIT license read. Fixed public commit; reference only, no copied/executed code.
Related topics