πŸ€– AI/ML

VAE

Variational Autoencoder (VAE)

A generative model that learns a probabilistic latent space. A deep learning architecture used for image generation, representation learning, and data compression.

πŸ“– Detailed Explanation

VAE (Variational Autoencoder) is a generative model that learns a latent representation of data probabilistically. Proposed by Kingma and Welling in 2013, this model combines a probabilistic approach with the traditional autoencoder, giving it the ability to generate new data rather than merely compress it. In a VAE, the Encoder encodes the input as a probability distribution (mean and variance) in the latent space, and the Decoder samples from this distribution to reconstruct the data.

The core of a VAE lies in its loss function. It consists of two terms: the Reconstruction Loss and the KL Divergence (Kullback-Leibler Divergence). The reconstruction loss minimizes the difference between input and output to ensure information is preserved, and the KL divergence regularizes the learned latent distribution so that it approaches the standard normal distribution. Thanks to this regularization, the latent space has a continuous and meaningful structure, so valid data can be generated even when sampling from an arbitrary point.

In practice, VAEs are used for image generation, anomaly detection, data augmentation, feature learning, and more. In particular, they are used as a key component of modern image generation models such as Stable Diffusion, enabling high-resolution images to be processed efficiently in a low-dimensional latent space. In the medical field, the reconstruction error of a VAE trained on normal data is used to detect abnormal (disease) patterns.

Variants of the VAE include Beta-VAE (learning interpretable latent variables), Conditional VAE (conditional generation), and VQ-VAE (discrete latent space). Compared with a GAN (Generative Adversarial Network), a VAE trains stably and its latent space is easier to interpret, but the generated images tend to be somewhat blurry. Recently, Latent Diffusion, which combines a VAE with a Diffusion Model, has become the standard for image generation.

πŸ’» Code Example

VAE model and training code implemented in PyTorch:

Python
# VAE (Variational Autoencoder) PyTorch κ΅¬ν˜„
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt

