Spaces:
Sleeping
Sleeping
File size: 5,943 Bytes
dffe47c |
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 |
# SOURCE: https://github.com/Sulam-Group/IBYDMT/blob/main/ibydmt/multimodal.py
from abc import abstractmethod
from typing import Mapping, Optional
import clip
import open_clip
from transformers import (
AlignModel,
AlignProcessor,
BlipForImageTextRetrieval,
BlipProcessor,
FlavaModel,
FlavaProcessor,
)
from app_lib.config import Config
from app_lib.config import Constants as c
class VisionLanguageModel:
def __init__(self, backbone: Optional[str] = None, device=c.DEVICE):
pass
@abstractmethod
def encode_text(self, text):
pass
@abstractmethod
def encode_image(self, image):
pass
models: Mapping[str, VisionLanguageModel] = {}
def register_model(name):
def register(cls: VisionLanguageModel):
if name in models:
raise ValueError(f"Model {name} is already registered")
models[name] = cls
return register
def get_model_name_and_backbone(config: Config):
backbone = config.data.backbone.split(":")
if len(backbone) == 1:
backbone.append(None)
return backbone
def get_model(config: Config, device=c.DEVICE) -> VisionLanguageModel:
model_name, backbone = get_model_name_and_backbone(config)
return models[model_name](backbone, device=device)
def get_text_encoder(config: Config, device=c.DEVICE):
model = get_model(config, device=device)
return model.encode_text
def get_image_encoder(config: Config, device=c.DEVICE):
model = get_model(config, device=device)
return model.encode_image
@register_model(name="clip")
class CLIPModel(VisionLanguageModel):
def __init__(self, backbone: str, device=c.DEVICE):
self.model, self.preprocess = clip.load(backbone, device=device)
self.tokenize = clip.tokenize
self.device = device
def encode_text(self, text):
text = self.tokenize(text).to(self.device)
return self.model.encode_text(text)
def encode_image(self, image):
image = self.preprocess(image).unsqueeze(0).to(self.device)
return self.model.encode_image(image)
@register_model(name="open_clip")
class OpenClipModel(VisionLanguageModel):
OPENCLIP_WEIGHTS = {
"ViT-B-32": "laion2b_s34b_b79k",
"ViT-L-14": "laion2b_s32b_b82k",
}
def __init__(self, backbone: str, device=c.DEVICE):
self.model, _, self.preprocess = open_clip.create_model_and_transforms(
backbone, pretrained=self.OPENCLIP_WEIGHTS[backbone], device=device
)
self.tokenize = open_clip.get_tokenizer(backbone)
self.device = device
def encode_text(self, text):
text = self.tokenize(text).to(self.device)
return self.model.encode_text(text)
def encode_image(self, image):
image = self.preprocess(image).unsqueeze(0).to(self.device)
return self.model.encode_image(image)
@register_model(name="flava")
class FLAVAModel(VisionLanguageModel):
HF_MODEL = "facebook/flava-full"
def __init__(self, backbone: Optional[str] = None, device=c.DEVICE):
if backbone is None:
backbone = self.HF_MODEL
self.model = FlavaModel.from_pretrained(backbone).to(device)
self.processor = FlavaProcessor.from_pretrained(backbone)
self.device = device
def encode_text(self, text):
text_inputs = self.processor(
text=text, return_tensors="pt", padding="max_length", max_length=77
)
text_inputs = {k: v.to(self.device) for k, v in text_inputs.items()}
return self.model.get_text_features(**text_inputs)[:, 0, :]
def encode_image(self, image):
image_inputs = self.processor(images=image, return_tensors="pt")
image_inputs = {k: v.to(self.device) for k, v in image_inputs.items()}
return self.model.get_image_features(**image_inputs)[:, 0, :]
@register_model(name="align")
class ALIGNModel(VisionLanguageModel):
HF_MODEL = "kakaobrain/align-base"
def __init__(self, backbone: Optional[str] = None, device=c.DEVICE):
if backbone is None:
backbone = self.HF_MODEL
self.model = AlignModel.from_pretrained(backbone).to(device)
self.processor = AlignProcessor.from_pretrained(backbone)
self.device = device
def encode_text(self, text):
text_inputs = self.processor(
text=text, return_tensors="pt", padding="max_length", max_length=77
)
text_inputs = {k: v.to(self.device) for k, v in text_inputs.items()}
return self.model.get_text_features(**text_inputs)
def encode_image(self, image):
image_inputs = self.processor(images=image, return_tensors="pt")
image_inputs = {k: v.to(self.device) for k, v in image_inputs.items()}
return self.model.get_image_features(**image_inputs)
@register_model(name="blip")
class BLIPModel(VisionLanguageModel):
HF_MODEL = "Salesforce/blip-itm-base-coco"
def __init__(self, backbone: Optional[str] = None, device=c.DEVICE):
if backbone is None:
backbone = self.HF_MODEL
self.model = BlipForImageTextRetrieval.from_pretrained(backbone).to(device)
self.processor = BlipProcessor.from_pretrained(backbone)
self.device = device
def encode_text(self, text):
text_inputs = self.processor(
text=text, return_tensors="pt", padding="max_length", max_length=77
)
text_inputs = {k: v.to(self.device) for k, v in text_inputs.items()}
question_embeds = self.model.text_encoder(**text_inputs)[0]
return self.model.text_proj(question_embeds[:, 0, :])
def encode_image(self, image):
image_inputs = self.processor(images=image, return_tensors="pt")
image_inputs = {k: v.to(self.device) for k, v in image_inputs.items()}
image_embeds = self.model.vision_model(**image_inputs)[0]
return self.model.vision_proj(image_embeds[:, 0, :])
|