Sure! Below is a Python code example that creates a prompt-based Visual Language Model (VLM) using GPT-2 for text generation, integrated with image processing capabilities. This code utilizes the AI2D dataset from Hugging Face, which contains diagram images and corresponding textual descriptions.
The code performs the following steps:
- Load the AI2D dataset: Retrieves images and text descriptions.
- Preprocess images and text: Applies necessary transformations to images and tokenizes text.
- Extract image features: Uses a pre-trained ResNet-50 model to obtain image embeddings.
- Define an adapter: Maps image features to GPT-2's hidden space.
- Integrate image features with GPT-2: Combines image embeddings with text embeddings for text generation.
- Train the adapter and GPT-2 model: Fine-tunes the combined model on the dataset.
- Save the trained model: Stores the trained model for later use.
Here's the complete code:
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from torchvision.models import resnet50, ResNet50_Weights
from transformers import GPT2Tokenizer, GPT2LMHeadModel
from transformers import get_linear_schedule_with_warmup, AdamW
from PIL import Image
from datasets import load_dataset
import os
# 1. Load the AI2D dataset
dataset = load_dataset('ai2d')
# 2. Define image and text preprocessing
image_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
# Normalize using ImageNet's mean and standard deviation
transforms.Normalize(ResNet50_Weights.IMAGENET1K_V1.transforms.mean, ResNet50_Weights.IMAGENET1K_V1.transforms.std)
])
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
# Add special tokens if necessary
tokenizer.pad_token = tokenizer.eos_token
# 3. Create a custom Dataset class
class AI2DDataset(Dataset):
def __init__(self, dataset_split, tokenizer, image_transform):
self.dataset = dataset_split
self.tokenizer = tokenizer
self.image_transform = image_transform
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
item = self.dataset[idx]
# Load image
image_path = item['image_path']
image = Image.open(image_path).convert('RGB')
image = self.image_transform(image)
# Load text
text = item['description']
# Tokenize text
tokens = self.tokenizer(
text, return_tensors='pt', truncation=True, padding='max_length', max_length=128
)
input_ids = tokens['input_ids'].squeeze(0)
attention_mask = tokens['attention_mask'].squeeze(0)
return image, input_ids, attention_mask
# 4. Prepare DataLoaders
train_data = AI2DDataset(dataset['train'], tokenizer, image_transform)
val_data = AI2DDataset(dataset['validation'], tokenizer, image_transform)
train_loader = DataLoader(train_data, batch_size=8, shuffle=True)
val_loader = DataLoader(val_data, batch_size=8)
# 5. Load pre-trained models
# Image feature extractor
image_model = resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)
image_model = torch.nn.Sequential(*list(image_model.children())[:-1]) # Remove last layer
image_model.eval() # Set to evaluation mode
# GPT-2 language model
gpt2_model = GPT2LMHeadModel.from_pretrained('gpt2')
gpt2_model.resize_token_embeddings(len(tokenizer))
# 6. Define the adapter to integrate image features
class ImageAdapter(torch.nn.Module):
def __init__(self, image_feature_dim, gpt2_hidden_size):
super(ImageAdapter, self).__init__()
self.linear = torch.nn.Linear(image_feature_dim, gpt2_hidden_size)
self.activation = torch.nn.Tanh()
def forward(self, image_features):
x = self.linear(image_features)
x = self.activation(x)
return x
image_feature_dim = 2048 # Feature dimension from ResNet-50
gpt2_hidden_size = gpt2_model.config.hidden_size
adapter = ImageAdapter(image_feature_dim, gpt2_hidden_size)
# 7. Define the combined model
class VLMModel(torch.nn.Module):
def __init__(self, image_model, adapter, gpt2_model):
super(VLMModel, self).__init__()
self.image_model = image_model
self.adapter = adapter
self.gpt2_model = gpt2_model
def forward(self, images, input_ids, attention_mask):
with torch.no_grad():
# Extract image features
image_features = self.image_model(images).flatten(1) # (batch_size, image_feature_dim)
# Adapt image features
adapted_features = self.adapter(image_features) # (batch_size, gpt2_hidden_size)
# Get text embeddings
text_embeddings = self.gpt2_model.transformer.wte(input_ids)
# Combine image and text embeddings
# Here we add image embeddings to the first token embedding
text_embeddings[:, 0, :] += adapted_features
# Forward pass through GPT-2
outputs = self.gpt2_model(inputs_embeds=text_embeddings, attention_mask=attention_mask, labels=input_ids)
return outputs
# Instantiate the model
vlm_model = VLMModel(image_model, adapter, gpt2_model)
# 8. Set up training components
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
vlm_model.to(device)
optimizer = AdamW(vlm_model.parameters(), lr=5e-5)
num_epochs = 3
total_steps = len(train_loader) * num_epochs
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=0, num_training_steps=total_steps
)
# 9. Training loop
from tqdm import tqdm
vlm_model.train()
for epoch in range(num_epochs):
print(f"Epoch {epoch+1}/{num_epochs}")
epoch_loss = 0
for images, input_ids, attention_mask in tqdm(train_loader):
images = images.to(device)
input_ids = input_ids.to(device)
attention_mask = attention_mask.to(device)
outputs = vlm_model(images, input_ids, attention_mask)
loss = outputs.loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()
epoch_loss += loss.item()
avg_train_loss = epoch_loss / len(train_loader)
print(f"Average training loss: {avg_train_loss:.4f}")
# Validation
vlm_model.eval()
val_loss = 0
with torch.no_grad():
for images, input_ids, attention_mask in val_loader:
images = images.to(device)
input_ids = input_ids.to(device)
attention_mask = attention_mask.to(device)
outputs = vlm_model(images, input_ids, attention_mask)
loss = outputs.loss
val_loss += loss.item()
avg_val_loss = val_loss / len(val_loader)
print(f"Validation loss: {avg_val_loss:.4f}")
vlm_model.train()
# 10. Save the trained model
output_dir = "./vlm_model"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
vlm_model.gpt2_model.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
Explanation:
- Dataset Loading: The code uses
load_dataset('ai2d') to fetch the AI2D dataset. Adjust the dataset loading based on the actual dataset structure if needed.
- Image Processing: Images are resized, normalized, and converted to tensors suitable for the ResNet-50 model.
- Text Tokenization: Text descriptions are tokenized using GPT-2's tokenizer with appropriate padding and truncation.
- Image Feature Extraction: A pre-trained ResNet-50 model (without the final classification layer) extracts 2048-dimensional features from images.
- Adapter Definition: The
ImageAdapter class maps these image features to the GPT-2 hidden size using a linear layer followed by a Tanh activation.
- Model Integration: The
VLMModel class combines image features with text embeddings by adding the adapted image features to the embedding of the first token.
- Training Loop: The model is trained using the AdamW optimizer and a linear learning rate scheduler. Both training and validation losses are calculated and printed.
- Saving the Model: After training, the GPT-2 part of the model and the tokenizer are saved for future use.
Note:
- Make sure all dependencies (
torch, transformers, datasets, torchvision, etc.) are installed.
- Adjust batch sizes and paths based on your compute resources and dataset structure.
- The method of integrating image features into GPT-2 can be further refined. This example adds image features to the first token's embedding, but other methods like concatenation or using special tokens can also be explored.
Usage:
- After training, you can use the saved model for text generation tasks that consider both image and textual inputs.
- Load the saved model and tokenizer using
GPT2LMHeadModel.from_pretrained and GPT2Tokenizer.from_pretrained.
Example for Inference:
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import torch
from PIL import Image
# Load the tokenizer and model
tokenizer = GPT2Tokenizer.from_pretrained('./vlm_model')
model = GPT2LMHeadModel.from_pretrained('./vlm_model')
# Set to evaluation mode
model.eval()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Load and preprocess an image
image = Image.open('path_to_image.jpg').convert('RGB')
image = image_transform(image).unsqueeze(0).to(device)
# Prepare a prompt
prompt = "The diagram shows"
# Tokenize the prompt
input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
# Extract image features using the same adapter
with torch.no_grad():
image_features = image_model(image).flatten(1)
adapted_features = adapter(image_features)
text_embeddings = model.transformer.wte(input_ids)
text_embeddings[:, 0, :] += adapted_features
# Generate text
outputs = model.generate(
inputs_embeds=text_embeddings,
max_length=50,
num_beams=5,
no_repeat_ngram_size=2,
early_stopping=True
)
# Decode the output
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
Conclusion:
This code provides a framework for integrating image features into a language model for text generation tasks. It uses a prompt-based adapter approach to train the model on a dataset containing both images and text descriptions.
Feel free to adjust the code based on the specific requirements of your dataset and experiment with different methods of integrating image features into the language model.