class VAE(nn.Module):
    """Variational Autoencoder"""

    def __init__(self, input_dim=784, hidden_dim=400, latent_dim=20):
        super(VAE, self).__init__()

        self.latent_dim = latent_dim

        # Encoder: μž…λ ₯ -> 잠재 λΆ„ν¬μ˜ 평균과 λΆ„μ‚°
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim // 2),
            nn.ReLU()
        )

        # 잠재 뢄포 νŒŒλΌλ―Έν„°
        self.fc_mu = nn.Linear(hidden_dim // 2, latent_dim)      # 평균
        self.fc_logvar = nn.Linear(hidden_dim // 2, latent_dim)  # 둜그 λΆ„μ‚°

        # Decoder: 잠재 벑터 -> μž¬κ΅¬μ„±λœ μž…λ ₯
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, hidden_dim // 2),
            nn.ReLU(),
            nn.Linear(hidden_dim // 2, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, input_dim),
            nn.Sigmoid()  # 0-1 λ²”μœ„λ‘œ 좜λ ₯
        )

    def encode(self, x):
        """μž…λ ₯을 잠재 λΆ„ν¬μ˜ νŒŒλΌλ―Έν„°λ‘œ 인코딩"""
        h = self.encoder(x)
        mu = self.fc_mu(h)
        logvar = self.fc_logvar(h)
        return mu, logvar

    def reparameterize(self, mu, logvar):
        """
        Reparameterization Trick
        z = mu + std * epsilon ν˜•νƒœλ‘œ μƒ˜ν”Œλ§ν•˜μ—¬ μ—­μ „νŒŒ κ°€λŠ₯ν•˜κ²Œ 함
        """
        std = torch.exp(0.5 * logvar)
        epsilon = torch.randn_like(std)  # ν‘œμ€€ μ •κ·œλΆ„ν¬μ—μ„œ μƒ˜ν”Œλ§
        z = mu + std * epsilon
        return z

    def decode(self, z):
        """잠재 벑터λ₯Ό 원본 κ³΅κ°„μœΌλ‘œ λ””μ½”λ”©"""
        return self.decoder(z)

    def forward(self, x):
        """μˆœμ „νŒŒ: 인코딩 -> μƒ˜ν”Œλ§ -> λ””μ½”λ”©"""
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        reconstructed = self.decode(z)
        return reconstructed, mu, logvar

    def generate(self, num_samples, device='cpu'):
        """μƒˆλ‘œμš΄ μƒ˜ν”Œ 생성"""
        # ν‘œμ€€ μ •κ·œλΆ„ν¬μ—μ„œ μƒ˜ν”Œλ§
        z = torch.randn(num_samples, self.latent_dim).to(device)
        samples = self.decode(z)
        return samples


def vae_loss(reconstructed, original, mu, logvar, beta=1.0):
    """
    VAE 손싀 ν•¨μˆ˜

    Args:
        reconstructed: μž¬κ΅¬μ„±λœ 좜λ ₯
        original: 원본 μž…λ ₯
        mu: 잠재 λΆ„ν¬μ˜ 평균
        logvar: 잠재 λΆ„ν¬μ˜ 둜그 λΆ„μ‚°
        beta: KL λ°œμ‚° κ°€μ€‘μΉ˜ (Beta-VAE용)

    Returns:
        total_loss, recon_loss, kl_loss
    """
    # 1. μž¬κ΅¬μ„± 손싀 (Binary Cross Entropy)
    recon_loss = F.binary_cross_entropy(reconstructed, original, reduction='sum')

    # 2. KL Divergence: 잠재 뢄포와 ν‘œμ€€ μ •κ·œλΆ„ν¬ κ°„μ˜ 거리
    # KL(q(z|x) || p(z)) = -0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
    kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())

    total_loss = recon_loss + beta * kl_loss
    return total_loss, recon_loss, kl_loss


def train_vae(model, train_loader, optimizer, device, epoch):
    """VAE ν•™μŠ΅ ν•¨μˆ˜"""
    model.train()
    total_loss = 0
    total_recon = 0
    total_kl = 0

    for batch_idx, (data, _) in enumerate(train_loader):
        data = data.view(-1, 784).to(device)  # Flatten

        optimizer.zero_grad()
        reconstructed, mu, logvar = model(data)

        loss, recon_loss, kl_loss = vae_loss(reconstructed, data, mu, logvar)
        loss.backward()
        optimizer.step()

        total_loss += loss.item()
        total_recon += recon_loss.item()
        total_kl += kl_loss.item()

    avg_loss = total_loss / len(train_loader.dataset)
    print(f'Epoch {epoch}: Loss={avg_loss:.4f}, '
          f'Recon={total_recon/len(train_loader.dataset):.4f}, '
          f'KL={total_kl/len(train_loader.dataset):.4f}')

    return avg_loss


def visualize_latent_space(model, test_loader, device):
    """잠재 곡간 μ‹œκ°ν™” (2D 잠재 곡간인 경우)"""
    model.eval()
    z_list = []
    label_list = []

    with torch.no_grad():
        for data, labels in test_loader:
            data = data.view(-1, 784).to(device)
            mu, _ = model.encode(data)
            z_list.append(mu.cpu())
            label_list.append(labels)

    z = torch.cat(z_list, dim=0).numpy()
    labels = torch.cat(label_list, dim=0).numpy()

    if z.shape[1] == 2:
        plt.figure(figsize=(10, 8))
        scatter = plt.scatter(z[:, 0], z[:, 1], c=labels, cmap='tab10', alpha=0.6)
        plt.colorbar(scatter)
        plt.xlabel('Latent Dimension 1')
        plt.ylabel('Latent Dimension 2')
        plt.title('VAE Latent Space Visualization')
        plt.savefig('vae_latent_space.png')
        print("Latent space visualization saved to 'vae_latent_space.png'")


# μ‚¬μš© 예제
if __name__ == "__main__":
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(f"Using device: {device}")

    # MNIST 데이터셋 λ‘œλ“œ
    transform = transforms.ToTensor()
    train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
    test_dataset = datasets.MNIST('./data', train=False, transform=transform)

    train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)
    test_loader = DataLoader(test_dataset, batch_size=128, shuffle=False)

    # VAE λͺ¨λΈ μ΄ˆκΈ°ν™”
    vae = VAE(input_dim=784, hidden_dim=400, latent_dim=20).to(device)
    optimizer = torch.optim.Adam(vae.parameters(), lr=1e-3)

    # ν•™μŠ΅
    print("Training VAE on MNIST...")
    for epoch in range(1, 11):
        train_vae(vae, train_loader, optimizer, device, epoch)

    # μƒˆλ‘œμš΄ μƒ˜ν”Œ 생성
    print("\nGenerating new samples...")
    samples = vae.generate(16, device)
    print(f"Generated samples shape: {samples.shape}")

πŸ—£οΈ How It's Said in Practice

In a generative model design meeting
"If we use a VAE for image generation, the latent space is easy to interpret, but the output is a bit blurry. If we want high quality, we should use it together with Diffusion."
In building an anomaly detection system
"We train a VAE on normal data and judge it as anomalous when the reconstruction error is large. It's practical because it works without labels."
In a model architecture discussion
"If you raise the beta value in Beta-VAE, disentanglement improves, so each latent variable comes to capture a meaningful feature."
In explaining Stable Diffusion
"Stable Diffusion runs diffusion not in pixel space but in the latent space created by a VAE. That's why it's fast and memory-efficient."

⚠️ Common Mistakes & Cautions

KL Collapse
This is a phenomenon in which the KL divergence converges to 0 early in training, making the latent space meaningless. It can be resolved with KL annealing (starting with a small beta early on and gradually increasing it) or the Free Bits technique.
Reconstruction Loss Selection Error
BCE should be used for binary data (0-1), and MSE for continuous data. When using Sigmoid output and BCE on images, the input must also be normalized to 0-1; otherwise, training becomes unstable.
Latent Dimension Setting
If the latent dimension is too large, the regularization effect weakens, and if it is too small, information loss increases. The appropriate dimension must be determined experimentally according to data complexity. MNIST needs 20-50, and complex images need larger dimensions.
Using a Single Evaluation Metric
You must not look at the reconstruction loss alone. Only by evaluating generation quality (FID), latent space structure (interpolation quality), diversity, and more together can you judge whether the VAE has been trained properly.

πŸ”— Related Terms

πŸ“š Learn More