Update model.py
Browse files
model.py
CHANGED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from timm import create_model
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from transformers import RobertaModel
|
5 |
+
|
6 |
+
EMBEDDING_DIM = 512
|
7 |
+
|
8 |
+
class ImageEncoder(nn.Module):
|
9 |
+
def __init__(self):
|
10 |
+
super(ImageEncoder, self).__init__()
|
11 |
+
# Load the Swin Transformer with features_only=True
|
12 |
+
self.swin = create_model("swin_base_patch4_window7_224.ms_in22k", pretrained=True, features_only=True)
|
13 |
+
for param in self.swin.parameters():
|
14 |
+
param.requires_grad = True
|
15 |
+
|
16 |
+
# Get the feature size of the final stage
|
17 |
+
self.swin_output_dim = self.swin.feature_info.channels()[-1] # Last stage: 1024 channels
|
18 |
+
|
19 |
+
# Define FC layer
|
20 |
+
self.fc1 = nn.Linear(self.swin_output_dim * 7 * 7, EMBEDDING_DIM) # Flattened input size
|
21 |
+
nn.init.xavier_uniform_(self.fc1.weight)
|
22 |
+
nn.init.zeros_(self.fc1.bias)
|
23 |
+
for param in self.fc1.parameters():
|
24 |
+
param.requires_grad = True
|
25 |
+
|
26 |
+
|
27 |
+
def forward(self, x):
|
28 |
+
# Extract features from Swin
|
29 |
+
swin_features = self.swin(x)[-1] # Use the last stage feature map (e.g., [B, 1024, 7, 7])
|
30 |
+
|
31 |
+
# Flatten feature map
|
32 |
+
swin_features = swin_features.view(swin_features.size(0), -1) # Shape: (B, 1024*7*7)
|
33 |
+
|
34 |
+
# Pass through FC layer
|
35 |
+
output = self.fc1(swin_features) # Shape: (B, embedding_dim)
|
36 |
+
return output
|
37 |
+
|
38 |
+
class RobertaEncoder(nn.Module):
|
39 |
+
def __init__(self, roberta_model_path="roberta-base"):
|
40 |
+
super(RobertaEncoder, self).__init__()
|
41 |
+
# Load pre-trained RoBERTa model
|
42 |
+
self.roberta = RobertaModel.from_pretrained(roberta_model_path)
|
43 |
+
|
44 |
+
# Add a linear projection layer to reduce dimensionality
|
45 |
+
self.projection = nn.Linear(self.roberta.config.hidden_size, EMBEDDING_DIM)
|
46 |
+
|
47 |
+
# Initialize the projection layer weights
|
48 |
+
nn.init.xavier_uniform_(self.projection.weight)
|
49 |
+
nn.init.zeros_(self.projection.bias)
|
50 |
+
|
51 |
+
# Allow fine-tuning of the RoBERTa model
|
52 |
+
for param in self.roberta.parameters():
|
53 |
+
param.requires_grad = True
|
54 |
+
|
55 |
+
def forward(self, input_ids, attention_mask):
|
56 |
+
"""
|
57 |
+
Forward pass through RoBERTa.
|
58 |
+
Args:
|
59 |
+
input_ids: Tensor of shape (batch_size, seq_length)
|
60 |
+
attention_mask: Tensor of shape (batch_size, seq_length)
|
61 |
+
|
62 |
+
Returns:
|
63 |
+
Embedding: Tensor of shape (batch_size, EMBEDDING_DIM)
|
64 |
+
"""
|
65 |
+
roberta_output = self.roberta(input_ids=input_ids, attention_mask=attention_mask)
|
66 |
+
cls_token = roberta_output.last_hidden_state[:, 0, :] # Use CLS token
|
67 |
+
pooled_output = torch.mean(roberta_output.last_hidden_state, dim=1) # Mean pooling
|
68 |
+
|
69 |
+
return self.projection(cls_token+pooled_output)
|
70 |
+
|
71 |
+
class LVL(nn.Module):
|
72 |
+
def __init__(self):
|
73 |
+
super(LVL, self).__init__()
|
74 |
+
self.image_encoder = ImageEncoder()
|
75 |
+
self.text_encoder = RobertaEncoder()
|
76 |
+
self.t_prime = nn.Parameter(torch.ones([]) * np.log(0.07))
|
77 |
+
self.b = nn.Parameter(torch.ones([]) * 0)
|
78 |
+
|
79 |
+
def get_images_features(self,images):
|
80 |
+
image_embeddings = self.image_encoder(images) # (batch_size, EMBEDDING_DIM)
|
81 |
+
image_embeddings = nn.functional.normalize(image_embeddings, p=2, dim=-1)
|
82 |
+
return image_embeddings
|
83 |
+
|
84 |
+
def get_texts_feature(self,input_ids,attention_mask):
|
85 |
+
text_embeddings = self.text_encoder(input_ids, attention_mask) # (batch_size, EMBEDDING_DIM)
|
86 |
+
text_embeddings = nn.functional.normalize(text_embeddings, p=2, dim=-1)
|
87 |
+
return text_embeddings
|
88 |
+
|
89 |
+
def forward(self, images, input_ids, attention_mask):
|
90 |
+
"""
|
91 |
+
Args:
|
92 |
+
images: Tensor of shape (batch_size, 3, 224, 224)
|
93 |
+
input_ids: Tensor of shape (batch_size, seq_length)
|
94 |
+
attention_mask: Tensor of shape (batch_size, seq_length)
|
95 |
+
|
96 |
+
Returns:
|
97 |
+
Image and text embeddings normalized for similarity calculation
|
98 |
+
"""
|
99 |
+
|
100 |
+
image_embeddings = self.get_images_features(images)
|
101 |
+
text_embeddings = self.get_texts_feature(input_ids, attention_mask)
|
102 |
+
return image_embeddings, text_embeddings
|