File size: 12,734 Bytes
56ef57e |
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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
from transformers import AutoConfig, AutoModel, PretrainedConfig, CLIPTextConfig, CLIPVisionConfig, PreTrainedModel, CLIPTextModelWithProjection, CLIPVisionModelWithProjection
from transformers.utils import ModelOutput
import torch
import open_clip
from dataclasses import dataclass
import safetensors.torch
from peft import get_peft_config, get_peft_model, LoraConfig, TaskType
import os
HF_SAFE_WEIGHTS_NAME = "open_clip_model.safetensors"
HF_SAFE_WEIGHTS_NAME_PRIOR = "prior_model.safetensors"
@dataclass
class PriorTransformerOutput(ModelOutput):
"""
The output of [`PriorTransformer`].
Args:
predicted_image_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`):
The predicted CLIP image embedding conditioned on the CLIP text embedding input.
"""
predicted_image_embedding: torch.FloatTensor
@dataclass
class TextEncoderOutput(ModelOutput):
"""
Output class for CLIPTextEncoderOnly model to store the outputs in a Hugging Face transformer style.
Attributes:
prompt_embeds (torch.Tensor): The embeddings of the input prompts.
last_hidden_states (torch.Tensor): The last hidden states from the model.
"""
text_embeds: torch.FloatTensor = None
last_hidden_state: torch.FloatTensor = None
class CLIPTextEncoderOnlyConfig(CLIPTextConfig):
model_type = "clip_custom_text_model"
def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
self.model_name = model_name
self.pretrained = pretrained
self.frozen = frozen
self.lora = lora
super().__init__(**kwargs)
class CLIPTextEncoderOnly(PreTrainedModel):
config_class = CLIPTextEncoderOnlyConfig
def __init__(self, config):
"""
Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
:param model_name: The name or path of the pretrained model.
:param pretrained: Whether to load the pretrained weights.
"""
super().__init__(config)
if config.pretrained:
self.model = CLIPTextModelWithProjection.from_pretrained(config.model_name)
else:
base_cfg = CLIPTextConfig.from_pretrained(config.model_name)
self.model = CLIPTextModelWithProjection(base_cfg)
if config.lora:
l_config = LoraConfig(
r=config.lora.lora_r,
lora_alpha=config.lora.lora_alpha,
target_modules=[
"k_proj",
"v_proj",
"q_proj",
"out_proj",
"fc1",
"fc2",
"visual_projection",
"text_projection"
],
lora_dropout=config.lora.lora_dropout,
bias="lora_only",
)
self.model = get_peft_model(self.model, l_config)
def forward(self, input_ids, attention_mask=None, position_ids=None):
"""
Forward pass of the model.
:param input_ids: Indices of input sequence tokens in the vocabulary.
:param attention_mask: Mask to avoid performing attention on padding token indices.
:param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
:return: Outputs of the model.
"""
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_hidden_states=True)
return TextEncoderOutput(text_embeds=outputs.text_embeds, last_hidden_state=outputs.last_hidden_state)
class CustomTextEncoderOnly(PreTrainedModel):
def __init__(self, model_name: str, output_hidden_size: int, pretrained: bool = True, frozen: bool = True, last_hidden_state: bool = False, lora: dict = None):
"""
Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
:param model_name: The name or path of the pretrained model.
:param pretrained: Whether to load the pretrained weights.
"""
config = AutoModel.from_pretrained(model_name).config
super().__init__(config)
self.last_hidden_state = last_hidden_state
if pretrained:
self.model = AutoModel.from_pretrained(model_name)
if frozen:
for param in self.model.parameters():
param.requires_grad = False
else:
self.model = AutoModel(config)
self.fc1 = torch.nn.Linear(self.model.config.hidden_size, output_hidden_size)
if last_hidden_state:
self.fc2 = torch.nn.Linear(self.model.config.hidden_size, output_hidden_size)
if lora:
l_config = LoraConfig(
task_type=TaskType.FEATURE_EXTRACTION,
r=lora.lora_r,
lora_alpha=lora.lora_alpha,
lora_dropout=lora.lora_dropout,
bias="lora_only",
)
self.model = get_peft_model(self.model, l_config)
def forward(self, input_ids, attention_mask=None, token_type_ids=None):
"""
Forward pass of the model.
:param input_ids: Indices of input sequence tokens in the vocabulary.
:param attention_mask: Mask to avoid performing attention on padding token indices.
:param token_type_ids: Segment token indices to indicate first and second portions of the inputs.
:return: Outputs of the model.
"""
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, output_hidden_states=True)
text_embeds = self.fc1(outputs[1])
last_hidden_state = None
if self.last_hidden_state:
last_hidden_state = self.fc2(outputs[0])
else:
last_hidden_state = outputs[0]
return TextEncoderOutput(text_embeds=text_embeds, last_hidden_state=last_hidden_state)
class CLIPVisionEncoderOnlyConfig(PretrainedConfig):
model_type = "clip_custom_vision_model"
def __init__(self, model_name: str = None, pretrained: bool = True, frozen: bool = False, lora: dict = None, **kwargs):
self.model_name = model_name
self.pretrained = pretrained
self.frozen = frozen
self.lora = lora
super().__init__(**kwargs)
class CLIPVisionEncoderOnly(PreTrainedModel):
config_class = CLIPVisionEncoderOnlyConfig
def __init__(self, config):
"""
Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
:param model_name: The name or path of the pretrained model.
:param pretrained: Whether to load the pretrained weights.
"""
super().__init__(config)
if config.pretrained:
self.model = CLIPVisionModelWithProjection.from_pretrained(config.model_name)
else:
base_cfg = CLIPVisionConfig.from_pretrained(config.model_name)
self.model = CLIPVisionModelWithProjection(base_cfg)
if config.lora:
l_config = LoraConfig(
r=config.lora.lora_r,
lora_alpha=config.lora.lora_alpha,
target_modules=[
"k_proj",
"v_proj",
"q_proj",
"out_proj",
"fc1",
"fc2",
"visual_projection",
"text_projection"
],
lora_dropout=config.lora.lora_dropout,
bias="lora_only",
)
self.model = get_peft_model(self.model, l_config)
def forward(self, data):
"""
Forward pass of the model.
"""
return self.model(**data).image_embeds
def parameters(self):
return self.model.parameters()
class OpenCLIPVisionEncoderOnly(torch.nn.Module):
def __init__(self, model_name: str, pretrained: bool = True, frozen: bool = False, lora: dict = None):
"""
Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
:param model_name: The name or path of the pretrained model.
:param pretrained: Whether to load the pretrained weights.
"""
super().__init__()
if pretrained:
model, _ = open_clip.create_model_from_pretrained(f"hf-hub:{model_name}")
model = model.visual
else:
raise NotImplemented
self.model = model
if lora:
l_config = LoraConfig(
r=lora.lora_r,
lora_alpha=lora.lora_alpha,
target_modules=[
"k_proj",
"v_proj",
"q_proj",
"out_proj",
"fc1",
"fc2",
"visual_projection",
"text_projection"
],
lora_dropout=lora.lora_dropout,
bias="lora_only",
)
self.model = get_peft_model(self.model, l_config)
def forward(self, image):
"""
Forward pass of the model.
"""
return self.model(image)
def save_pretrained(self, save_dir):
tensors = self.model.state_dict()
safetensors.torch.save_file(tensors, save_dir / HF_SAFE_WEIGHTS_NAME)
class CustomPriorModel(torch.nn.Module):
def __init__(self, in_hidden_state, out_hidden_state):
"""
Initializes the Hugging Face text encoder for CLIP model, inheriting from PreTrainedModel.
:param model_name: The name or path of the pretrained model.
:param pretrained: Whether to load the pretrained weights.
"""
super().__init__()
mid_hidden_state = max(in_hidden_state, out_hidden_state)
self.fc1 = torch.nn.Linear(in_hidden_state*2, mid_hidden_state)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(mid_hidden_state, out_hidden_state)
def reinitialize_model(self):
for name, param in self.named_parameters():
if param.requires_grad:
if len(param.shape) > 1:
torch.nn.init.xavier_uniform_(param)
else:
if 'weight' in name:
torch.nn.init.normal_(param)
else:
torch.nn.init.zeros_(param)
def forward(self, feats):
"""
Forward pass of the model.
"""
return PriorTransformerOutput(predicted_image_embedding=self.fc2(self.relu(self.fc1(feats))))
def save_pretrained(self, save_dir):
pass
# tensors = self.state_dict()
# safetensors.torch.save_file(tensors, os.path.join(save_dir, HF_SAFE_WEIGHTS_NAME_PRIOR))
def test_text_model(register=False, upload=False):
# register the classes
if register:
AutoConfig.register("clip_custom_text_model", CLIPTextEncoderOnlyConfig)
AutoModel.register(CLIPTextEncoderOnlyConfig, CLIPTextEncoderOnly)
CLIPTextEncoderOnlyConfig.register_for_auto_class()
CLIPTextEncoderOnly.register_for_auto_class("AutoModel")
if upload:
# Initialize the model
model_name = "openai/clip-vit-base-patch32"
pretrained=True
lora=None
cfg = CLIPTextEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
model = CLIPTextEncoderOnly(cfg)
model.push_to_hub("test-text-hf-upload")
model = CLIPTextEncoderOnly.from_pretrained("mpatel57/test-text-hf-upload", force_download=True)
def test_vision_model(register=False, upload=False):
# register the classes
if register:
AutoConfig.register("clip_custom_vision_model", CLIPVisionEncoderOnlyConfig)
AutoModel.register(CLIPVisionEncoderOnlyConfig, CLIPVisionEncoderOnly)
CLIPVisionEncoderOnlyConfig.register_for_auto_class()
CLIPVisionEncoderOnly.register_for_auto_class("AutoModel")
if upload:
# Initialize the model
model_name = "openai/clip-vit-base-patch32"
pretrained=True
lora=None
cfg = CLIPVisionEncoderOnlyConfig(model_name=model_name, pretrained=pretrained, lora=lora)
model = CLIPVisionEncoderOnly(cfg)
model.push_to_hub("test-vision-hf-upload")
model = CLIPVisionEncoderOnly.from_pretrained("mpatel57/test-vision-hf-upload", force_download=True)
if __name__ == "__main__":
test_text_model(register=False, upload=True)
test_vision_model(register=False, upload=True)
|