Spaces:
Running
on
Zero
Running
on
Zero
File size: 5,512 Bytes
9890667 323d67d 9890667 323d67d 9890667 323d67d |
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 |
import torch
import torch.nn as nn
import clip
import copy
from torch.autograd import Function
from collections import OrderedDict
from torchvision import transforms
def convert_state_dict(state_dict):
new_state_dict = OrderedDict()
for k, v in state_dict.items():
if k.startswith("module."):
k = k.replace("module.", "")
new_state_dict[k] = v
return new_state_dict
def convert_weights_float(model: nn.Module):
"""Convert applicable model parameters to fp32"""
def _convert_weights_to_fp32(l):
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
l.weight.data = l.weight.data.float()
if l.bias is not None:
l.bias.data = l.bias.data.float()
if isinstance(l, nn.MultiheadAttention):
for attr in [
*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]],
"in_proj_bias",
"bias_k",
"bias_v",
]:
tensor = getattr(l, attr)
if tensor is not None:
tensor.data = tensor.data.float()
for name in ["text_projection", "proj"]:
if hasattr(l, name):
attr = getattr(l, name)
if attr is not None:
attr.data = attr.data.float()
model.apply(_convert_weights_to_fp32)
class ReverseLayerF(Function):
@staticmethod
def forward(ctx, x, alpha):
ctx.alpha = alpha
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output):
output = grad_output.neg() * ctx.alpha
return output, None
## taken from https://github.com/moein-shariatnia/OpenAI-CLIP/blob/master/modules.py
class ProjectionHead(nn.Module):
def __init__(self, embedding_dim, projection_dim, dropout=0):
super().__init__()
self.projection = nn.Linear(embedding_dim, projection_dim)
self.gelu = nn.GELU()
self.fc = nn.Linear(projection_dim, projection_dim)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(projection_dim)
def forward(self, x):
projected = self.projection(x)
x = self.gelu(projected)
x = self.fc(x)
x = self.dropout(x)
x = x + projected
x = self.layer_norm(x)
return x
def init_weights(m): # TODO: do we need init for layernorm?
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.normal_(m.bias, std=1e-6)
class CSD_CLIP(nn.Module):
"""backbone + projection head"""
def __init__(self, name="vit_large", content_proj_head="default", model_path=None):
super(CSD_CLIP, self).__init__()
self.content_proj_head = content_proj_head
if name == "vit_large":
if model_path is None:
clipmodel, _ = clip.load("ViT-L/14")
else:
clipmodel, _ = clip.load(model_path)
self.backbone = clipmodel.visual
self.embedding_dim = 1024
elif name == "vit_base":
if model_path is None:
clipmodel, _ = clip.load("ViT-B/16")
else:
clipmodel, _ = clip.load(model_path)
self.backbone = clipmodel.visual
self.embedding_dim = 768
self.feat_dim = 512
else:
raise Exception("This model is not implemented")
convert_weights_float(self.backbone)
self.last_layer_style = copy.deepcopy(self.backbone.proj)
if content_proj_head == "custom":
self.last_layer_content = ProjectionHead(self.embedding_dim, self.feat_dim)
self.last_layer_content.apply(init_weights)
else:
self.last_layer_content = copy.deepcopy(self.backbone.proj)
self.backbone.proj = None
@property
def dtype(self):
return self.backbone.conv1.weight.dtype
def forward(self, input_data, alpha=None):
feature = self.backbone(input_data)
if alpha is not None:
reverse_feature = ReverseLayerF.apply(feature, alpha)
else:
reverse_feature = feature
style_output = feature @ self.last_layer_style
style_output = nn.functional.normalize(style_output, dim=1, p=2)
# if alpha is not None:
if self.content_proj_head == "custom":
content_output = self.last_layer_content(reverse_feature)
else:
content_output = reverse_feature @ self.last_layer_content
content_output = nn.functional.normalize(content_output, dim=1, p=2)
return feature, content_output, style_output
def create_model_and_transforms(model_path="models/csd_clip.pth"):
# init model
model = CSD_CLIP("vit_large", "default")
# load model
checkpoint = torch.load(model_path, map_location="cpu")
state_dict = convert_state_dict(checkpoint["model_state_dict"])
model.load_state_dict(state_dict, strict=False)
# normalization
normalize = transforms.Normalize(
(0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)
)
preprocess = transforms.Compose(
[
transforms.Resize(
size=224, interpolation=transforms.functional.InterpolationMode.BICUBIC
),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
]
)
return model, preprocess, preprocess
|