mpatel57 commited on
Commit
27c8593
1 Parent(s): 023efba

Upload CustomTextEncoderOnly

Browse files
Files changed (4) hide show
  1. README.md +199 -0
  2. config.json +33 -0
  3. model.safetensors +3 -0
  4. utils.py +372 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "CustomTextEncoderOnly"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "utils.CustomTextEncoderOnlyConfig",
8
+ "AutoModel": "utils.CustomTextEncoderOnly"
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
+ "last_hidden_state": false,
19
+ "layer_norm_eps": 1e-05,
20
+ "lora": null,
21
+ "max_position_embeddings": 77,
22
+ "model_name": "google-bert/bert-base-uncased",
23
+ "model_type": "whole_custom_text_model",
24
+ "num_attention_heads": 8,
25
+ "num_hidden_layers": 12,
26
+ "output_hidden_size": 512,
27
+ "pad_token_id": 1,
28
+ "pretrained": true,
29
+ "projection_dim": 512,
30
+ "torch_dtype": "float32",
31
+ "transformers_version": "4.40.1",
32
+ "vocab_size": 49408
33
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a97d8f4ce8ca5eea64b098b26c6c99109fec12480c2da419999ea91a5377a1a8
3
+ size 439527592
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(CLIPTextConfig):
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)