marcusinthesky commited on
Commit
94b9488
1 Parent(s): c908178

Upload VTDE

Browse files
Files changed (3) hide show
  1. config.json +181 -0
  2. model.safetensors +3 -0
  3. modelling.py +172 -0
config.json ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": "66a47bbdac28fd423c63897fb3f9b453b072b307",
3
+ "_name_or_path": "flavour/clippy-dinov2-small-e5-small-v2",
4
+ "architectures": [
5
+ "VTDE"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "modelling.VTDEConfig",
9
+ "AutoModel": "modelling.VTDE"
10
+ },
11
+ "logit_scale_init_value": 2.6592,
12
+ "model_type": "vision-text-dual-encoder",
13
+ "projection_dim": 384,
14
+ "text_config": {
15
+ "_name_or_path": "intfloat/e5-small-v2",
16
+ "add_cross_attention": false,
17
+ "architectures": [
18
+ "BertModel"
19
+ ],
20
+ "attention_probs_dropout_prob": 0.1,
21
+ "bad_words_ids": null,
22
+ "begin_suppress_tokens": null,
23
+ "bos_token_id": null,
24
+ "chunk_size_feed_forward": 0,
25
+ "classifier_dropout": null,
26
+ "cross_attention_hidden_size": null,
27
+ "decoder_start_token_id": null,
28
+ "diversity_penalty": 0.0,
29
+ "do_sample": false,
30
+ "early_stopping": false,
31
+ "encoder_no_repeat_ngram_size": 0,
32
+ "eos_token_id": null,
33
+ "exponential_decay_length_penalty": null,
34
+ "finetuning_task": null,
35
+ "forced_bos_token_id": null,
36
+ "forced_eos_token_id": null,
37
+ "hidden_act": "gelu",
38
+ "hidden_dropout_prob": 0.1,
39
+ "hidden_size": 384,
40
+ "id2label": {
41
+ "0": "LABEL_0",
42
+ "1": "LABEL_1"
43
+ },
44
+ "initializer_range": 0.02,
45
+ "intermediate_size": 1536,
46
+ "is_decoder": false,
47
+ "is_encoder_decoder": false,
48
+ "label2id": {
49
+ "LABEL_0": 0,
50
+ "LABEL_1": 1
51
+ },
52
+ "layer_norm_eps": 1e-12,
53
+ "length_penalty": 1.0,
54
+ "max_length": 20,
55
+ "max_position_embeddings": 512,
56
+ "min_length": 0,
57
+ "model_type": "bert",
58
+ "no_repeat_ngram_size": 0,
59
+ "num_attention_heads": 12,
60
+ "num_beam_groups": 1,
61
+ "num_beams": 1,
62
+ "num_hidden_layers": 12,
63
+ "num_return_sequences": 1,
64
+ "output_attentions": false,
65
+ "output_hidden_states": false,
66
+ "output_scores": false,
67
+ "pad_token_id": 0,
68
+ "position_embedding_type": "absolute",
69
+ "prefix": null,
70
+ "problem_type": null,
71
+ "pruned_heads": {},
72
+ "remove_invalid_values": false,
73
+ "repetition_penalty": 1.0,
74
+ "return_dict": true,
75
+ "return_dict_in_generate": false,
76
+ "sep_token_id": null,
77
+ "suppress_tokens": null,
78
+ "task_specific_params": null,
79
+ "temperature": 1.0,
80
+ "tf_legacy_loss": false,
81
+ "tie_encoder_decoder": false,
82
+ "tie_word_embeddings": true,
83
+ "tokenizer_class": null,
84
+ "top_k": 50,
85
+ "top_p": 1.0,
86
+ "torch_dtype": "float32",
87
+ "torchscript": false,
88
+ "transformers_version": "4.32.0.dev0",
89
+ "type_vocab_size": 2,
90
+ "typical_p": 1.0,
91
+ "use_bfloat16": false,
92
+ "use_cache": true,
93
+ "vocab_size": 30522
94
+ },
95
+ "text_pooling_mode": "mean",
96
+ "torch_dtype": "float32",
97
+ "transformers_version": null,
98
+ "vision_config": {
99
+ "_name_or_path": "facebook/dinov2-small",
100
+ "add_cross_attention": false,
101
+ "architectures": [
102
+ "Dinov2Model"
103
+ ],
104
+ "attention_probs_dropout_prob": 0.0,
105
+ "bad_words_ids": null,
106
+ "begin_suppress_tokens": null,
107
+ "bos_token_id": null,
108
+ "chunk_size_feed_forward": 0,
109
+ "cross_attention_hidden_size": null,
110
+ "decoder_start_token_id": null,
111
+ "diversity_penalty": 0.0,
112
+ "do_sample": false,
113
+ "drop_path_rate": 0.0,
114
+ "early_stopping": false,
115
+ "encoder_no_repeat_ngram_size": 0,
116
+ "eos_token_id": null,
117
+ "exponential_decay_length_penalty": null,
118
+ "finetuning_task": null,
119
+ "forced_bos_token_id": null,
120
+ "forced_eos_token_id": null,
121
+ "hidden_act": "gelu",
122
+ "hidden_dropout_prob": 0.0,
123
+ "hidden_size": 384,
124
+ "id2label": {
125
+ "0": "LABEL_0",
126
+ "1": "LABEL_1"
127
+ },
128
+ "image_size": 518,
129
+ "initializer_range": 0.02,
130
+ "is_decoder": false,
131
+ "is_encoder_decoder": false,
132
+ "label2id": {
133
+ "LABEL_0": 0,
134
+ "LABEL_1": 1
135
+ },
136
+ "layer_norm_eps": 1e-06,
137
+ "layerscale_value": 1.0,
138
+ "length_penalty": 1.0,
139
+ "max_length": 20,
140
+ "min_length": 0,
141
+ "mlp_ratio": 4,
142
+ "model_type": "dinov2",
143
+ "no_repeat_ngram_size": 0,
144
+ "num_attention_heads": 6,
145
+ "num_beam_groups": 1,
146
+ "num_beams": 1,
147
+ "num_channels": 3,
148
+ "num_hidden_layers": 12,
149
+ "num_return_sequences": 1,
150
+ "output_attentions": false,
151
+ "output_hidden_states": false,
152
+ "output_scores": false,
153
+ "pad_token_id": null,
154
+ "patch_size": 14,
155
+ "prefix": null,
156
+ "problem_type": null,
157
+ "pruned_heads": {},
158
+ "qkv_bias": true,
159
+ "remove_invalid_values": false,
160
+ "repetition_penalty": 1.0,
161
+ "return_dict": true,
162
+ "return_dict_in_generate": false,
163
+ "sep_token_id": null,
164
+ "suppress_tokens": null,
165
+ "task_specific_params": null,
166
+ "temperature": 1.0,
167
+ "tf_legacy_loss": false,
168
+ "tie_encoder_decoder": false,
169
+ "tie_word_embeddings": true,
170
+ "tokenizer_class": null,
171
+ "top_k": 50,
172
+ "top_p": 1.0,
173
+ "torch_dtype": "float32",
174
+ "torchscript": false,
175
+ "transformers_version": "4.32.0.dev0",
176
+ "typical_p": 1.0,
177
+ "use_bfloat16": false,
178
+ "use_swiglu_ffn": false
179
+ },
180
+ "vision_pooling_mode": "max"
181
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e682c8dea59f1d00687358e8eae3a22954e5d4382acfe21c2e88e125b9bcdd19
3
+ size 223489116
modelling.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../notebooks/12_modelling.ipynb.
2
+
3
+ # %% auto 0
4
+ __all__ = ['VTDEConfig', 'VTDE']
5
+
6
+ # %% ../notebooks/12_modelling.ipynb 1
7
+ from transformers.models.clip.modeling_clip import CLIPOutput, clip_loss
8
+ from typing import Optional, Tuple, Union
9
+ from transformers import VisionTextDualEncoderConfig, AutoModel, PreTrainedModel, VisionTextDualEncoderModel
10
+ import torch
11
+
12
+ class VTDEConfig(VisionTextDualEncoderConfig):
13
+ def __init__(self, projection_dim=512, logit_scale_init_value=2.6592,
14
+ text_pooling_mode='mean',
15
+ vision_pooling_mode='max',
16
+ **kwargs):
17
+ """
18
+ pooling_mode in ['mean', 'max', 'cls']
19
+ https://arxiv.org/pdf/2210.09996.pdf
20
+ https://github.com/kahnchana/clippy/blob/3c102c29c32f7c66c6e52e09b795fe9c061bbb03/src/open_clip/hf_model.py#L56
21
+ """
22
+ self.text_pooling_mode = text_pooling_mode
23
+ self.vision_pooling_mode = vision_pooling_mode
24
+ super().__init__(projection_dim, logit_scale_init_value, **kwargs)
25
+
26
+ class VTDE(VisionTextDualEncoderModel):
27
+ config_class = VTDEConfig
28
+ base_model_prefix = "vtde"
29
+
30
+ def __init__(
31
+ self,
32
+ config: Optional[VTDEConfig] = None,
33
+ vision_model: Optional[PreTrainedModel] = None,
34
+ text_model: Optional[PreTrainedModel] = None,
35
+ ):
36
+ # You can customize the constructor if needed
37
+ super().__init__(config, vision_model, text_model)
38
+ self.text_pooling_mode = config.text_pooling_mode
39
+ self.vision_pooling_mode = config.vision_pooling_mode
40
+
41
+ def get_text_features(
42
+ self,
43
+ input_ids=None,
44
+ attention_mask=None,
45
+ position_ids=None,
46
+ token_type_ids=None,
47
+ output_attentions=None,
48
+ output_hidden_states=None,
49
+ return_dict=None,
50
+ ):
51
+ text_outputs = self.text_model(
52
+ input_ids=input_ids,
53
+ attention_mask=attention_mask,
54
+ token_type_ids=token_type_ids,
55
+ position_ids=position_ids,
56
+ output_attentions=output_attentions,
57
+ output_hidden_states=output_hidden_states,
58
+ return_dict=return_dict,
59
+ )
60
+ if self.text_pooling_mode == 'cls':
61
+ pooled_output = text_outputs[1]
62
+ elif self.text_pooling_mode == 'mean':
63
+ pooled_output = torch.mean(text_outputs[0], dim=1)
64
+ elif self.text_pooling_mode == 'max':
65
+ pooled_output = torch.max(text_outputs[0], dim=1)[0]
66
+ elif self.text_pooling_mode == 'norm':
67
+ """we select the patch with the largest norm"""
68
+ last_hidden_states = text_outputs[0]
69
+ patch_norms = torch.norm(last_hidden_states[:, :-1, :], dim=-1)
70
+ max_norm_idx = torch.argmax(patch_norms, dim=1)
71
+ pooled_output = last_hidden_states[:, max_norm_idx, :][:, 0, :]
72
+ else:
73
+ "We want to raise the name of the pooling mode"
74
+ raise NotImplementedError
75
+
76
+ text_features = self.text_projection(pooled_output)
77
+
78
+ return text_features
79
+
80
+ def get_image_features(
81
+ self,
82
+ pixel_values=None,
83
+ output_attentions=None,
84
+ output_hidden_states=None,
85
+ return_dict=None,
86
+ ):
87
+ vision_outputs = self.vision_model(
88
+ pixel_values=pixel_values,
89
+ output_attentions=output_attentions,
90
+ output_hidden_states=output_hidden_states,
91
+ return_dict=return_dict,
92
+ )
93
+
94
+ if self.vision_pooling_mode == 'cls':
95
+ pooled_output = vision_outputs[1]
96
+ elif self.vision_pooling_mode == 'mean':
97
+ pooled_output = torch.mean(vision_outputs[0], dim=1)
98
+ elif self.vision_pooling_mode == 'max':
99
+ pooled_output = torch.max(vision_outputs[0], dim=1)[0]
100
+ elif self.vision_pooling_mode == 'norm':
101
+ """we select the patch with the largest norm"""
102
+ last_hidden_states = vision_outputs[0]
103
+ patch_norms = torch.norm(last_hidden_states[:, :-1, :], dim=-1)
104
+ max_norm_idx = torch.argmax(patch_norms, dim=1)
105
+ pooled_output = last_hidden_states[:, max_norm_idx, :][:, 0, :]
106
+ else:
107
+ raise NotImplementedError
108
+
109
+ image_features = self.visual_projection(pooled_output)
110
+
111
+ return image_features
112
+
113
+ def forward(
114
+ self,
115
+ input_ids: Optional[torch.LongTensor] = None,
116
+ pixel_values: Optional[torch.FloatTensor] = None,
117
+ attention_mask: Optional[torch.Tensor] = None,
118
+ position_ids: Optional[torch.LongTensor] = None,
119
+ return_loss: Optional[bool] = None,
120
+ token_type_ids: Optional[torch.LongTensor] = None,
121
+ output_attentions: Optional[bool] = None,
122
+ output_hidden_states: Optional[bool] = None,
123
+ return_dict: Optional[bool] = None,
124
+ ) -> Union[Tuple[torch.Tensor], CLIPOutput]:
125
+
126
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
127
+
128
+ image_embeds = self.get_image_features(
129
+ pixel_values=pixel_values,
130
+ output_attentions=output_attentions,
131
+ output_hidden_states=output_hidden_states,
132
+ return_dict=return_dict,
133
+ )
134
+
135
+ text_embeds = self.get_text_features(
136
+ input_ids=input_ids,
137
+ attention_mask=attention_mask,
138
+ position_ids=position_ids,
139
+ output_attentions=output_attentions,
140
+ output_hidden_states=output_hidden_states,
141
+ return_dict=return_dict,
142
+ )
143
+
144
+ # normalized features
145
+ image_embeds = image_embeds / image_embeds.norm(dim=-1, keepdim=True)
146
+ text_embeds = text_embeds / text_embeds.norm(dim=-1, keepdim=True)
147
+
148
+ # cosine similarity as logits
149
+ logit_scale = self.logit_scale.exp()
150
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
151
+ logits_per_image = logits_per_text.T
152
+
153
+ loss = None
154
+ if return_loss:
155
+ loss = clip_loss(logits_per_text)
156
+
157
+ if not return_dict:
158
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
159
+ return ((loss,) + output) if loss is not None else output
160
+
161
+ return CLIPOutput(
162
+ loss=loss,
163
+ logits_per_image=logits_per_image,
164
+ logits_per_text=logits_per_text,
165
+ text_embeds=text_embeds,
166
+ image_embeds=image_embeds,
167
+ text_model_output=text_embeds,
168
+ vision_model_output=image_embeds,
169
+ )
170
+
171
+ VTDEConfig.register_for_auto_class()
172
+ VTDE.register_for_auto_class("AutoModel")