import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List, Tuple
class VisionLanguageModel(nn.Module):
"""
A PyTorch model that processes images and corresponding text inputs.
"""
def __init__(
self,
image_channels: int,
num_classes: int,
vocab_size: int,
embedding_dim: int,
hidden_dim: int,
output_dim: int,
) -> None:
"""
Initializes the VisionLanguageModel.
Args:
image_channels (int): Number of channels in the input images.
num_classes (int): Number of classes for classification tasks.
vocab_size (int): Size of the vocabulary for text inputs.
embedding_dim (int): Dimension of the word embeddings.
hidden_dim (int): Dimension of the hidden state in the text encoder.
output_dim (int): Dimension of the output features.
"""
super(VisionLanguageModel, self).__init__()
# Vision encoder using a simple CNN
self.vision_encoder = nn.Sequential(
nn.Conv2d(image_channels, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
nn.AdaptiveAvgPool2d((1, 1)),
)
# Text encoder using an embedding layer and GRU
self.text_embedding = nn.Embedding(vocab_size, embedding_dim)
self.text_encoder = nn.GRU(
embedding_dim, hidden_dim, batch_first=True, bidirectional=True
)
# Fusion layer to combine vision and language features
self.fc = nn.Linear(128 + hidden_dim * 2, output_dim)
self.classifier = nn.Linear(output_dim, num_classes)
def forward(
self, images: torch.Tensor, texts: List[List[int]]
) -> torch.Tensor:
"""
Forward pass of the model.
Args:
images (torch.Tensor): Batch of images with shape (batch_size, channels, height, width).
texts (List[List[int]]): Batch of tokenized text inputs.
Returns:
torch.Tensor: Output logits for classification.
"""
try:
# Validate inputs
if images.dim() != 4:
raise ValueError(
f"Expected images tensor to be 4D, but got {images.dim()}D."
)
batch_size = images.size(0)
# Process images
image_features = self.vision_encoder(images)
image_features = image_features.view(batch_size, -1)
# Process texts
text_lengths = [len(t) for t in texts]
max_length = max(text_lengths)
padded_texts = [
t + [0] * (max_length - len(t)) for t in texts
] # Padding
text_tensor = torch.tensor(padded_texts, dtype=torch.long)
embedded_text = self.text_embedding(text_tensor)
packed_input = nn.utils.rnn.pack_padded_sequence(
embedded_text,
text_lengths,
batch_first=True,
enforce_sorted=False,
)
_, hidden = self.text_encoder(packed_input)
text_features = torch.cat((hidden[-2], hidden[-1]), dim=1)
# Combine features
combined = torch.cat((image_features, text_features), dim=1)
combined = F.relu(self.fc(combined))
# Classification
logits = self.classifier(combined)
return logits
except Exception as e:
print(f"An error occurred during forward pass: {e}")
raise e
def main() -> None:
"""
Main function to test the VisionLanguageModel.
"""
try:
# Hyperparameters
batch_size = 8
image_channels = 3
height = 224
width = 224
vocab_size = 10000
embedding_dim = 300
hidden_dim = 256
output_dim = 512
num_classes = 10
# Dummy data
images = torch.randn(batch_size, image_channels, height, width)
texts = [[1, 2, 3, 4] for _ in range(batch_size)] # Example tokenized texts
# Initialize model
model = VisionLanguageModel(
image_channels,
num_classes,
vocab_size,
embedding_dim,
hidden_dim,
output_dim,
)
# Forward pass
outputs = model(images, texts)
print(f"Model output shape: {outputs.shape}")
except Exception as e:
print(f"An error occurred in main: {e}")
if __name__ == "__main__":
main()