Latent Diffusion Models: Mathematical Foundation
Latent Diffusion Models (LDMs) combine autoencoders with diffusion models to generate high-quality images efficiently. Here's the math:
1. Autoencoder Component
First, LDMs compress the input data into a lower-dimensional latent space:
- Encoder: z=E(x) where x∈RH×W×3 is an image and z∈Rh×w×c is its latent representation
- Decoder: x^=D(z) reconstructs the image
- Training objective: LAE=∥x−D(E(x))∥2 plus perceptual losses
2. Forward Diffusion Process
The diffusion process gradually adds noise to the latent representation:
- Start with z0=z (clean latent)
- For timesteps t=1,...,T: where
3. Reverse Diffusion Process
The model learns to denoise by reversing the process:
- Parameterize: pθ(zt−1
4. Training Objective
The model is trained to predict the noise:
Ldiffusion=E
For conditional generation (e.g., text-to-image), the objective becomes:
Ldiffusion=E
where c is the conditioning information (e.g., text embedding).
# Simplified sampling algorithm
def sample(model, condition=None, steps=1000):
z_t = torch.randn(batch_size, latent_dim) # Start with noise
for t in reversed(range(1, steps+1)):
# Predict noise
noise_pred = model(z_t, t, condition)
# Calculate mean for reverse step
alpha_t = alphas[t]
alpha_prev = alphas[t-1] if t > 1 else 1.0
# One denoising step
z_t = denoise_step(z_t, noise_pred, alpha_t, alpha_prev)
# Add noise if t > 1
if t > 1:
z_t += noise_scale * torch.randn_like(z_t)
# Decode the latent representation to get image
return decoder(z_t)
Would you like me to explain or break down the code?