mpatel57 commited on
Commit
4afcd9a
1 Parent(s): 56ad9ea

Upload folder using huggingface_hub

Browse files
text-encoder/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CLIPTextEncoderOnly"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "utils.CLIPTextEncoderOnlyConfig",
8
+ "AutoModel": "utils.CLIPTextEncoderOnly"
9
+ },
10
+ "bos_token_id": 49406,
11
+ "eos_token_id": 49407,
12
+ "frozen": false,
13
+ "hidden_act": "quick_gelu",
14
+ "hidden_size": 512,
15
+ "initializer_factor": 1.0,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 2048,
18
+ "layer_norm_eps": 1e-05,
19
+ "lora": null,
20
+ "max_position_embeddings": 77,
21
+ "model_name": "openai/clip-vit-base-patch32",
22
+ "model_type": "clip_custom_text_model",
23
+ "num_attention_heads": 8,
24
+ "num_hidden_layers": 12,
25
+ "pad_token_id": 1,
26
+ "pretrained": false,
27
+ "projection_dim": 512,
28
+ "torch_dtype": "float32",
29
+ "transformers_version": "4.40.1",
30
+ "vocab_size": 49408
31
+ }
text-encoder/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6e3b87fbd1e1b69105e5175bdb8ec486526baae1ae82b1e92b4ae976caab0d5
3
+ size 253736912
text-encoder/utils.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig, AutoModel, PretrainedConfig, CLIPTextConfig, CLIPVisionConfig, PreTrainedModel, CLIPTextModelWithProjection, CLIPVisionModelWithProjection
2
+ from transformers.utils import ModelOutput
3
+ import torch
4
+ import open_clip
5
+ from dataclasses import dataclass
6
+ import safetensors.torch
7
+ from peft import get_peft_config, get_peft_model, LoraConfig, TaskType
8
+ import os
9
+
10
+ HF_SAFE_WEIGHTS_NAME = "open_clip_model.safetensors"
11
+ HF_SAFE_WEIGHTS_NAME_PRIOR = "prior_model.safetensors"
12
+
13
+ @dataclass
14
+ class PriorTransformerOutput(ModelOutput):
15
+ """
16
+ The output of [`PriorTransformer`].
17
+
18
+ Args:
19
+ predicted_image_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`):
20
+ The predicted CLIP image embedding conditioned on the CLIP text embedding input.
21
+ """
22
+
23
+ predicted_image_embedding: torch.FloatTensor
24
+
25
+ @dataclass
26
+ class TextEncoderOutput(ModelOutput):
27
+ """
28
+ Output class for CLIPTextEncoderOnly model to store the outputs in a Hugging Face transformer style.
29
+
30
+ Attributes:
31
+ prompt_embeds (torch.Tensor): The embeddings of the input prompts.
32
+ last_hidden_states (torch.Tensor): The last hidden states from the model.
33
+ """
34
+ text_embeds: torch.FloatTensor = None
35
+ last_hidden_state: torch.FloatTensor = None
36
+
37
+ class CLIPTextEncoderOnlyConfig(CLIPTextConfig):
38
+ model_type = "clip_custom_text_model"
39
+
40
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
41
+ self.model_name = model_name
42
+ self.pretrained = pretrained
43
+ self.frozen = frozen
44
+ self.lora = lora
45
+ super().__init__(**kwargs)
46
+
47
+ class CLIPTextEncoderOnly(PreTrainedModel):
48
+ config_class = CLIPTextEncoderOnlyConfig
49
+
50
+ def __init__(self, config):
51
+ """
52
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
53
+
54
+ :param model_name: The name or path of the pretrained model.
55
+ :param pretrained: Whether to load the pretrained weights.
56
+ """
57
+ super().__init__(config)
58
+
59
+ if config.pretrained:
60
+ self.model = CLIPTextModelWithProjection.from_pretrained(config.model_name)
61
+ else:
62
+ base_cfg = CLIPTextConfig.from_pretrained(config.model_name)
63
+ self.model = CLIPTextModelWithProjection(base_cfg)
64
+
65
+ if config.lora:
66
+ l_config = LoraConfig(
67
+ r=config.lora.lora_r,
68
+ lora_alpha=config.lora.lora_alpha,
69
+ target_modules=[
70
+ "k_proj",
71
+ "v_proj",
72
+ "q_proj",
73
+ "out_proj",
74
+ "fc1",
75
+ "fc2",
76
+ "visual_projection",
77
+ "text_projection"
78
+ ],
79
+ lora_dropout=config.lora.lora_dropout,
80
+ bias="lora_only",
81
+ )
82
+ self.model = get_peft_model(self.model, l_config)
83
+
84
+
85
+ def forward(self, input_ids, attention_mask=None, position_ids=None):
86
+ """
87
+ Forward pass of the model.
88
+
89
+ :param input_ids: Indices of input sequence tokens in the vocabulary.
90
+ :param attention_mask: Mask to avoid performing attention on padding token indices.
91
+ :param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
92
+ :return: Outputs of the model.
93
+ """
94
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_hidden_states=True)
95
+ return TextEncoderOutput(text_embeds=outputs.text_embeds, last_hidden_state=outputs.last_hidden_state)
96
+
97
+
98
+ class CustomTextEncoderOnlyConfig(PretrainedConfig):
99
+ model_type = "whole_custom_text_model"
100
+
101
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, output_hidden_size: int = 512, last_hidden_state: bool = False, lora: dict = None, **kwargs):
102
+ self.model_name = model_name
103
+ self.pretrained = pretrained
104
+ self.frozen = frozen
105
+ self.output_hidden_size = output_hidden_size
106
+ self.last_hidden_state = last_hidden_state
107
+ self.lora = lora
108
+ super().__init__(**kwargs)
109
+
110
+ class CustomTextEncoderOnly(PreTrainedModel):
111
+ config_class = CustomTextEncoderOnlyConfig
112
+
113
+ def __init__(self, config):
114
+ """
115
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
116
+
117
+ :param model_name: The name or path of the pretrained model.
118
+ :param pretrained: Whether to load the pretrained weights.
119
+ """
120
+ super().__init__(config)
121
+
122
+ self.last_hidden_state = config.last_hidden_state
123
+
124
+ if config.pretrained:
125
+ self.model = AutoModel.from_pretrained(config.model_name)
126
+ if config.frozen:
127
+ for param in self.model.parameters():
128
+ param.requires_grad = False
129
+ else:
130
+ self.model = AutoModel(config)
131
+
132
+ self.fc1 = torch.nn.Linear(self.model.config.hidden_size, config.output_hidden_size)
133
+ if config.last_hidden_state:
134
+ self.fc2 = torch.nn.Linear(self.model.config.hidden_size, config.output_hidden_size)
135
+
136
+ if config.lora:
137
+ l_config = LoraConfig(
138
+ task_type=TaskType.FEATURE_EXTRACTION,
139
+ r=config.lora.lora_r,
140
+ lora_alpha=config.lora.lora_alpha,
141
+ lora_dropout=config.lora.lora_dropout,
142
+ bias="lora_only",
143
+ )
144
+ self.model = get_peft_model(self.model, l_config)
145
+
146
+ def forward(self, input_ids, attention_mask=None, token_type_ids=None):
147
+ """
148
+ Forward pass of the model.
149
+
150
+ :param input_ids: Indices of input sequence tokens in the vocabulary.
151
+ :param attention_mask: Mask to avoid performing attention on padding token indices.
152
+ :param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
153
+ :return: Outputs of the model.
154
+ """
155
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, output_hidden_states=True)
156
+ text_embeds = self.fc1(outputs[1])
157
+ last_hidden_state = None
158
+ if self.last_hidden_state:
159
+ last_hidden_state = self.fc2(outputs[0])
160
+ else:
161
+ last_hidden_state = outputs[0]
162
+ return TextEncoderOutput(text_embeds=text_embeds, last_hidden_state=last_hidden_state)
163
+
164
+ class CLIPVisionEncoderOnlyConfig(PretrainedConfig):
165
+ model_type = "clip_custom_vision_model"
166
+
167
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
168
+ self.model_name = model_name
169
+ self.pretrained = pretrained
170
+ self.frozen = frozen
171
+ self.lora = lora
172
+ super().__init__(**kwargs)
173
+
174
+ class CLIPVisionEncoderOnly(PreTrainedModel):
175
+ config_class = CLIPVisionEncoderOnlyConfig
176
+
177
+ def __init__(self, config):
178
+ """
179
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
180
+
181
+ :param model_name: The name or path of the pretrained model.
182
+ :param pretrained: Whether to load the pretrained weights.
183
+ """
184
+ super().__init__(config)
185
+
186
+ if config.pretrained:
187
+ self.model = CLIPVisionModelWithProjection.from_pretrained(config.model_name)
188
+ else:
189
+ base_cfg = CLIPVisionConfig.from_pretrained(config.model_name)
190
+ self.model = CLIPVisionModelWithProjection(base_cfg)
191
+
192
+ if config.lora:
193
+ l_config = LoraConfig(
194
+ r=config.lora.lora_r,
195
+ lora_alpha=config.lora.lora_alpha,
196
+ target_modules=[
197
+ "k_proj",
198
+ "v_proj",
199
+ "q_proj",
200
+ "out_proj",
201
+ "fc1",
202
+ "fc2",
203
+ "visual_projection",
204
+ "text_projection"
205
+ ],
206
+ lora_dropout=config.lora.lora_dropout,
207
+ bias="lora_only",
208
+ )
209
+ self.model = get_peft_model(self.model, l_config)
210
+
211
+ def forward(self, data):
212
+ """
213
+ Forward pass of the model.
214
+ """
215
+ return self.model(**data).image_embeds
216
+
217
+ def parameters(self):
218
+ return self.model.parameters()
219
+
220
+
221
+ class OpenCLIPVisionEncoderOnly(torch.nn.Module):
222
+ def __init__(self, model_name: str, pretrained: bool = True, frozen: bool = False, lora: dict = None):
223
+ """
224
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
225
+
226
+ :param model_name: The name or path of the pretrained model.
227
+ :param pretrained: Whether to load the pretrained weights.
228
+ """
229
+ super().__init__()
230
+ if pretrained:
231
+ model, _ = open_clip.create_model_from_pretrained(f"hf-hub:{model_name}")
232
+ model = model.visual
233
+ else:
234
+ raise NotImplemented
235
+ self.model = model
236
+
237
+ if lora:
238
+ l_config = LoraConfig(
239
+ r=lora.lora_r,
240
+ lora_alpha=lora.lora_alpha,
241
+ target_modules=[
242
+ "k_proj",
243
+ "v_proj",
244
+ "q_proj",
245
+ "out_proj",
246
+ "fc1",
247
+ "fc2",
248
+ "visual_projection",
249
+ "text_projection"
250
+ ],
251
+ lora_dropout=lora.lora_dropout,
252
+ bias="lora_only",
253
+ )
254
+ self.model = get_peft_model(self.model, l_config)
255
+
256
+ def forward(self, image):
257
+ """
258
+ Forward pass of the model.
259
+ """
260
+ return self.model(image)
261
+
262
+ def save_pretrained(self, save_dir):
263
+ tensors = self.model.state_dict()
264
+ safetensors.torch.save_file(tensors, save_dir / HF_SAFE_WEIGHTS_NAME)
265
+
266
+ class CustomPriorModel(torch.nn.Module):
267
+ def __init__(self, in_hidden_state, out_hidden_state):
268
+ """
269
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
270
+
271
+ :param model_name: The name or path of the pretrained model.
272
+ :param pretrained: Whether to load the pretrained weights.
273
+ """
274
+ super().__init__()
275
+ mid_hidden_state = max(in_hidden_state, out_hidden_state)
276
+
277
+ self.fc1 = torch.nn.Linear(in_hidden_state*2, mid_hidden_state)
278
+ self.relu = torch.nn.ReLU()
279
+ self.fc2 = torch.nn.Linear(mid_hidden_state, out_hidden_state)
280
+
281
+ def reinitialize_model(self):
282
+ for name, param in self.named_parameters():
283
+ if param.requires_grad:
284
+ if len(param.shape) > 1:
285
+ torch.nn.init.xavier_uniform_(param)
286
+ else:
287
+ if 'weight' in name:
288
+ torch.nn.init.normal_(param)
289
+ else:
290
+ torch.nn.init.zeros_(param)
291
+
292
+ def forward(self, feats):
293
+ """
294
+ Forward pass of the model.
295
+ """
296
+ return PriorTransformerOutput(predicted_image_embedding=self.fc2(self.relu(self.fc1(feats))))
297
+
298
+ def save_pretrained(self, save_dir):
299
+ pass
300
+ # tensors = self.state_dict()
301
+ # safetensors.torch.save_file(tensors, os.path.join(save_dir, HF_SAFE_WEIGHTS_NAME_PRIOR))
302
+
303
+
304
+ def test_text_model(register=False, upload=False):
305
+ # register the classes
306
+ if register:
307
+ AutoConfig.register("clip_custom_text_model", CLIPTextEncoderOnlyConfig)
308
+ AutoModel.register(CLIPTextEncoderOnlyConfig, CLIPTextEncoderOnly)
309
+ CLIPTextEncoderOnlyConfig.register_for_auto_class()
310
+ CLIPTextEncoderOnly.register_for_auto_class("AutoModel")
311
+
312
+ if upload:
313
+ # Initialize the model
314
+ model_name = "openai/clip-vit-base-patch32"
315
+ pretrained=True
316
+ lora=None
317
+
318
+ cfg = CLIPTextEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
319
+ model = CLIPTextEncoderOnly(cfg)
320
+ model.push_to_hub("test-text-hf-upload")
321
+
322
+ model = CLIPTextEncoderOnly.from_pretrained("mpatel57/test-text-hf-upload", force_download=True)
323
+
324
+ def test_custom_text_model(register=False, upload=False):
325
+ # register the classes
326
+ if register:
327
+ AutoConfig.register("whole_custom_text_model", CustomTextEncoderOnlyConfig)
328
+ AutoModel.register(CustomTextEncoderOnlyConfig, CustomTextEncoderOnly)
329
+ CustomTextEncoderOnlyConfig.register_for_auto_class()
330
+ CustomTextEncoderOnly.register_for_auto_class("AutoModel")
331
+
332
+ if upload:
333
+ # Initialize the model
334
+ model_name = "google-bert/bert-base-uncased"
335
+ pretrained=True
336
+ frozen=False
337
+ output_hidden_size=512
338
+ last_hidden_state=False
339
+
340
+ lora=None
341
+
342
+ cfg = CustomTextEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, frozen=frozen, output_hidden_size=output_hidden_size, last_hidden_state=last_hidden_state, lora=lora)
343
+ model = CustomTextEncoderOnly(cfg)
344
+ model.push_to_hub("test-text-hf-upload")
345
+
346
+ model = CustomTextEncoderOnly.from_pretrained("mpatel57/test-text-hf-upload", force_download=True)
347
+
348
+ def test_vision_model(register=False, upload=False):
349
+ # register the classes
350
+ if register:
351
+ AutoConfig.register("clip_custom_vision_model", CLIPVisionEncoderOnlyConfig)
352
+ AutoModel.register(CLIPVisionEncoderOnlyConfig, CLIPVisionEncoderOnly)
353
+ CLIPVisionEncoderOnlyConfig.register_for_auto_class()
354
+ CLIPVisionEncoderOnly.register_for_auto_class("AutoModel")
355
+
356
+ if upload:
357
+ # Initialize the model
358
+ model_name = "openai/clip-vit-base-patch32"
359
+ pretrained=True
360
+ lora=None
361
+
362
+ cfg = CLIPVisionEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
363
+ model = CLIPVisionEncoderOnly(cfg)
364
+ model.push_to_hub("test-vision-hf-upload")
365
+
366
+ model = CLIPVisionEncoderOnly.from_pretrained("mpatel57/test-vision-hf-upload", force_download=True)
367
+
368
+
369
+ if __name__ == "__main__":
370
+ test_custom_text_model(register=False, upload=True)
371
+ # test_text_model(register=False, upload=True)
372
+ # test_vision_model(register=False, upload=True)
utils.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig, AutoModel, PretrainedConfig, CLIPTextConfig, CLIPVisionConfig, PreTrainedModel, CLIPTextModelWithProjection, CLIPVisionModelWithProjection
2
+ from transformers.utils import ModelOutput
3
+ import torch
4
+ import open_clip
5
+ from dataclasses import dataclass
6
+ import safetensors.torch
7
+ from peft import get_peft_config, get_peft_model, LoraConfig, TaskType
8
+ import os
9
+
10
+ HF_SAFE_WEIGHTS_NAME = "open_clip_model.safetensors"
11
+ HF_SAFE_WEIGHTS_NAME_PRIOR = "prior_model.safetensors"
12
+
13
+ @dataclass
14
+ class PriorTransformerOutput(ModelOutput):
15
+ """
16
+ The output of [`PriorTransformer`].
17
+
18
+ Args:
19
+ predicted_image_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`):
20
+ The predicted CLIP image embedding conditioned on the CLIP text embedding input.
21
+ """
22
+
23
+ predicted_image_embedding: torch.FloatTensor
24
+
25
+ @dataclass
26
+ class TextEncoderOutput(ModelOutput):
27
+ """
28
+ Output class for CLIPTextEncoderOnly model to store the outputs in a Hugging Face transformer style.
29
+
30
+ Attributes:
31
+ prompt_embeds (torch.Tensor): The embeddings of the input prompts.
32
+ last_hidden_states (torch.Tensor): The last hidden states from the model.
33
+ """
34
+ text_embeds: torch.FloatTensor = None
35
+ last_hidden_state: torch.FloatTensor = None
36
+
37
+ class CLIPTextEncoderOnlyConfig(CLIPTextConfig):
38
+ model_type = "clip_custom_text_model"
39
+
40
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
41
+ self.model_name = model_name
42
+ self.pretrained = pretrained
43
+ self.frozen = frozen
44
+ self.lora = lora
45
+ super().__init__(**kwargs)
46
+
47
+ class CLIPTextEncoderOnly(PreTrainedModel):
48
+ config_class = CLIPTextEncoderOnlyConfig
49
+
50
+ def __init__(self, config):
51
+ """
52
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
53
+
54
+ :param model_name: The name or path of the pretrained model.
55
+ :param pretrained: Whether to load the pretrained weights.
56
+ """
57
+ super().__init__(config)
58
+
59
+ if config.pretrained:
60
+ self.model = CLIPTextModelWithProjection.from_pretrained(config.model_name)
61
+ else:
62
+ base_cfg = CLIPTextConfig.from_pretrained(config.model_name)
63
+ self.model = CLIPTextModelWithProjection(base_cfg)
64
+
65
+ if config.lora:
66
+ l_config = LoraConfig(
67
+ r=config.lora.lora_r,
68
+ lora_alpha=config.lora.lora_alpha,
69
+ target_modules=[
70
+ "k_proj",
71
+ "v_proj",
72
+ "q_proj",
73
+ "out_proj",
74
+ "fc1",
75
+ "fc2",
76
+ "visual_projection",
77
+ "text_projection"
78
+ ],
79
+ lora_dropout=config.lora.lora_dropout,
80
+ bias="lora_only",
81
+ )
82
+ self.model = get_peft_model(self.model, l_config)
83
+
84
+
85
+ def forward(self, input_ids, attention_mask=None, position_ids=None):
86
+ """
87
+ Forward pass of the model.
88
+
89
+ :param input_ids: Indices of input sequence tokens in the vocabulary.
90
+ :param attention_mask: Mask to avoid performing attention on padding token indices.
91
+ :param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
92
+ :return: Outputs of the model.
93
+ """
94
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_hidden_states=True)
95
+ return TextEncoderOutput(text_embeds=outputs.text_embeds, last_hidden_state=outputs.last_hidden_state)
96
+
97
+
98
+ class CustomTextEncoderOnlyConfig(PretrainedConfig):
99
+ model_type = "whole_custom_text_model"
100
+
101
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, output_hidden_size: int = 512, last_hidden_state: bool = False, lora: dict = None, **kwargs):
102
+ self.model_name = model_name
103
+ self.pretrained = pretrained
104
+ self.frozen = frozen
105
+ self.output_hidden_size = output_hidden_size
106
+ self.last_hidden_state = last_hidden_state
107
+ self.lora = lora
108
+ super().__init__(**kwargs)
109
+
110
+ class CustomTextEncoderOnly(PreTrainedModel):
111
+ config_class = CustomTextEncoderOnlyConfig
112
+
113
+ def __init__(self, config):
114
+ """
115
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
116
+
117
+ :param model_name: The name or path of the pretrained model.
118
+ :param pretrained: Whether to load the pretrained weights.
119
+ """
120
+ super().__init__(config)
121
+
122
+ self.last_hidden_state = config.last_hidden_state
123
+
124
+ if config.pretrained:
125
+ self.model = AutoModel.from_pretrained(config.model_name)
126
+ if config.frozen:
127
+ for param in self.model.parameters():
128
+ param.requires_grad = False
129
+ else:
130
+ self.model = AutoModel(config)
131
+
132
+ self.fc1 = torch.nn.Linear(self.model.config.hidden_size, config.output_hidden_size)
133
+ if config.last_hidden_state:
134
+ self.fc2 = torch.nn.Linear(self.model.config.hidden_size, config.output_hidden_size)
135
+
136
+ if config.lora:
137
+ l_config = LoraConfig(
138
+ task_type=TaskType.FEATURE_EXTRACTION,
139
+ r=config.lora.lora_r,
140
+ lora_alpha=config.lora.lora_alpha,
141
+ lora_dropout=config.lora.lora_dropout,
142
+ bias="lora_only",
143
+ )
144
+ self.model = get_peft_model(self.model, l_config)
145
+
146
+ def forward(self, input_ids, attention_mask=None, token_type_ids=None):
147
+ """
148
+ Forward pass of the model.
149
+
150
+ :param input_ids: Indices of input sequence tokens in the vocabulary.
151
+ :param attention_mask: Mask to avoid performing attention on padding token indices.
152
+ :param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
153
+ :return: Outputs of the model.
154
+ """
155
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, output_hidden_states=True)
156
+ text_embeds = self.fc1(outputs[1])
157
+ last_hidden_state = None
158
+ if self.last_hidden_state:
159
+ last_hidden_state = self.fc2(outputs[0])
160
+ else:
161
+ last_hidden_state = outputs[0]
162
+ return TextEncoderOutput(text_embeds=text_embeds, last_hidden_state=last_hidden_state)
163
+
164
+ class CLIPVisionEncoderOnlyConfig(PretrainedConfig):
165
+ model_type = "clip_custom_vision_model"
166
+
167
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
168
+ self.model_name = model_name
169
+ self.pretrained = pretrained
170
+ self.frozen = frozen
171
+ self.lora = lora
172
+ super().__init__(**kwargs)
173
+
174
+ class CLIPVisionEncoderOnly(PreTrainedModel):
175
+ config_class = CLIPVisionEncoderOnlyConfig
176
+
177
+ def __init__(self, config):
178
+ """
179
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
180
+
181
+ :param model_name: The name or path of the pretrained model.
182
+ :param pretrained: Whether to load the pretrained weights.
183
+ """
184
+ super().__init__(config)
185
+
186
+ if config.pretrained:
187
+ self.model = CLIPVisionModelWithProjection.from_pretrained(config.model_name)
188
+ else:
189
+ base_cfg = CLIPVisionConfig.from_pretrained(config.model_name)
190
+ self.model = CLIPVisionModelWithProjection(base_cfg)
191
+
192
+ if config.lora:
193
+ l_config = LoraConfig(
194
+ r=config.lora.lora_r,
195
+ lora_alpha=config.lora.lora_alpha,
196
+ target_modules=[
197
+ "k_proj",
198
+ "v_proj",
199
+ "q_proj",
200
+ "out_proj",
201
+ "fc1",
202
+ "fc2",
203
+ "visual_projection",
204
+ "text_projection"
205
+ ],
206
+ lora_dropout=config.lora.lora_dropout,
207
+ bias="lora_only",
208
+ )
209
+ self.model = get_peft_model(self.model, l_config)
210
+
211
+ def forward(self, data):
212
+ """
213
+ Forward pass of the model.
214
+ """
215
+ return self.model(**data).image_embeds
216
+
217
+ def parameters(self):
218
+ return self.model.parameters()
219
+
220
+
221
+ class OpenCLIPVisionEncoderOnly(torch.nn.Module):
222
+ def __init__(self, model_name: str, pretrained: bool = True, frozen: bool = False, lora: dict = None):
223
+ """
224
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
225
+
226
+ :param model_name: The name or path of the pretrained model.
227
+ :param pretrained: Whether to load the pretrained weights.
228
+ """
229
+ super().__init__()
230
+ if pretrained:
231
+ model, _ = open_clip.create_model_from_pretrained(f"hf-hub:{model_name}")
232
+ model = model.visual
233
+ else:
234
+ raise NotImplemented
235
+ self.model = model
236
+
237
+ if lora:
238
+ l_config = LoraConfig(
239
+ r=lora.lora_r,
240
+ lora_alpha=lora.lora_alpha,
241
+ target_modules=[
242
+ "k_proj",
243
+ "v_proj",
244
+ "q_proj",
245
+ "out_proj",
246
+ "fc1",
247
+ "fc2",
248
+ "visual_projection",
249
+ "text_projection"
250
+ ],
251
+ lora_dropout=lora.lora_dropout,
252
+ bias="lora_only",
253
+ )
254
+ self.model = get_peft_model(self.model, l_config)
255
+
256
+ def forward(self, image):
257
+ """
258
+ Forward pass of the model.
259
+ """
260
+ return self.model(image)
261
+
262
+ def save_pretrained(self, save_dir):
263
+ tensors = self.model.state_dict()
264
+ safetensors.torch.save_file(tensors, save_dir / HF_SAFE_WEIGHTS_NAME)
265
+
266
+ class CustomPriorModel(torch.nn.Module):
267
+ def __init__(self, in_hidden_state, out_hidden_state):
268
+ """
269
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
270
+
271
+ :param model_name: The name or path of the pretrained model.
272
+ :param pretrained: Whether to load the pretrained weights.
273
+ """
274
+ super().__init__()
275
+ mid_hidden_state = max(in_hidden_state, out_hidden_state)
276
+
277
+ self.fc1 = torch.nn.Linear(in_hidden_state*2, mid_hidden_state)
278
+ self.relu = torch.nn.ReLU()
279
+ self.fc2 = torch.nn.Linear(mid_hidden_state, out_hidden_state)
280
+
281
+ def reinitialize_model(self):
282
+ for name, param in self.named_parameters():
283
+ if param.requires_grad:
284
+ if len(param.shape) > 1:
285
+ torch.nn.init.xavier_uniform_(param)
286
+ else:
287
+ if 'weight' in name:
288
+ torch.nn.init.normal_(param)
289
+ else:
290
+ torch.nn.init.zeros_(param)
291
+
292
+ def forward(self, feats):
293
+ """
294
+ Forward pass of the model.
295
+ """
296
+ return PriorTransformerOutput(predicted_image_embedding=self.fc2(self.relu(self.fc1(feats))))
297
+
298
+ def save_pretrained(self, save_dir):
299
+ pass
300
+ # tensors = self.state_dict()
301
+ # safetensors.torch.save_file(tensors, os.path.join(save_dir, HF_SAFE_WEIGHTS_NAME_PRIOR))
302
+
303
+
304
+ def test_text_model(register=False, upload=False):
305
+ # register the classes
306
+ if register:
307
+ AutoConfig.register("clip_custom_text_model", CLIPTextEncoderOnlyConfig)
308
+ AutoModel.register(CLIPTextEncoderOnlyConfig, CLIPTextEncoderOnly)
309
+ CLIPTextEncoderOnlyConfig.register_for_auto_class()
310
+ CLIPTextEncoderOnly.register_for_auto_class("AutoModel")
311
+
312
+ if upload:
313
+ # Initialize the model
314
+ model_name = "openai/clip-vit-base-patch32"
315
+ pretrained=True
316
+ lora=None
317
+
318
+ cfg = CLIPTextEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
319
+ model = CLIPTextEncoderOnly(cfg)
320
+ model.push_to_hub("test-text-hf-upload")
321
+
322
+ model = CLIPTextEncoderOnly.from_pretrained("mpatel57/test-text-hf-upload", force_download=True)
323
+
324
+ def test_custom_text_model(register=False, upload=False):
325
+ # register the classes
326
+ if register:
327
+ AutoConfig.register("whole_custom_text_model", CustomTextEncoderOnlyConfig)
328
+ AutoModel.register(CustomTextEncoderOnlyConfig, CustomTextEncoderOnly)
329
+ CustomTextEncoderOnlyConfig.register_for_auto_class()
330
+ CustomTextEncoderOnly.register_for_auto_class("AutoModel")
331
+
332
+ if upload:
333
+ # Initialize the model
334
+ model_name = "google-bert/bert-base-uncased"
335
+ pretrained=True
336
+ frozen=False
337
+ output_hidden_size=512
338
+ last_hidden_state=False
339
+
340
+ lora=None
341
+
342
+ cfg = CustomTextEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, frozen=frozen, output_hidden_size=output_hidden_size, last_hidden_state=last_hidden_state, lora=lora)
343
+ model = CustomTextEncoderOnly(cfg)
344
+ model.push_to_hub("test-text-hf-upload")
345
+
346
+ model = CustomTextEncoderOnly.from_pretrained("mpatel57/test-text-hf-upload", force_download=True)
347
+
348
+ def test_vision_model(register=False, upload=False):
349
+ # register the classes
350
+ if register:
351
+ AutoConfig.register("clip_custom_vision_model", CLIPVisionEncoderOnlyConfig)
352
+ AutoModel.register(CLIPVisionEncoderOnlyConfig, CLIPVisionEncoderOnly)
353
+ CLIPVisionEncoderOnlyConfig.register_for_auto_class()
354
+ CLIPVisionEncoderOnly.register_for_auto_class("AutoModel")
355
+
356
+ if upload:
357
+ # Initialize the model
358
+ model_name = "openai/clip-vit-base-patch32"
359
+ pretrained=True
360
+ lora=None
361
+
362
+ cfg = CLIPVisionEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
363
+ model = CLIPVisionEncoderOnly(cfg)
364
+ model.push_to_hub("test-vision-hf-upload")
365
+
366
+ model = CLIPVisionEncoderOnly.from_pretrained("mpatel57/test-vision-hf-upload", force_download=True)
367
+
368
+
369
+ if __name__ == "__main__":
370
+ test_custom_text_model(register=False, upload=True)
371
+ # test_text_model(register=False, upload=True)
372
+ # test_vision_model(register=False, upload=True)
vision-encoder/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CLIPVisionEncoderOnly"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "utils.CLIPVisionEncoderOnlyConfig",
7
+ "AutoModel": "utils.CLIPVisionEncoderOnly"
8
+ },
9
+ "frozen": false,
10
+ "lora": null,
11
+ "model_name": "openai/clip-vit-base-patch32",
12
+ "model_type": "clip_custom_vision_model",
13
+ "pretrained": false,
14
+ "torch_dtype": "float32",
15
+ "transformers_version": "4.40.1"
16
+ }
vision-encoder/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d72f519a4035dcf8b5435ea939f2926256185e287a0550cc9059f51d8f917422
3
+ size 351421984
vision-encoder/utils.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig, AutoModel, PretrainedConfig, CLIPTextConfig, CLIPVisionConfig, PreTrainedModel, CLIPTextModelWithProjection, CLIPVisionModelWithProjection
2
+ from transformers.utils import ModelOutput
3
+ import torch
4
+ import open_clip
5
+ from dataclasses import dataclass
6
+ import safetensors.torch
7
+ from peft import get_peft_config, get_peft_model, LoraConfig, TaskType
8
+ import os
9
+
10
+ HF_SAFE_WEIGHTS_NAME = "open_clip_model.safetensors"
11
+ HF_SAFE_WEIGHTS_NAME_PRIOR = "prior_model.safetensors"
12
+
13
+ @dataclass
14
+ class PriorTransformerOutput(ModelOutput):
15
+ """
16
+ The output of [`PriorTransformer`].
17
+
18
+ Args:
19
+ predicted_image_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`):
20
+ The predicted CLIP image embedding conditioned on the CLIP text embedding input.
21
+ """
22
+
23
+ predicted_image_embedding: torch.FloatTensor
24
+
25
+ @dataclass
26
+ class TextEncoderOutput(ModelOutput):
27
+ """
28
+ Output class for CLIPTextEncoderOnly model to store the outputs in a Hugging Face transformer style.
29
+
30
+ Attributes:
31
+ prompt_embeds (torch.Tensor): The embeddings of the input prompts.
32
+ last_hidden_states (torch.Tensor): The last hidden states from the model.
33
+ """
34
+ text_embeds: torch.FloatTensor = None
35
+ last_hidden_state: torch.FloatTensor = None
36
+
37
+ class CLIPTextEncoderOnlyConfig(CLIPTextConfig):
38
+ model_type = "clip_custom_text_model"
39
+
40
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
41
+ self.model_name = model_name
42
+ self.pretrained = pretrained
43
+ self.frozen = frozen
44
+ self.lora = lora
45
+ super().__init__(**kwargs)
46
+
47
+ class CLIPTextEncoderOnly(PreTrainedModel):
48
+ config_class = CLIPTextEncoderOnlyConfig
49
+
50
+ def __init__(self, config):
51
+ """
52
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
53
+
54
+ :param model_name: The name or path of the pretrained model.
55
+ :param pretrained: Whether to load the pretrained weights.
56
+ """
57
+ super().__init__(config)
58
+
59
+ if config.pretrained:
60
+ self.model = CLIPTextModelWithProjection.from_pretrained(config.model_name)
61
+ else:
62
+ base_cfg = CLIPTextConfig.from_pretrained(config.model_name)
63
+ self.model = CLIPTextModelWithProjection(base_cfg)
64
+
65
+ if config.lora:
66
+ l_config = LoraConfig(
67
+ r=config.lora.lora_r,
68
+ lora_alpha=config.lora.lora_alpha,
69
+ target_modules=[
70
+ "k_proj",
71
+ "v_proj",
72
+ "q_proj",
73
+ "out_proj",
74
+ "fc1",
75
+ "fc2",
76
+ "visual_projection",
77
+ "text_projection"
78
+ ],
79
+ lora_dropout=config.lora.lora_dropout,
80
+ bias="lora_only",
81
+ )
82
+ self.model = get_peft_model(self.model, l_config)
83
+
84
+
85
+ def forward(self, input_ids, attention_mask=None, position_ids=None):
86
+ """
87
+ Forward pass of the model.
88
+
89
+ :param input_ids: Indices of input sequence tokens in the vocabulary.
90
+ :param attention_mask: Mask to avoid performing attention on padding token indices.
91
+ :param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
92
+ :return: Outputs of the model.
93
+ """
94
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_hidden_states=True)
95
+ return TextEncoderOutput(text_embeds=outputs.text_embeds, last_hidden_state=outputs.last_hidden_state)
96
+
97
+
98
+ class CustomTextEncoderOnlyConfig(PretrainedConfig):
99
+ model_type = "whole_custom_text_model"
100
+
101
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, output_hidden_size: int = 512, last_hidden_state: bool = False, lora: dict = None, **kwargs):
102
+ self.model_name = model_name
103
+ self.pretrained = pretrained
104
+ self.frozen = frozen
105
+ self.output_hidden_size = output_hidden_size
106
+ self.last_hidden_state = last_hidden_state
107
+ self.lora = lora
108
+ super().__init__(**kwargs)
109
+
110
+ class CustomTextEncoderOnly(PreTrainedModel):
111
+ config_class = CustomTextEncoderOnlyConfig
112
+
113
+ def __init__(self, config):
114
+ """
115
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
116
+
117
+ :param model_name: The name or path of the pretrained model.
118
+ :param pretrained: Whether to load the pretrained weights.
119
+ """
120
+ super().__init__(config)
121
+
122
+ self.last_hidden_state = config.last_hidden_state
123
+
124
+ if config.pretrained:
125
+ self.model = AutoModel.from_pretrained(config.model_name)
126
+ if config.frozen:
127
+ for param in self.model.parameters():
128
+ param.requires_grad = False
129
+ else:
130
+ self.model = AutoModel(config)
131
+
132
+ self.fc1 = torch.nn.Linear(self.model.config.hidden_size, config.output_hidden_size)
133
+ if config.last_hidden_state:
134
+ self.fc2 = torch.nn.Linear(self.model.config.hidden_size, config.output_hidden_size)
135
+
136
+ if config.lora:
137
+ l_config = LoraConfig(
138
+ task_type=TaskType.FEATURE_EXTRACTION,
139
+ r=config.lora.lora_r,
140
+ lora_alpha=config.lora.lora_alpha,
141
+ lora_dropout=config.lora.lora_dropout,
142
+ bias="lora_only",
143
+ )
144
+ self.model = get_peft_model(self.model, l_config)
145
+
146
+ def forward(self, input_ids, attention_mask=None, token_type_ids=None):
147
+ """
148
+ Forward pass of the model.
149
+
150
+ :param input_ids: Indices of input sequence tokens in the vocabulary.
151
+ :param attention_mask: Mask to avoid performing attention on padding token indices.
152
+ :param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
153
+ :return: Outputs of the model.
154
+ """
155
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, output_hidden_states=True)
156
+ text_embeds = self.fc1(outputs[1])
157
+ last_hidden_state = None
158
+ if self.last_hidden_state:
159
+ last_hidden_state = self.fc2(outputs[0])
160
+ else:
161
+ last_hidden_state = outputs[0]
162
+ return TextEncoderOutput(text_embeds=text_embeds, last_hidden_state=last_hidden_state)
163
+
164
+ class CLIPVisionEncoderOnlyConfig(PretrainedConfig):
165
+ model_type = "clip_custom_vision_model"
166
+
167
+ def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
168
+ self.model_name = model_name
169
+ self.pretrained = pretrained
170
+ self.frozen = frozen
171
+ self.lora = lora
172
+ super().__init__(**kwargs)
173
+
174
+ class CLIPVisionEncoderOnly(PreTrainedModel):
175
+ config_class = CLIPVisionEncoderOnlyConfig
176
+
177
+ def __init__(self, config):
178
+ """
179
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
180
+
181
+ :param model_name: The name or path of the pretrained model.
182
+ :param pretrained: Whether to load the pretrained weights.
183
+ """
184
+ super().__init__(config)
185
+
186
+ if config.pretrained:
187
+ self.model = CLIPVisionModelWithProjection.from_pretrained(config.model_name)
188
+ else:
189
+ base_cfg = CLIPVisionConfig.from_pretrained(config.model_name)
190
+ self.model = CLIPVisionModelWithProjection(base_cfg)
191
+
192
+ if config.lora:
193
+ l_config = LoraConfig(
194
+ r=config.lora.lora_r,
195
+ lora_alpha=config.lora.lora_alpha,
196
+ target_modules=[
197
+ "k_proj",
198
+ "v_proj",
199
+ "q_proj",
200
+ "out_proj",
201
+ "fc1",
202
+ "fc2",
203
+ "visual_projection",
204
+ "text_projection"
205
+ ],
206
+ lora_dropout=config.lora.lora_dropout,
207
+ bias="lora_only",
208
+ )
209
+ self.model = get_peft_model(self.model, l_config)
210
+
211
+ def forward(self, data):
212
+ """
213
+ Forward pass of the model.
214
+ """
215
+ return self.model(**data).image_embeds
216
+
217
+ def parameters(self):
218
+ return self.model.parameters()
219
+
220
+
221
+ class OpenCLIPVisionEncoderOnly(torch.nn.Module):
222
+ def __init__(self, model_name: str, pretrained: bool = True, frozen: bool = False, lora: dict = None):
223
+ """
224
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
225
+
226
+ :param model_name: The name or path of the pretrained model.
227
+ :param pretrained: Whether to load the pretrained weights.
228
+ """
229
+ super().__init__()
230
+ if pretrained:
231
+ model, _ = open_clip.create_model_from_pretrained(f"hf-hub:{model_name}")
232
+ model = model.visual
233
+ else:
234
+ raise NotImplemented
235
+ self.model = model
236
+
237
+ if lora:
238
+ l_config = LoraConfig(
239
+ r=lora.lora_r,
240
+ lora_alpha=lora.lora_alpha,
241
+ target_modules=[
242
+ "k_proj",
243
+ "v_proj",
244
+ "q_proj",
245
+ "out_proj",
246
+ "fc1",
247
+ "fc2",
248
+ "visual_projection",
249
+ "text_projection"
250
+ ],
251
+ lora_dropout=lora.lora_dropout,
252
+ bias="lora_only",
253
+ )
254
+ self.model = get_peft_model(self.model, l_config)
255
+
256
+ def forward(self, image):
257
+ """
258
+ Forward pass of the model.
259
+ """
260
+ return self.model(image)
261
+
262
+ def save_pretrained(self, save_dir):
263
+ tensors = self.model.state_dict()
264
+ safetensors.torch.save_file(tensors, save_dir / HF_SAFE_WEIGHTS_NAME)
265
+
266
+ class CustomPriorModel(torch.nn.Module):
267
+ def __init__(self, in_hidden_state, out_hidden_state):
268
+ """
269
+ Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
270
+
271
+ :param model_name: The name or path of the pretrained model.
272
+ :param pretrained: Whether to load the pretrained weights.
273
+ """
274
+ super().__init__()
275
+ mid_hidden_state = max(in_hidden_state, out_hidden_state)
276
+
277
+ self.fc1 = torch.nn.Linear(in_hidden_state*2, mid_hidden_state)
278
+ self.relu = torch.nn.ReLU()
279
+ self.fc2 = torch.nn.Linear(mid_hidden_state, out_hidden_state)
280
+
281
+ def reinitialize_model(self):
282
+ for name, param in self.named_parameters():
283
+ if param.requires_grad:
284
+ if len(param.shape) > 1:
285
+ torch.nn.init.xavier_uniform_(param)
286
+ else:
287
+ if 'weight' in name:
288
+ torch.nn.init.normal_(param)
289
+ else:
290
+ torch.nn.init.zeros_(param)
291
+
292
+ def forward(self, feats):
293
+ """
294
+ Forward pass of the model.
295
+ """
296
+ return PriorTransformerOutput(predicted_image_embedding=self.fc2(self.relu(self.fc1(feats))))
297
+
298
+ def save_pretrained(self, save_dir):
299
+ pass
300
+ # tensors = self.state_dict()
301
+ # safetensors.torch.save_file(tensors, os.path.join(save_dir, HF_SAFE_WEIGHTS_NAME_PRIOR))
302
+
303
+
304
+ def test_text_model(register=False, upload=False):
305
+ # register the classes
306
+ if register:
307
+ AutoConfig.register("clip_custom_text_model", CLIPTextEncoderOnlyConfig)
308
+ AutoModel.register(CLIPTextEncoderOnlyConfig, CLIPTextEncoderOnly)
309
+ CLIPTextEncoderOnlyConfig.register_for_auto_class()
310
+ CLIPTextEncoderOnly.register_for_auto_class("AutoModel")
311
+
312
+ if upload:
313
+ # Initialize the model
314
+ model_name = "openai/clip-vit-base-patch32"
315
+ pretrained=True
316
+ lora=None
317
+
318
+ cfg = CLIPTextEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
319
+ model = CLIPTextEncoderOnly(cfg)
320
+ model.push_to_hub("test-text-hf-upload")
321
+
322
+ model = CLIPTextEncoderOnly.from_pretrained("mpatel57/test-text-hf-upload", force_download=True)
323
+
324
+ def test_custom_text_model(register=False, upload=False):
325
+ # register the classes
326
+ if register:
327
+ AutoConfig.register("whole_custom_text_model", CustomTextEncoderOnlyConfig)
328
+ AutoModel.register(CustomTextEncoderOnlyConfig, CustomTextEncoderOnly)
329
+ CustomTextEncoderOnlyConfig.register_for_auto_class()
330
+ CustomTextEncoderOnly.register_for_auto_class("AutoModel")
331
+
332
+ if upload:
333
+ # Initialize the model
334
+ model_name = "google-bert/bert-base-uncased"
335
+ pretrained=True
336
+ frozen=False
337
+ output_hidden_size=512
338
+ last_hidden_state=False
339
+
340
+ lora=None
341
+
342
+ cfg = CustomTextEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, frozen=frozen, output_hidden_size=output_hidden_size, last_hidden_state=last_hidden_state, lora=lora)
343
+ model = CustomTextEncoderOnly(cfg)
344
+ model.push_to_hub("test-text-hf-upload")
345
+
346
+ model = CustomTextEncoderOnly.from_pretrained("mpatel57/test-text-hf-upload", force_download=True)
347
+
348
+ def test_vision_model(register=False, upload=False):
349
+ # register the classes
350
+ if register:
351
+ AutoConfig.register("clip_custom_vision_model", CLIPVisionEncoderOnlyConfig)
352
+ AutoModel.register(CLIPVisionEncoderOnlyConfig, CLIPVisionEncoderOnly)
353
+ CLIPVisionEncoderOnlyConfig.register_for_auto_class()
354
+ CLIPVisionEncoderOnly.register_for_auto_class("AutoModel")
355
+
356
+ if upload:
357
+ # Initialize the model
358
+ model_name = "openai/clip-vit-base-patch32"
359
+ pretrained=True
360
+ lora=None
361
+
362
+ cfg = CLIPVisionEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
363
+ model = CLIPVisionEncoderOnly(cfg)
364
+ model.push_to_hub("test-vision-hf-upload")
365
+
366
+ model = CLIPVisionEncoderOnly.from_pretrained("mpatel57/test-vision-hf-upload", force_download=True)
367
+
368
+
369
+ if __name__ == "__main__":
370
+ test_custom_text_model(register=False, upload=True)
371
+ # test_text_model(register=False, upload=True)
372
+ # test_vision_model(register=False, upload=True)