Creating a Variational Autoencoder (VAE) that compresses sequences of 6 PNG images (each of resolution 64x64) into a single latent representation is an exciting project. This setup is particularly useful for video data, where each sequence of frames can be treated as a single data instance. Below, I'll guide you through the process of building such a VAE using PyTorch, which is well-supported on Google Colab.
Overview
- Data Preparation: Organize your dataset into sequences of 6 consecutive images.
- Model Architecture: Design an encoder and decoder that can handle sequences of images. We'll treat the 6 images as separate channels, resulting in a multi-channel input.
- Training the VAE: Implement the VAE loss function and train the model on your dataset.
- Inference: Compress and decompress sequences of images using the trained VAE.
Step-by-Step Implementation
1. Setup and Imports
First, ensure that you're using Google Colab with GPU support for efficient training.
# Check GPU availability
import torch
print("GPU Available: ", torch.cuda.is_available())
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
Import the necessary libraries:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
import os
import numpy as np
2. Data Preparation
Assuming you have a dataset of images stored in directories, you'll need to create a custom dataset that groups every 6 consecutive images as a single data point.
class ImageSequenceDataset(Dataset):
def __init__(self, root_dir, transform=None, sequence_length=6):
"""
Args:
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied on a sample.
sequence_length (int): Number of images in a sequence.
"""
self.root_dir = root_dir
self.transform = transform
self.sequence_length = sequence_length
self.image_files = sorted([os.path.join(root_dir, img) for img in os.listdir(root_dir) if img.endswith('.png')])
self.num_sequences = len(self.image_files) // self.sequence_length
def __len__(self):
return self.num_sequences
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
sequence = []
for i in range(self.sequence_length):
img_path = self.image_files[idx * self.sequence_length + i]
image = Image.open(img_path).convert('RGB') # Ensure 3 channels
if self.transform:
image = self.transform(image)
sequence.append(image)
# Stack images along the channel dimension
sequence = torch.cat(sequence, dim=0) # Shape: (3*6, 64, 64)
return sequence
Transforms and DataLoader:
transform = transforms.Compose([
transforms.Resize((64, 64)),
transforms.ToTensor(), # Converts to [0,1]
transforms.Normalize(mean=[0.5]*3*6, std=[0.5]*3*6) # Normalize to [-1, 1]
])
dataset = ImageSequenceDataset(root_dir='/path/to/your/images', transform=transform)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True, num_workers=4)
Replace '/path/to/your/images' with the actual path to your dataset.
3. VAE Model Architecture
We'll design the encoder and decoder to handle multi-channel inputs (18 channels for 6 RGB images).
class VAE(nn.Module):
def __init__(self, sequence_length=6, img_channels=3, latent_dim=256):
super(VAE, self).__init__()
self.sequence_length = sequence_length
self.img_channels = img_channels
self.input_channels = sequence_length * img_channels
self.latent_dim = latent_dim
# Encoder
self.encoder = nn.Sequential(
nn.Conv2d(self.input_channels, 64, kernel_size=4, stride=2, padding=1), # 32x32
nn.ReLU(inplace=True),
nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1), # 16x16
nn.ReLU(inplace=True),
nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1), # 8x8
nn.ReLU(inplace=True),
nn.Conv2d(256, 512, kernel_size=4, stride=2, padding=1), # 4x4
nn.ReLU(inplace=True),
nn.Flatten()
)
self.fc_mu = nn.Linear(512*4*4, latent_dim)
self.fc_logvar = nn.Linear(512*4*4, latent_dim)
# Decoder
self.decoder_input = nn.Linear(latent_dim, 512*4*4)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(512, 256, kernel_size=4, stride=2, padding=1), # 8x8
nn.ReLU(inplace=True),
nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1), # 16x16
nn.ReLU(inplace=True),
nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1), # 32x32
nn.ReLU(inplace=True),
nn.ConvTranspose2d(64, self.input_channels, kernel_size=4, stride=2, padding=1), # 64x64
nn.Tanh() # Output in [-1, 1]
)
def encode(self, x):
x_encoded = self.encoder(x)
mu = self.fc_mu(x_encoded)
logvar = self.fc_logvar(x_encoded)
return mu, logvar
def reparameterize(self, mu, logvar):
std = torch.exp(0.5*logvar)
eps = torch.randn_like(std)
return mu + eps*std
def decode(self, z):
x = self.decoder_input(z)
x = x.view(-1, 512, 4, 4)
x = self.decoder(x)
return x
def forward(self, x):
mu, logvar = self.encode(x)
z = self.reparameterize(mu, logvar)
recon_x = self.decode(z)
return recon_x, mu, logvar
Model Details:
-
Encoder: Uses a series of convolutional layers to downsample the input and extract features. The output is flattened and passed through two linear layers to obtain the mean (mu) and log-variance (logvar) for the latent space.
-
Reparameterization Trick: Allows backpropagation through the stochastic sampling step by expressing the latent variable z as a deterministic function of mu, logvar, and some noise.
-
Decoder: Maps the latent vector z back to the original input space using linear layers followed by transpose convolutions to upsample.
4. Loss Function
The VAE loss consists of two parts:
- Reconstruction Loss: Measures how well the decoder reconstructs the input. We'll use Mean Squared Error (MSE) or Binary Cross-Entropy (BCE) depending on the output activation.
- KL Divergence: Regularizes the latent space to follow a standard normal distribution.
def loss_function(recon_x, x, mu, logvar):
# Reconstruction loss
BCE = nn.functional.mse_loss(recon_x, x, reduction='sum')
# KL divergence
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD
Note: Since the decoder uses Tanh activation to output values in [-1, 1] and the input was normalized accordingly, MSE is appropriate.
5. Training the VAE
# Hyperparameters
latent_dim = 256
learning_rate = 1e-3
num_epochs = 50
sequence_length = 6
batch_size = 32
# Initialize model, optimizer
model = VAE(sequence_length=sequence_length, latent_dim=latent_dim).to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training loop
model.train()
for epoch in range(1, num_epochs + 1):
train_loss = 0
for batch_idx, data in enumerate(dataloader):
data = data.to(device)
optimizer.zero_grad()
recon_batch, mu, logvar = model(data)
loss = loss_function(recon_batch, data, mu, logvar)
loss.backward()
train_loss += loss.item()
optimizer.step()
if batch_idx % 100 == 0:
print(f'Epoch [{epoch}/{num_epochs}] Batch [{batch_idx}/{len(dataloader)}] Loss: {loss.item() / len(data):.4f}')
print(f'====> Epoch: {epoch} Average loss: {train_loss / len(dataloader.dataset):.4f}')
# Optionally, save checkpoints
torch.save(model.state_dict(), f'vae_epoch_{epoch}.pth')
Tips:
- Early Stopping: Monitor the loss and implement early stopping to prevent overfitting.
- Learning Rate Scheduling: Use schedulers like
ReduceLROnPlateau to adjust the learning rate based on validation loss.
6. Inference: Compressing and Decompressing Sequences
After training, you can use the VAE to compress (encode) sequences of images into latent vectors and decompress (decode) them back.
model.eval()
with torch.no_grad():
for i, data in enumerate(dataloader):
data = data.to(device)
recon_batch, mu, logvar = model(data)
# To get the latent representation
z = mu # Or use `z = model.reparameterize(mu, logvar)` for stochastic sampling
# Save or process `z` as needed
# For example, moving it to CPU:
z = z.cpu().numpy()
# To reconstruct
recon = recon_batch.cpu()
# Denormalize
recon = (recon * 0.5) + 0.5 # From [-1,1] to [0,1]
# Split into 6 images
for j in range(recon.size(0)):
sequence = recon[j]
for k in range(sequence_length):
img = sequence[k*3:(k+1)*3, :, :]
img = transforms.ToPILImage()(img)
img.save(f'reconstructed_sequence_{i}_image_{k}.png')
if i == 0: # Just process one batch for illustration
break
7. Enhancements and Modern Techniques
To make your VAE more powerful and modern, consider the following enhancements:
-
Residual Blocks: Incorporate residual connections to help with training deeper networks.
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
self.bn2 = nn.BatchNorm2d(out_channels)
if in_channels != out_channels:
self.adjust = nn.Conv2d(in_channels, out_channels, kernel_size=1)
else:
self.adjust = nn.Identity()
def forward(self, x):
residual = self.adjust(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out += residual
out = self.relu(out)
return out
-
Attention Mechanisms: Incorporate attention layers to allow the model to focus on important features.
-
Beta-VAE: Introduce a weight on the KL divergence term to control the capacity of the latent space.
beta = 4 # Adjust as needed
def loss_function(recon_x, x, mu, logvar):
BCE = nn.functional.mse_loss(recon_x, x, reduction='sum')
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + beta * KLD
-
Skip Connections: Add skip connections between encoder and decoder layers for better reconstruction.
8. Handling Large Datasets on Google Colab
Google Colab offers limited RAM and GPU resources. To efficiently handle large datasets:
-
Data Loading: Use num_workers in DataLoader to parallelize data loading.
-
Data Augmentation: Apply data augmentation on-the-fly instead of storing augmented data.
-
Model Checkpointing: Regularly save model checkpoints to avoid losing progress.
-
Mixed Precision Training: Use torch.cuda.amp for mixed precision training to save memory and speed up training.
scaler = torch.cuda.amp.GradScaler()
# In the training loop
for epoch in range(1, num_epochs + 1):
for batch_idx, data in enumerate(dataloader):
data = data.to(device)
optimizer.zero_grad()
with torch.cuda.amp.autocast():
recon_batch, mu, logvar = model(data)
loss = loss_function(recon_batch, data, mu, logvar)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
-
Checkpointing with Degradation: Save only certain layers or use lighter versions if the session is likely to disconnect.
9. Example Workflow in Google Colab
Here’s a condensed version of the workflow, perfect for executing on Google Colab:
-
Mount Google Drive (if your dataset is stored there):
from google.colab import drive
drive.mount('/content/drive')
-
Install Dependencies (if not already installed):
!pip install torch torchvision
-
Define the Dataset, Model, and Training Loop: Use the classes and functions defined above.
-
Train the Model: Execute the training loop, monitor progress, and save checkpoints.
-
Visualize Reconstructions:
import matplotlib.pyplot as plt
model.eval()
with torch.no_grad():
data = next(iter(dataloader)).to(device)
recon, _, _ = model(data)
recon = (recon * 0.5) + 0.5 # Denormalize to [0,1]
batch = data[:6] # Take first 6 samples
recon = recon[:6]
# Plot original and reconstructed images
for i in range(6):
orig = batch[i].cpu().numpy()
rec = recon[i].cpu().numpy()
fig, axes = plt.subplots(2, sequence_length, figsize=(15, 4))
for j in range(sequence_length):
ax = axes[0, j]
ax.imshow(np.transpose(orig[j*3:(j+1)*3], (1,2,0)))
ax.axis('off')
if i == 0:
ax.set_title(f'Orig Frame {j+1}')
ax = axes[1, j]
ax.imshow(np.transpose(rec[j*3:(j+1)*3], (1,2,0)))
ax.axis('off')
if i == 0:
ax.set_title(f'Recon Frame {j+1}')
plt.show()
Conclusion
By following the steps outlined above, you can build a VAE that effectively compresses sequences of 6 PNG images into a single latent representation. This architecture is versatile and can be further enhanced with modern techniques such as residual connections, attention mechanisms, and beta-VAE adjustments. Utilizing Google Colab's computational resources, you can train this model efficiently on large datasets.
Feel free to adjust the hyperparameters, architecture, and data handling to better suit your specific needs and dataset characteristics.