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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MIT License
|
| 3 |
+
|
| 4 |
+
Copyright (c) 2021 OpenAI
|
| 5 |
+
|
| 6 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 7 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 8 |
+
in the Software without restriction, including without limitation the rights
|
| 9 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 10 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 11 |
+
furnished to do so, subject to the following conditions:
|
| 12 |
+
|
| 13 |
+
The above copyright notice and this permission notice shall be included in all
|
| 14 |
+
copies or substantial portions of the Software.
|
| 15 |
+
|
| 16 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 17 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 18 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 19 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 20 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 21 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
SOFTWARE.
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
from collections import OrderedDict
|
| 26 |
+
from typing import Tuple, Union
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn.functional as F
|
| 31 |
+
from torch import nn
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Bottleneck(nn.Module):
|
| 35 |
+
expansion = 4
|
| 36 |
+
|
| 37 |
+
def __init__(self, inplanes, planes, stride=1):
|
| 38 |
+
super().__init__()
|
| 39 |
+
|
| 40 |
+
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
|
| 41 |
+
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
|
| 42 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
| 43 |
+
|
| 44 |
+
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
|
| 45 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
| 46 |
+
|
| 47 |
+
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
|
| 48 |
+
|
| 49 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
|
| 50 |
+
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
|
| 51 |
+
|
| 52 |
+
self.relu = nn.ReLU(inplace=True)
|
| 53 |
+
self.downsample = None
|
| 54 |
+
self.stride = stride
|
| 55 |
+
|
| 56 |
+
if stride > 1 or inplanes != planes * Bottleneck.expansion:
|
| 57 |
+
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
|
| 58 |
+
self.downsample = nn.Sequential(OrderedDict([
|
| 59 |
+
("-1", nn.AvgPool2d(stride)),
|
| 60 |
+
("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
|
| 61 |
+
("1", nn.BatchNorm2d(planes * self.expansion))
|
| 62 |
+
]))
|
| 63 |
+
|
| 64 |
+
def forward(self, x: torch.Tensor):
|
| 65 |
+
identity = x
|
| 66 |
+
|
| 67 |
+
out = self.relu(self.bn1(self.conv1(x)))
|
| 68 |
+
out = self.relu(self.bn2(self.conv2(out)))
|
| 69 |
+
out = self.avgpool(out)
|
| 70 |
+
out = self.bn3(self.conv3(out))
|
| 71 |
+
|
| 72 |
+
if self.downsample is not None:
|
| 73 |
+
identity = self.downsample(x)
|
| 74 |
+
|
| 75 |
+
out += identity
|
| 76 |
+
out = self.relu(out)
|
| 77 |
+
return out
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class AttentionPool2d(nn.Module):
|
| 81 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
|
| 84 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
| 85 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
| 86 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
| 87 |
+
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
|
| 88 |
+
self.num_heads = num_heads
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
|
| 92 |
+
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
|
| 93 |
+
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
|
| 94 |
+
x, _ = F.multi_head_attention_forward(
|
| 95 |
+
query=x, key=x, value=x,
|
| 96 |
+
embed_dim_to_check=x.shape[-1],
|
| 97 |
+
num_heads=self.num_heads,
|
| 98 |
+
q_proj_weight=self.q_proj.weight,
|
| 99 |
+
k_proj_weight=self.k_proj.weight,
|
| 100 |
+
v_proj_weight=self.v_proj.weight,
|
| 101 |
+
in_proj_weight=None,
|
| 102 |
+
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
|
| 103 |
+
bias_k=None,
|
| 104 |
+
bias_v=None,
|
| 105 |
+
add_zero_attn=False,
|
| 106 |
+
dropout_p=0,
|
| 107 |
+
out_proj_weight=self.c_proj.weight,
|
| 108 |
+
out_proj_bias=self.c_proj.bias,
|
| 109 |
+
use_separate_proj_weight=True,
|
| 110 |
+
training=self.training,
|
| 111 |
+
need_weights=False
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
return x[0]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class ModifiedResNet(nn.Module):
|
| 118 |
+
"""
|
| 119 |
+
A ResNet class that is similar to torchvision's but contains the following changes:
|
| 120 |
+
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
|
| 121 |
+
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
|
| 122 |
+
- The final pooling layer is a QKV attention instead of an average pool
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.output_dim = output_dim
|
| 128 |
+
self.input_resolution = input_resolution
|
| 129 |
+
|
| 130 |
+
# the 3-layer stem
|
| 131 |
+
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
|
| 132 |
+
self.bn1 = nn.BatchNorm2d(width // 2)
|
| 133 |
+
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
|
| 134 |
+
self.bn2 = nn.BatchNorm2d(width // 2)
|
| 135 |
+
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
|
| 136 |
+
self.bn3 = nn.BatchNorm2d(width)
|
| 137 |
+
self.avgpool = nn.AvgPool2d(2)
|
| 138 |
+
self.relu = nn.ReLU(inplace=True)
|
| 139 |
+
|
| 140 |
+
# residual layers
|
| 141 |
+
self._inplanes = width # this is a *mutable* variable used during construction
|
| 142 |
+
self.layer1 = self._make_layer(width, layers[0])
|
| 143 |
+
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
|
| 144 |
+
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
|
| 145 |
+
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
|
| 146 |
+
|
| 147 |
+
embed_dim = width * 32 # the ResNet feature dimension
|
| 148 |
+
self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
|
| 149 |
+
|
| 150 |
+
def _make_layer(self, planes, blocks, stride=1):
|
| 151 |
+
layers = [Bottleneck(self._inplanes, planes, stride)]
|
| 152 |
+
|
| 153 |
+
self._inplanes = planes * Bottleneck.expansion
|
| 154 |
+
for _ in range(1, blocks):
|
| 155 |
+
layers.append(Bottleneck(self._inplanes, planes))
|
| 156 |
+
|
| 157 |
+
return nn.Sequential(*layers)
|
| 158 |
+
|
| 159 |
+
def forward(self, x):
|
| 160 |
+
def stem(x):
|
| 161 |
+
for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]:
|
| 162 |
+
x = self.relu(bn(conv(x)))
|
| 163 |
+
x = self.avgpool(x)
|
| 164 |
+
return x
|
| 165 |
+
|
| 166 |
+
x = x.type(self.conv1.weight.dtype)
|
| 167 |
+
x = stem(x)
|
| 168 |
+
x = self.layer1(x)
|
| 169 |
+
x = self.layer2(x)
|
| 170 |
+
x = self.layer3(x)
|
| 171 |
+
x = self.layer4(x)
|
| 172 |
+
x = self.attnpool(x)
|
| 173 |
+
|
| 174 |
+
return x
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class LayerNorm(nn.LayerNorm):
|
| 178 |
+
"""Subclass torch's LayerNorm to handle fp16."""
|
| 179 |
+
|
| 180 |
+
def forward(self, x: torch.Tensor):
|
| 181 |
+
orig_type = x.dtype
|
| 182 |
+
ret = super().forward(x.type(torch.float32))
|
| 183 |
+
return ret.type(orig_type)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class QuickGELU(nn.Module):
|
| 187 |
+
def forward(self, x: torch.Tensor):
|
| 188 |
+
return x * torch.sigmoid(1.702 * x)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class ResidualAttentionBlock(nn.Module):
|
| 192 |
+
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
|
| 193 |
+
super().__init__()
|
| 194 |
+
|
| 195 |
+
self.attn = nn.MultiheadAttention(d_model, n_head)
|
| 196 |
+
self.ln_1 = LayerNorm(d_model)
|
| 197 |
+
self.mlp = nn.Sequential(OrderedDict([
|
| 198 |
+
("c_fc", nn.Linear(d_model, d_model * 4)),
|
| 199 |
+
("gelu", QuickGELU()),
|
| 200 |
+
("c_proj", nn.Linear(d_model * 4, d_model))
|
| 201 |
+
]))
|
| 202 |
+
self.ln_2 = LayerNorm(d_model)
|
| 203 |
+
self.attn_mask = attn_mask
|
| 204 |
+
|
| 205 |
+
def attention(self, x: torch.Tensor):
|
| 206 |
+
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
|
| 207 |
+
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
|
| 208 |
+
|
| 209 |
+
def forward(self, x: torch.Tensor):
|
| 210 |
+
x = x + self.attention(self.ln_1(x))
|
| 211 |
+
x = x + self.mlp(self.ln_2(x))
|
| 212 |
+
return x
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class Transformer(nn.Module):
|
| 216 |
+
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.width = width
|
| 219 |
+
self.layers = layers
|
| 220 |
+
self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
|
| 221 |
+
|
| 222 |
+
def forward(self, x: torch.Tensor):
|
| 223 |
+
return self.resblocks(x)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class VisualTransformer(nn.Module):
|
| 227 |
+
def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.input_resolution = input_resolution
|
| 230 |
+
self.output_dim = output_dim
|
| 231 |
+
self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
|
| 232 |
+
|
| 233 |
+
scale = width ** -0.5
|
| 234 |
+
self.class_embedding = nn.Parameter(scale * torch.randn(width))
|
| 235 |
+
self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
|
| 236 |
+
self.ln_pre = LayerNorm(width)
|
| 237 |
+
|
| 238 |
+
self.transformer = Transformer(width, layers, heads)
|
| 239 |
+
|
| 240 |
+
self.ln_post = LayerNorm(width)
|
| 241 |
+
self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
|
| 242 |
+
|
| 243 |
+
def forward(self, x: torch.Tensor):
|
| 244 |
+
x = self.conv1(x) # shape = [*, width, grid, grid]
|
| 245 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
| 246 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
| 247 |
+
x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
|
| 248 |
+
x = x + self.positional_embedding.to(x.dtype)
|
| 249 |
+
x = self.ln_pre(x)
|
| 250 |
+
|
| 251 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
| 252 |
+
x = self.transformer(x)
|
| 253 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
| 254 |
+
|
| 255 |
+
x = self.ln_post(x[:, 0, :])
|
| 256 |
+
|
| 257 |
+
if self.proj is not None:
|
| 258 |
+
x = x @ self.proj
|
| 259 |
+
|
| 260 |
+
return x
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class CLIP(nn.Module):
|
| 264 |
+
def __init__(self,
|
| 265 |
+
embed_dim: int,
|
| 266 |
+
# vision
|
| 267 |
+
image_resolution: int,
|
| 268 |
+
vision_layers: Union[Tuple[int, int, int, int], int],
|
| 269 |
+
vision_width: int,
|
| 270 |
+
vision_patch_size: int,
|
| 271 |
+
# text
|
| 272 |
+
context_length: int,
|
| 273 |
+
vocab_size: int,
|
| 274 |
+
transformer_width: int,
|
| 275 |
+
transformer_heads: int,
|
| 276 |
+
transformer_layers: int
|
| 277 |
+
):
|
| 278 |
+
super().__init__()
|
| 279 |
+
|
| 280 |
+
self.context_length = context_length
|
| 281 |
+
|
| 282 |
+
if isinstance(vision_layers, (tuple, list)):
|
| 283 |
+
vision_heads = vision_width * 32 // 64
|
| 284 |
+
self.visual = ModifiedResNet(
|
| 285 |
+
layers=vision_layers,
|
| 286 |
+
output_dim=embed_dim,
|
| 287 |
+
heads=vision_heads,
|
| 288 |
+
input_resolution=image_resolution,
|
| 289 |
+
width=vision_width
|
| 290 |
+
)
|
| 291 |
+
else:
|
| 292 |
+
vision_heads = vision_width // 64
|
| 293 |
+
self.visual = VisualTransformer(
|
| 294 |
+
input_resolution=image_resolution,
|
| 295 |
+
patch_size=vision_patch_size,
|
| 296 |
+
width=vision_width,
|
| 297 |
+
layers=vision_layers,
|
| 298 |
+
heads=vision_heads,
|
| 299 |
+
output_dim=embed_dim
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
self.transformer = Transformer(
|
| 303 |
+
width=transformer_width,
|
| 304 |
+
layers=transformer_layers,
|
| 305 |
+
heads=transformer_heads,
|
| 306 |
+
attn_mask=self.build_attention_mask()
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
self.vocab_size = vocab_size
|
| 310 |
+
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
|
| 311 |
+
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
|
| 312 |
+
self.ln_final = LayerNorm(transformer_width)
|
| 313 |
+
|
| 314 |
+
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
|
| 315 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
|
| 316 |
+
|
| 317 |
+
self.initialize_parameters()
|
| 318 |
+
|
| 319 |
+
def initialize_parameters(self):
|
| 320 |
+
nn.init.normal_(self.token_embedding.weight, std=0.02)
|
| 321 |
+
nn.init.normal_(self.positional_embedding, std=0.01)
|
| 322 |
+
|
| 323 |
+
if isinstance(self.visual, ModifiedResNet):
|
| 324 |
+
if self.visual.attnpool is not None:
|
| 325 |
+
std = self.visual.attnpool.c_proj.in_features ** -0.5
|
| 326 |
+
nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
|
| 327 |
+
nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
|
| 328 |
+
nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
|
| 329 |
+
nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
|
| 330 |
+
|
| 331 |
+
for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
|
| 332 |
+
for name, param in resnet_block.named_parameters():
|
| 333 |
+
if name.endswith("bn3.weight"):
|
| 334 |
+
nn.init.zeros_(param)
|
| 335 |
+
|
| 336 |
+
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
|
| 337 |
+
attn_std = self.transformer.width ** -0.5
|
| 338 |
+
fc_std = (2 * self.transformer.width) ** -0.5
|
| 339 |
+
for block in self.transformer.resblocks:
|
| 340 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
| 341 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
| 342 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
| 343 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
| 344 |
+
|
| 345 |
+
if self.text_projection is not None:
|
| 346 |
+
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
|
| 347 |
+
|
| 348 |
+
def build_attention_mask(self):
|
| 349 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
| 350 |
+
# pytorch uses additive attention mask; fill with -inf
|
| 351 |
+
mask = torch.empty(self.context_length, self.context_length)
|
| 352 |
+
mask.fill_(float("-inf"))
|
| 353 |
+
mask.triu_(1) # zero out the lower diagonal
|
| 354 |
+
return mask
|
| 355 |
+
|
| 356 |
+
@property
|
| 357 |
+
def dtype(self):
|
| 358 |
+
return self.visual.conv1.weight.dtype
|
| 359 |
+
|
| 360 |
+
def encode_image(self, image):
|
| 361 |
+
return self.visual(image.type(self.dtype))
|
| 362 |
+
|
| 363 |
+
def encode_text(self, text):
|
| 364 |
+
x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
|
| 365 |
+
|
| 366 |
+
x = x + self.positional_embedding.type(self.dtype)
|
| 367 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
| 368 |
+
x = self.transformer(x)
|
| 369 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
| 370 |
+
x = self.ln_final(x).type(self.dtype)
|
| 371 |
+
|
| 372 |
+
# x.shape = [batch_size, n_ctx, transformer.width]
|
| 373 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
| 374 |
+
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
|
| 375 |
+
|
| 376 |
+
return x
|
| 377 |
+
|
| 378 |
+
def forward(self, image, text):
|
| 379 |
+
image_features = self.encode_image(image)
|
| 380 |
+
text_features = self.encode_text(text)
|
| 381 |
+
|
| 382 |
+
# normalized features
|
| 383 |
+
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
| 384 |
+
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
|
| 385 |
+
|
| 386 |
+
# cosine similarity as logits
|
| 387 |
+
logit_scale = self.logit_scale.exp()
|
| 388 |
+
logits_per_image = logit_scale * image_features @ text_features.t()
|
| 389 |
+
logits_per_text = logit_scale * text_features @ image_features.t()
|
| 390 |
+
|
| 391 |
+
# shape = [global_batch_size, global_batch_size]
|
| 392 |
+
return logits_per_image, logits_per_text
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def convert_weights(model: nn.Module):
|
| 396 |
+
"""Convert applicable model parameters to fp16"""
|
| 397 |
+
|
| 398 |
+
def _convert_weights_to_fp16(l):
|
| 399 |
+
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
|
| 400 |
+
l.weight.data = l.weight.data.half()
|
| 401 |
+
if l.bias is not None:
|
| 402 |
+
l.bias.data = l.bias.data.half()
|
| 403 |
+
|
| 404 |
+
if isinstance(l, nn.MultiheadAttention):
|
| 405 |
+
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
|
| 406 |
+
tensor = getattr(l, attr)
|
| 407 |
+
if tensor is not None:
|
| 408 |
+
tensor.data = tensor.data.half()
|
| 409 |
+
|
| 410 |
+
for name in ["text_projection", "proj"]:
|
| 411 |
+
if hasattr(l, name):
|
| 412 |
+
attr = getattr(l, name)
|
| 413 |
+
if attr is not None:
|
| 414 |
+
attr.data = attr.data.half()
|
| 415 |
+
|
| 416 |
+
model.apply(_convert_weights_to_fp16)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def build_model(state_dict: dict):
|
| 420 |
+
vit = "visual.proj" in state_dict
|
| 421 |
+
|
| 422 |
+
if vit:
|
| 423 |
+
vision_width = state_dict["visual.conv1.weight"].shape[0]
|
| 424 |
+
vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
| 425 |
+
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
|
| 426 |
+
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
| 427 |
+
image_resolution = vision_patch_size * grid_size
|
| 428 |
+
else:
|
| 429 |
+
counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
|
| 430 |
+
vision_layers = tuple(counts)
|
| 431 |
+
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
|
| 432 |
+
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
|
| 433 |
+
vision_patch_size = None
|
| 434 |
+
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
|
| 435 |
+
image_resolution = output_width * 32
|
| 436 |
+
|
| 437 |
+
embed_dim = state_dict["text_projection"].shape[1]
|
| 438 |
+
context_length = state_dict["positional_embedding"].shape[0]
|
| 439 |
+
vocab_size = state_dict["token_embedding.weight"].shape[0]
|
| 440 |
+
transformer_width = state_dict["ln_final.weight"].shape[0]
|
| 441 |
+
transformer_heads = transformer_width // 64
|
| 442 |
+
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
|
| 443 |
+
|
| 444 |
+
model = CLIP(
|
| 445 |
+
embed_dim,
|
| 446 |
+
image_resolution, vision_layers, vision_width, vision_patch_size,
|
| 447 |
+
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
for key in ["input_resolution", "context_length", "vocab_size"]:
|
| 451 |
+
if key in state_dict:
|
| 452 |
+
del state_dict[key]
|
| 453 |
+
|
| 454 |
+
convert_weights(model)
|
| 455 |
+
model.load_state_dict(state_dict)
|
| 456 |
+
return model.eval()
|