File size: 3,751 Bytes
df511be
 
 
 
 
 
 
 
 
259423f
df511be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import torch
import torch.nn as nn
from transformers import CLIPTextModel, RobertaModel, CLIPVisionModel
from timm import create_model
EMBEDDING_DIM = 512
class ImageEncoder(nn.Module):
    def __init__(self):
        super(ImageEncoder, self).__init__()
        # Load the Swin Transformer with features_only=True
        self.swin = create_model("swin-tiny-patch4-window7-224", pretrained=True, features_only=True)
        for param in self.swin.parameters():
            param.requires_grad = True

        # Get the feature size of the final stage
        self.swin_output_dim = self.swin.feature_info.channels()[-1]  # Last stage: 1024 channels

        # Define FC layer
        self.fc1 = nn.Linear(self.swin_output_dim * 7 * 7, EMBEDDING_DIM)  # Flattened input size
        nn.init.xavier_uniform_(self.fc1.weight)
        nn.init.zeros_(self.fc1.bias)
        for param in self.fc1.parameters():
            param.requires_grad = True


    def forward(self, x):
        # Extract features from Swin
        swin_features = self.swin(x)[-1]  # Use the last stage feature map (e.g., [B, 1024, 7, 7])

        # Flatten feature map
        swin_features = swin_features.view(swin_features.size(0), -1)  # Shape: (B, 1024*7*7)

        # Pass through FC layer
        output = self.fc1(swin_features)  # Shape: (B, embedding_dim)
        return output

from transformers import RobertaModel

class RobertaEncoder(nn.Module):
    def __init__(self, roberta_model_path="roberta-base"):
        super(RobertaEncoder, self).__init__()
        # Load pre-trained RoBERTa model
        self.roberta = RobertaModel.from_pretrained(roberta_model_path)

        # Add a linear projection layer to reduce dimensionality
        self.projection = nn.Linear(self.roberta.config.hidden_size, EMBEDDING_DIM)

        # Initialize the projection layer weights
        nn.init.xavier_uniform_(self.projection.weight)
        nn.init.zeros_(self.projection.bias)

        # Allow fine-tuning of the RoBERTa model
        for param in self.roberta.parameters():
            param.requires_grad = True

    def forward(self, input_ids, attention_mask):
        """
        Forward pass through RoBERTa.
        Args:
            input_ids: Tensor of shape (batch_size, seq_length)
            attention_mask: Tensor of shape (batch_size, seq_length)

        Returns:
            Embedding: Tensor of shape (batch_size, EMBEDDING_DIM)
        """
        roberta_output = self.roberta(input_ids=input_ids, attention_mask=attention_mask)
        cls_token = roberta_output.last_hidden_state[:, 0, :]  # Use CLS token
        pooled_output = torch.mean(roberta_output.last_hidden_state, dim=1)  # Mean pooling

        return self.projection(cls_token+pooled_output)

from transformers import AutoTokenizer, Siglip2TextModel,AutoModel


class SigLIP2TextEncoder(nn.Module):
    def __init__(self, embedding_dim=512):
        super(SigLIP2TextEncoder, self).__init__()
        model  = AutoModel.from_pretrained("google/siglip2-base-patch16-224")
        self.text_encoder = model.text_model
        hidden_size = self.text_encoder.config.hidden_size
        self.projection = nn.Linear(hidden_size, embedding_dim)

        nn.init.xavier_uniform_(self.projection.weight)
        nn.init.zeros_(self.projection.bias)

        for param in self.text_encoder.parameters():
            param.requires_grad = True
        for param in self.projection.parameters():
            param.requires_grad = True

    def forward(self, tokens):
        """
        Args:
            tokens:

        Returns:
            Tensor of shape (batch_size, embedding_dim)
        """

        outputs = self.text_encoder(**tokens)

        return self.projection(outputs.pooler_output)