Spaces:
Runtime error
Runtime error
File size: 9,199 Bytes
68324dd |
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 |
import torch
import torch.nn as nn
import numpy as np
from functools import partial
from lib.model_zoo.common.get_model import register
version = '0'
symbol = 'clip'
class AbstractEncoder(nn.Module):
def __init__(self):
super().__init__()
def encode(self, *args, **kwargs):
raise NotImplementedError
from transformers import CLIPTokenizer, CLIPTextModel
def disabled_train(self, mode=True):
"""Overwrite model.train with this function to make sure train/eval mode
does not change anymore."""
return self
@register('clip_text_frozen', version)
class FrozenCLIPTextEmbedder(AbstractEncoder):
"""Uses the CLIP transformer encoder for text (from huggingface)"""
def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77): # clip-vit-base-patch32
super().__init__()
self.tokenizer = CLIPTokenizer.from_pretrained(version)
self.transformer = CLIPTextModel.from_pretrained(version)
self.device = device
self.max_length = max_length # TODO: typical value?
self.freeze()
def freeze(self):
self.transformer = self.transformer.eval()
#self.train = disabled_train
for param in self.parameters():
param.requires_grad = False
def forward(self, text):
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
tokens = batch_encoding["input_ids"].to(self.device)
outputs = self.transformer(input_ids=tokens)
z = outputs.last_hidden_state
return z
def encode(self, text):
return self(text)
from transformers import CLIPProcessor, CLIPVisionModel
@register('clip_vision_frozen', version)
class FrozenCLIPVisionEmbedder(AbstractEncoder):
def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77): # clip-vit-base-patch32
super().__init__()
self.processor = CLIPProcessor.from_pretrained(version)
self.transformer = CLIPVisionModel.from_pretrained(version)
self.device = device
self.max_length = max_length # TODO: typical value?
self.freeze()
def freeze(self):
self.transformer = self.transformer.eval()
#self.train = disabled_train
for param in self.parameters():
param.requires_grad = False
def forward(self, images):
inputs = self.processor(images=images, return_tensors="pt")
pixels = inputs['pixel_values'].to(self.device)
outputs = self.transformer(pixel_values=pixels)
z = outputs.last_hidden_state
return z
def encode(self, image):
return self(image)
from transformers import CLIPModel
@register('clip_frozen', version)
class FrozenCLIP(AbstractEncoder):
def __init__(self,
version="openai/clip-vit-large-patch14",
max_length=77,
encode_type='encode_text',): # clip-vit-base-patch32
super().__init__()
self.tokenizer = CLIPTokenizer.from_pretrained(version)
self.processor = CLIPProcessor.from_pretrained(version)
self.model = CLIPModel.from_pretrained(version)
self.max_length = max_length # TODO: typical value?
self.encode_type = encode_type
self.pinv_text_projection = None
self.freeze()
def get_device(self):
# A trick to get device
return self.model.text_projection.weight.device
def freeze(self):
self.model = self.model.eval()
#self.train = disabled_train
for param in self.parameters():
param.requires_grad = False
def encode_text_pooled(self, text):
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
tokens = batch_encoding["input_ids"].to(self.get_device())
return self.model.get_text_features(input_ids=tokens)
def encode_vision_pooled(self, images):
inputs = self.processor(images=images, return_tensors="pt")
pixels = inputs['pixel_values'].to(self.get_device())
return self.model.get_image_features(pixel_values=pixels)
def encode_text_noproj(self, text):
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
tokens = batch_encoding["input_ids"].to(self.get_device())
outputs = self.model.text_model(input_ids=tokens)
return outputs.last_hidden_state
def encode_vision_noproj(self, images):
inputs = self.processor(images=images, return_tensors="pt")
pixels = inputs['pixel_values'].to(self.get_device())
outputs = self.model.vision_model(pixel_values=pixels)
return outputs.last_hidden_state
def encode_text_bug(self, text):
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
tokens = batch_encoding["input_ids"].to(self.get_device())
outputs = self.model.text_model(input_ids=tokens)
z = outputs.last_hidden_state
z_pooled = outputs.pooler_output
z = z / torch.norm(z_pooled.unsqueeze(1), dim=-1, keepdim=True)
return self.model.text_projection(z)
def encode_text(self, text):
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
tokens = batch_encoding["input_ids"].to(self.get_device())
outputs = self.model.text_model(input_ids=tokens)
z = self.model.text_projection(outputs.last_hidden_state)
z_pooled = self.model.text_projection(outputs.pooler_output)
z = z / torch.norm(z_pooled.unsqueeze(1), dim=-1, keepdim=True)
return z
def encode_vision(self, images):
z = self.encode_vision_noproj(images)
z = self.model.vision_model.post_layernorm(z)
z = self.model.visual_projection(z)
z_pooled = z[:, 0:1]
# z_pooled_normed = z_pooled / z_pooled.norm(dim=-1, keepdim=True)
z = z / torch.norm(z_pooled, dim=-1, keepdim=True)
return z
def encode_vision_pinvtext(self, images):
blank_text_encode_norm_avg = 28.9096
z = self.encode_vision(images)
if self.pinv_text_projection is None:
self.pinv_text_projection = torch.linalg.pinv(self.model.text_projection.weight).T
z = torch.matmul(z, self.pinv_text_projection)
# z = z / torch.norm(z[:, 0:1], dim=-1, keepdim=True)
z = z / torch.norm(z, dim=-1, keepdim=True)
z = z*blank_text_encode_norm_avg
# return z[:, 1:2].repeat(1, 77, 1)
z2 = self.encode_text_noproj('')
# z2[:, 1:77] = z[:, 0:76]
return torch.flip(z, dims=(1,))[:, 0:77]
def encode(self, *args, **kwargs):
return getattr(self, self.encode_type)(*args, **kwargs)
#############################
# copyed from justin's code #
#############################
@register('clip_vision_frozen_justin', version)
class FrozenCLIPVisionEmbedder_Justin(AbstractEncoder):
"""
Uses the CLIP image encoder.
"""
def __init__(
self,
model='ViT-L/14',
jit=False,
device='cuda' if torch.cuda.is_available() else 'cpu',
antialias=False,
):
super().__init__()
from . import clip_justin
self.model, _ = clip_justin.load(name=model, device=device, jit=jit)
self.device = device
self.antialias = antialias
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
# I didn't call this originally, but seems like it was frozen anyway
self.freeze()
def freeze(self):
self.transformer = self.model.eval()
for param in self.parameters():
param.requires_grad = False
def preprocess(self, x):
import kornia
# Expects inputs in the range -1, 1
x = kornia.geometry.resize(x, (224, 224),
interpolation='bicubic',align_corners=True,
antialias=self.antialias)
x = (x + 1.) / 2.
# renormalize according to clip
x = kornia.enhance.normalize(x, self.mean, self.std)
return x
def forward(self, x):
# x is assumed to be in range [-1,1]
return self.model.encode_image(self.preprocess(x)).float()
def encode(self, im):
return self(im).unsqueeze(1)
|