I'll provide you with a complete implementation of image inpainting using a diffusion model in PyTorch. This includes the model architecture, training process, and inference code.
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
import math
class SinusoidalPositionEmbeddings(nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, time):
device = time.device
half_dim = self.dim // 2
embeddings = math.log(10000) / (half_dim - 1)
embeddings = torch.exp(torch.arange(half_dim, device=device) * -embeddings)
embeddings = time[:, None] * embeddings[None, :]
embeddings = torch.cat((embeddings.sin(), embeddings.cos()), dim=-1)
return embeddings
class Block(nn.Module):
def __init__(self, in_channels, out_channels, time_emb_dim, up=False):
super().__init__()
self.time_mlp = nn.Linear(time_emb_dim, out_channels)
if up:
self.conv1 = nn.Conv2d(2 * in_channels, out_channels, 3, padding=1)
self.transform = nn.ConvTranspose2d(out_channels, out_channels, 4, 2, 1)
else:
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
self.transform = nn.Conv2d(out_channels, out_channels, 4, 2, 1)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
self.bnorm1 = nn.BatchNorm2d(out_channels)
self.bnorm2 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU()
def forward(self, x, t):
h = self.bnorm1(self.relu(self.conv1(x)))
time_emb = self.relu(self.time_mlp(t))
time_emb = time_emb[(...,) + (None,) * 2]
h = h + time_emb
h = self.bnorm2(self.relu(self.conv2(h)))
return self.transform(h)
class SimpleUNet(nn.Module):
def __init__(self, image_channels=3, time_dim=256, device="cuda"):
super().__init__()
self.device = device
self.time_dim = time_dim
# Time embedding
self.time_mlp = nn.Sequential(
SinusoidalPositionEmbeddings(time_dim),
nn.Linear(time_dim, time_dim),
nn.ReLU()
)
# Initial projection
self.conv0 = nn.Conv2d(image_channels, 64, 3, padding=1)
# Downsample
self.downs = nn.ModuleList([
Block(64, 128, time_dim),
Block(128, 256, time_dim),
Block(256, 512, time_dim)
])
# Upsample
self.ups = nn.ModuleList([
Block(512, 256, time_dim, up=True),
Block(256, 128, time_dim, up=True),
Block(128, 64, time_dim, up=True)
])
# Final projection
self.output = nn.Conv2d(64, image_channels, 1)
def forward(self, x, timestep):
t = self.time_mlp(timestep)
x = self.conv0(x)
# Downsample
residuals = []
for down in self.downs:
x = down(x, t)
residuals.append(x)
# Upsample
for up, skip in zip(self.ups, reversed(residuals)):
x = torch.cat((x, skip), dim=1)
x = up(x, t)
return self.output(x)
class DiffusionModel:
def __init__(self, num_timesteps=1000, beta_start=0.0001, beta_end=0.02, device="cuda"):
self.num_timesteps = num_timesteps
self.device = device
# Linear beta schedule
self.betas = torch.linspace(beta_start, beta_end, num_timesteps).to(device)
self.alphas = 1 - self.betas
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
self.alphas_cumprod_prev = F.pad(self.alphas_cumprod[:-1], (1, 0), value=1.0)
# Calculations for diffusion q(x_t | x_{t-1})
self.sqrt_alphas_cumprod = torch.sqrt(self.alphas_cumprod)
self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1 - self.alphas_cumprod)
# Calculations for posterior q(x_{t-1} | x_t, x_0)
self.posterior_variance = self.betas * (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod)
self.posterior_log_variance_clipped = torch.log(torch.clamp(self.posterior_variance, min=1e-20))
self.posterior_mean_coef1 = self.betas * torch.sqrt(self.alphas_cumprod_prev) / (1 - self.alphas_cumprod)
self.posterior_mean_coef2 = (1 - self.alphas_cumprod_prev) * torch.sqrt(self.alphas) / (1 - self.alphas_cumprod)
def q_sample(self, x_start, t, noise=None):
"""Forward diffusion process"""
if noise is None:
noise = torch.randn_like(x_start)
sqrt_alphas_cumprod_t = self.sqrt_alphas_cumprod[t][:, None, None, None]
sqrt_one_minus_alphas_cumprod_t = self.sqrt_one_minus_alphas_cumprod[t][:, None, None, None]
return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise
@torch.no_grad()
def p_sample(self, model, x, t, mask, known_region):
"""Sample from p(x_{t-1} | x_t)"""
betas_t = self.betas[t][:, None, None, None]
sqrt_one_minus_alphas_cumprod_t = self.sqrt_one_minus_alphas_cumprod[t][:, None, None, None]
sqrt_recip_alphas_t = torch.sqrt(1.0 / self.alphas[t])[:, None, None, None]
# Predict noise
model_mean = sqrt_recip_alphas_t * (
x - betas_t / sqrt_one_minus_alphas_cumprod_t * model(x, t)
)
if t[0] == 0:
return model_mean
else:
posterior_variance_t = self.posterior_variance[t][:, None, None, None]
noise = torch.randn_like(x)
return model_mean + torch.sqrt(posterior_variance_t) * noise
@torch.no_grad()
def inpaint(self, model, shape, mask, known_region, device):
"""Inpainting process"""
model.eval()
# Start from pure noise
img = torch.randn(shape, device=device)
for i in tqdm(reversed(range(self.num_timesteps)), desc='Inpainting'):
t = torch.full((shape[0],), i, device=device, dtype=torch.long)
# Sample from model
img = self.p_sample(model, img, t, mask, known_region)
# Replace known regions
if i > 0:
# Add noise to known region for next timestep
noise = torch.randn_like(known_region)
known_region_noisy = self.q_sample(known_region, t-1, noise)
img = mask * known_region_noisy + (1 - mask) * img
# Final replacement of known regions
img = mask * known_region + (1 - mask) * img
return img
def train_diffusion_model(model, dataloader, num_epochs=100, lr=1e-4, device="cuda"):
"""Training loop for diffusion model"""
diffusion = DiffusionModel(device=device)
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
mse_loss = nn.MSELoss()
model.train()
for epoch in range(num_epochs):
epoch_loss = 0
for batch_idx, (images, _) in enumerate(dataloader):
images = images.to(device)
batch_size = images.shape[0]
# Sample random timesteps
t = torch.randint(0, diffusion.num_timesteps, (batch_size,), device=device).long()
# Add noise to images
noise = torch.randn_like(images)
x_noisy = diffusion.q_sample(images, t, noise=noise)
# Predict noise
predicted_noise = model(x_noisy, t)
# Calculate loss
loss = mse_loss(noise, predicted_noise)
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_loss += loss.item()
avg_loss = epoch_loss / len(dataloader)
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}")
return model
# Example usage
def create_inpainting_mask(height, width, mask_type="center"):
"""Create different types of masks for inpainting"""
mask = torch.zeros(1, 1, height, width)
if mask_type == "center":
# Mask center region
h_start, h_end = height // 4, 3 * height // 4
w_start, w_end = width // 4, 3 * width // 4
mask[:, :, h_start:h_end, w_start:w_end] = 1
elif mask_type == "random":
# Random rectangular mask
h_start = np.random.randint(0, height // 2)
w_start = np.random.randint(0, width // 2)
h_size = np.random.randint(height // 4, height // 2)
w_size = np.random.randint(width // 4, width // 2)
mask[:, :, h_start:h_start+h_size, w_start:w_start+w_size] = 1
return 1 - mask # Return inverted mask (1 for regions to inpaint)
# Demonstration code
if __name__ == "__main__":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize model
model = SimpleUNet(image_channels=3, device=device).to(device)
# For demonstration, create synthetic data
# In practice, you would use a real image dataset
from torch.utils.data import DataLoader, TensorDataset
# Create synthetic dataset (replace with real data)
num_samples = 100
synthetic_images = torch.randn(num_samples, 3, 64, 64)
synthetic_labels = torch.zeros(num_samples)
dataset = TensorDataset(synthetic_images, synthetic_labels)
dataloader = DataLoader(dataset, batch_size=8, shuffle=True)
# Train model (use pre-trained weights in practice)
print("Training diffusion model...")
trained_model = train_diffusion_model(model, dataloader, num_epochs=10, device=device)
# Perform inpainting
print("\nPerforming inpainting...")
# Load or create an image to inpaint
test_image = torch.randn(1, 3, 64, 64).to(device) # Replace with real image
# Create mask (0 where we want to inpaint, 1 where we keep original)
mask = create_inpainting_mask(64, 64, "center").to(device)
# Apply mask to create corrupted image
known_region = test_image * mask
# Initialize diffusion model
diffusion = DiffusionModel(device=device)
# Perform inpainting
inpainted_image = diffusion.inpaint(
trained_model,
shape=(1, 3, 64, 64),
mask=mask,
known_region=known_region,
device=device
)
print("Inpainting complete!")
# The inpainted_image tensor contains the restored image
# You can save or visualize it as needed
This implementation includes:
- U-Net Architecture: A simplified U-Net with time embeddings for the diffusion model
- Diffusion Process: Forward and reverse diffusion processes with beta scheduling
- Training Loop: Standard training procedure for diffusion models
- Inpainting Algorithm: Specialized sampling process that preserves known regions while generating missing parts
- Mask Creation: Utility function to create different types of masks
To use this code effectively:
- Replace the synthetic data with a real image dataset (e.g., CelebA, ImageNet)
- Train the model for more epochs with appropriate hyperparameters
- For inference, load your image and create an appropriate mask for the regions you want to inpaint
- The inpainting process will iteratively denoise while preserving the known regions
The key insight for inpainting with diffusion models is that during the reverse process, we replace the known regions with their appropriately noised versions at each timestep, allowing the model to generate coherent content for the masked regions while maintaining consistency with the known parts.