Creating a model that takes two images as input, identifies the changes between them, and generates a descriptive caption is an advanced task that combines elements of image comparison and natural language generation. Below, I provide a comprehensive guide to building such a model using PyTorch and Hugging Face’s Transformers library. We'll leverage pre-trained models to simplify the process and fine-tune them for our specific task.
Overview of the Approach
- Feature Extraction: Use a pre-trained image encoder (e.g., CLIP’s Vision Transformer) to extract features from both images.
- Feature Comparison: Compute the difference between the two feature representations to highlight changes.
- Text Generation: Use a pre-trained language model (e.g., GPT-2 or a Transformer-based decoder) to generate a caption based on the difference features.
- Training: Fine-tune the combined model on a dataset containing image pairs and corresponding change descriptions.
Prerequisites
Before diving into the code, ensure you have the following libraries installed:
pip install torch torchvision transformers datasets
Step-by-Step Implementation
1. Import Libraries
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from transformers import CLIPModel, CLIPProcessor, GPT2Tokenizer, GPT2LMHeadModel, AdamW
from PIL import Image
import os
from tqdm import tqdm
2. Prepare the Dataset
Assume you have a dataset where each sample consists of two images and a text description of the changes between them. Organize your dataset directory as follows:
dataset/
├── train/
│ ├── img1_0001.jpg
│ ├── img2_0001.jpg
│ └── caption_0001.txt
├── val/
│ ├── img1_0002.jpg
│ ├── img2_0002.jpg
│ └── caption_0002.txt
└── ...
Create a custom Dataset class to handle the data loading:
class ChangeCaptionDataset(Dataset):
def __init__(self, root_dir, split='train', transform=None):
self.root_dir = os.path.join(root_dir, split)
self.image1_paths = sorted([os.path.join(self.root_dir, fname)
for fname in os.listdir(self.root_dir)
if fname.startswith('img1') and fname.endswith(('.png', '.jpg', '.jpeg'))])
self.image2_paths = sorted([os.path.join(self.root_dir, fname)
for fname in os.listdir(self.root_dir)
if fname.startswith('img2') and fname.endswith(('.png', '.jpg', '.jpeg'))])
self.caption_paths = sorted([os.path.join(self.root_dir, fname)
for fname in os.listdir(self.root_dir)
if fname.startswith('caption') and fname.endswith('.txt')])
self.transform = transform
assert len(self.image1_paths) == len(self.image2_paths) == len(self.caption_paths), "Mismatch in dataset lengths."
def __len__(self):
return len(self.caption_paths)
def __getitem__(self, idx):
img1 = Image.open(self.image1_paths[idx]).convert('RGB')
img2 = Image.open(self.image2_paths[idx]).convert('RGB')
if self.transform:
img1 = self.transform(img1)
img2 = self.transform(img2)
with open(self.caption_paths[idx], 'r') as f:
caption = f.read().strip()
return img1, img2, caption
3. Initialize Processors and Tokenizers
# Initialize CLIP processor for image preprocessing
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
# Initialize GPT-2 tokenizer and model
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
# Ensure the tokenizer has a padding token
if tokenizer.pad_token is None:
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
gpt2_model = GPT2LMHeadModel.from_pretrained("gpt2")
4. Define the Combined Model
We'll create a model that processes both images, computes their feature difference, and generates a caption based on this difference.
class ChangeCaptionModel(nn.Module):
def __init__(self, clip_model, gpt2_model, tokenizer, device):
super(ChangeCaptionModel, self).__init__()
self.clip_encoder = clip_model.get_image_features # Function to get image features
self.tokenizer = tokenizer
self.gpt2 = gpt2_model
self.device = device
# Freeze CLIP encoder if desired
for param in self.clip_encoder.parameters():
param.requires_grad = False
# Project CLIP features to GPT-2 hidden size if necessary
self.feature_dim = clip_model.config.projection_dim
self.gpt2_hidden_size = gpt2_model.config.hidden_size
if self.feature_dim != self.gpt2_hidden_size:
self.feature_proj = nn.Linear(self.feature_dim, self.gpt2_hidden_size)
else:
self.feature_proj = nn.Identity()
def forward(self, img1, img2, captions=None):
# Extract features for both images
with torch.no_grad():
feat1 = self.clip_encoder(pixel_values=img1) # Shape: (batch_size, feature_dim)
feat2 = self.clip_encoder(pixel_values=img2) # Shape: (batch_size, feature_dim)
# Compute feature difference
feat_diff = feat2 - feat1 # Shape: (batch_size, feature_dim)
# Project to GPT-2 hidden size
projected_feat = self.feature_proj(feat_diff) # Shape: (batch_size, gpt2_hidden_size)
if captions is not None:
# Tokenize captions
inputs = self.tokenizer(captions, return_tensors='pt', padding=True, truncation=True).to(self.device)
input_ids = inputs.input_ids
attention_mask = inputs.attention_mask
# Embed the projected features as a prompt
# Here, we can prepend the features to the input embeddings
# GPT-2 does not have a method to directly input extra embeddings, so we can modify the inputs accordingly.
# For simplicity, we concatenate the caption tokens and let GPT-2 generate based on the input
outputs = self.gpt2(input_ids=input_ids, attention_mask=attention_mask, labels=input_ids)
loss = outputs.loss
return loss
else:
# Inference mode
generated = self.gpt2.generate(
bos_token_id=self.tokenizer.bos_token_id,
max_length=50,
num_beams=5,
early_stopping=True
)
caption = self.tokenizer.decode(generated[0], skip_special_tokens=True)
return caption
Notes:
-
Feature Projection: Since CLIP’s feature dimension may not match GPT-2’s hidden size, we project the feature difference to match GPT-2's expected input size.
-
Integration: Directly integrating image features into GPT-2 is non-trivial because GPT-2 is primarily designed for text. For a more sophisticated approach, consider using a multimodal transformer that can handle both image and text inputs, such as VisualGPT or BLIP.
-
Training Objective: In this simplified example, we're using the standard language modeling loss by treating the task as generating the caption based on the input images. For better performance, custom loss functions that explicitly model the change detection might be necessary.
5. Prepare Data Loaders
from torchvision import transforms
# Define image transformations
transform = transforms.Compose([
transforms.Resize((224, 224)), # CLIP expects 224x224 images
transforms.ToTensor(),
transforms.Normalize(mean=clip_processor.image_processor.image_mean,
std=clip_processor.image_processor.image_std)
])
# Create datasets
train_dataset = ChangeCaptionDataset(root_dir='dataset', split='train', transform=transform)
val_dataset = ChangeCaptionDataset(root_dir='dataset', split='val', transform=transform)
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True, num_workers=4)
val_loader = DataLoader(val_dataset, batch_size=8, shuffle=False, num_workers=4)
6. Initialize the Model, Optimizer, and Device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = ChangeCaptionModel(clip_model, gpt2_model, tokenizer, device).to(device)
# Move GPT-2 to device
model.gpt2.to(device)
# Define optimizer (only train GPT-2 and projection layers)
optimizer = AdamW(filter(lambda p: p.requires_grad, model.parameters()), lr=5e-5)
Ensure that only the necessary parts are trainable. For example, if you froze the CLIP encoder, it won’t be updated during training.
7. Training Loop
num_epochs = 5
for epoch in range(num_epochs):
model.train()
total_loss = 0
for img1, img2, captions in tqdm(train_loader, desc=f"Training Epoch {epoch+1}"):
img1 = img1.to(device)
img2 = img2.to(device)
captions = captions.to(device) # Assuming captions are already tokenized; otherwise, handle accordingly.
optimizer.zero_grad()
loss = model(img1, img2, captions)
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / len(train_loader)
print(f"Epoch {epoch+1}/{num_epochs} - Average Loss: {avg_loss:.4f}")
# Validation
model.eval()
with torch.no_grad():
val_loss = 0
for img1, img2, captions in tqdm(val_loader, desc="Validation"):
img1 = img1.to(device)
img2 = img2.to(device)
captions = captions.to(device)
loss = model(img1, img2, captions)
val_loss += loss.item()
avg_val_loss = val_loss / len(val_loader)
print(f"Validation Loss: {avg_val_loss:.4f}")
Notes:
-
Caption Handling: Ensure that captions are properly tokenized. In the forward method of ChangeCaptionModel, you might need to adjust how captions are processed based on your specific implementation.
-
Adjustments for Generation: The inference part of the model (model.generate) is simplistic. For better performance, integrate the image features more effectively, possibly through attention mechanisms or multimodal transformers.
8. Inference
After training, you can generate captions for new image pairs as follows:
def generate_caption(model, img1_path, img2_path, processor, tokenizer, device, transform):
model.eval()
with torch.no_grad():
img1 = Image.open(img1_path).convert('RGB')
img2 = Image.open(img2_path).convert('RGB')
img1 = transform(img1).unsqueeze(0).to(device)
img2 = transform(img2).unsqueeze(0).to(device)
caption = model(img1, img2)
return caption
# Example usage
img1_path = 'path/to/image1.jpg'
img2_path = 'path/to/image2.jpg'
caption = generate_caption(model, img1_path, img2_path, clip_processor, tokenizer, device, transform)
print("Generated Caption:", caption)
Considerations and Enhancements
-
Dataset: Ensure you have a high-quality dataset with diverse image pairs and accurate change captions. Datasets like CLEVR-Change can be useful for benchmarking.
-
Model Architecture: For better integration between visual and textual modalities, consider using architectures specifically designed for multimodal tasks, such as BLIP or VisualGPT.
-
Loss Functions: Incorporate loss functions that explicitly encourage the model to focus on the changes between images, such as contrastive losses or attention-based mechanisms.
-
Evaluation Metrics: Use metrics like BLEU, METEOR, or CIDEr to evaluate the quality of the generated captions against ground truth descriptions.
-
Fine-Tuning: You can further fine-tune the image encoder (CLIP) and language model (GPT-2) jointly if computational resources allow, potentially improving performance.
Conclusion
The implementation provided offers a foundational structure for building a change captioning model using pre-trained image and language models. Depending on your specific requirements and dataset, further refinements and architectural adjustments may be necessary to achieve optimal performance.