Master-Shi commited on
Commit
a826e66
·
verified ·
1 Parent(s): 6c8b670

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/__init__.py +9 -0
  2. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/constants.py +2 -0
  3. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/eva_vit_model.py +571 -0
  4. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/factory.py +528 -0
  5. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_configs.py +57 -0
  6. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_model.py +240 -0
  7. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/loss.py +123 -0
  8. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model.py +429 -0
  9. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json +19 -0
  10. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-B-16.json +29 -0
  11. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json +25 -0
  12. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json +25 -0
  13. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/modified_resnet.py +179 -0
  14. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/openai.py +144 -0
  15. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/rope.py +131 -0
  16. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/timm_model.py +114 -0
  17. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/tokenizer.py +205 -0
  18. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transform.py +104 -0
  19. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transformer.py +683 -0
  20. 之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/utils.py +321 -0
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
2
+ from .factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer
3
+ from .factory import list_models, add_model_config, get_model_config, load_checkpoint
4
+ from .loss import ClipLoss
5
+ from .model import CLIP, CustomCLIP, CLIPTextCfg, CLIPVisionCfg, convert_weights_to_lp, convert_weights_to_fp16, trace_model, get_cast_dtype
6
+ from .openai import load_openai_model, list_openai_models
7
+ from .pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained
8
+ from .tokenizer import SimpleTokenizer, tokenize
9
+ from .transform import image_transform
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/constants.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)
2
+ OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/eva_vit_model.py ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from https://github.com/microsoft/unilm/tree/master/beit
3
+ # --------------------------------------------------------
4
+ import math
5
+ import os
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ try:
11
+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_
12
+ except:
13
+ from timm.layers import drop_path, to_2tuple, trunc_normal_
14
+
15
+ from .transformer import PatchDropout
16
+ from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast
17
+
18
+ if os.getenv("ENV_TYPE") == "deepspeed":
19
+ try:
20
+ from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
21
+ except:
22
+ from torch.utils.checkpoint import checkpoint
23
+ else:
24
+ from torch.utils.checkpoint import checkpoint
25
+
26
+ try:
27
+ import xformers.ops as xops
28
+ except ImportError:
29
+ xops = None
30
+ # print("Please 'pip install xformers'")
31
+
32
+
33
+ class DropPath(nn.Module):
34
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
35
+
36
+ def __init__(self, drop_prob=None):
37
+ super(DropPath, self).__init__()
38
+ self.drop_prob = drop_prob
39
+
40
+ def forward(self, x):
41
+ return drop_path(x, self.drop_prob, self.training)
42
+
43
+ def extra_repr(self) -> str:
44
+ return "p={}".format(self.drop_prob)
45
+
46
+
47
+ class Mlp(nn.Module):
48
+ def __init__(
49
+ self,
50
+ in_features,
51
+ hidden_features=None,
52
+ out_features=None,
53
+ act_layer=nn.GELU,
54
+ norm_layer=nn.LayerNorm,
55
+ drop=0.0,
56
+ subln=False,
57
+ ):
58
+ super().__init__()
59
+ out_features = out_features or in_features
60
+ hidden_features = hidden_features or in_features
61
+ self.fc1 = nn.Linear(in_features, hidden_features)
62
+ self.act = act_layer()
63
+
64
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
65
+
66
+ self.fc2 = nn.Linear(hidden_features, out_features)
67
+ self.drop = nn.Dropout(drop)
68
+
69
+ def forward(self, x):
70
+ x = self.fc1(x)
71
+ x = self.act(x)
72
+ # x = self.drop(x)
73
+ # commit this for the orignal BERT implement
74
+ x = self.ffn_ln(x)
75
+
76
+ x = self.fc2(x)
77
+ x = self.drop(x)
78
+ return x
79
+
80
+
81
+ class SwiGLU(nn.Module):
82
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, norm_layer=nn.LayerNorm, subln=False):
83
+ super().__init__()
84
+ out_features = out_features or in_features
85
+ hidden_features = hidden_features or in_features
86
+
87
+ self.w1 = nn.Linear(in_features, hidden_features)
88
+ self.w2 = nn.Linear(in_features, hidden_features)
89
+
90
+ self.act = act_layer()
91
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
92
+ self.w3 = nn.Linear(hidden_features, out_features)
93
+
94
+ self.drop = nn.Dropout(drop)
95
+
96
+ def forward(self, x):
97
+ x1 = self.w1(x)
98
+ x2 = self.w2(x)
99
+ hidden = self.act(x1) * x2
100
+ x = self.ffn_ln(hidden)
101
+ x = self.w3(x)
102
+ x = self.drop(x)
103
+ return x
104
+
105
+
106
+ class Attention(nn.Module):
107
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm):
108
+ super().__init__()
109
+ self.num_heads = num_heads
110
+ head_dim = dim // num_heads
111
+ if attn_head_dim is not None:
112
+ head_dim = attn_head_dim
113
+ all_head_dim = head_dim * self.num_heads
114
+ self.scale = qk_scale or head_dim**-0.5
115
+
116
+ self.subln = subln
117
+ if self.subln:
118
+ self.q_proj = nn.Linear(dim, all_head_dim, bias=False)
119
+ self.k_proj = nn.Linear(dim, all_head_dim, bias=False)
120
+ self.v_proj = nn.Linear(dim, all_head_dim, bias=False)
121
+ else:
122
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
123
+
124
+ if qkv_bias:
125
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
126
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
127
+ else:
128
+ self.q_bias = None
129
+ self.v_bias = None
130
+
131
+ if window_size:
132
+ self.window_size = window_size
133
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
134
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
135
+ # cls to token & token 2 cls & cls to cls
136
+
137
+ # get pair-wise relative position index for each token inside the window
138
+ coords_h = torch.arange(window_size[0])
139
+ coords_w = torch.arange(window_size[1])
140
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
141
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
142
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
143
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
144
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
145
+ relative_coords[:, :, 1] += window_size[1] - 1
146
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
147
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
148
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
149
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
150
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
151
+ relative_position_index[0, 0] = self.num_relative_distance - 1
152
+
153
+ self.register_buffer("relative_position_index", relative_position_index)
154
+ else:
155
+ self.window_size = None
156
+ self.relative_position_bias_table = None
157
+ self.relative_position_index = None
158
+
159
+ self.attn_drop = nn.Dropout(attn_drop)
160
+ self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity()
161
+ # self.proj = nn.Linear(all_head_dim, all_head_dim)
162
+ self.proj = nn.Linear(all_head_dim, dim)
163
+ self.proj_drop = nn.Dropout(proj_drop)
164
+ self.xattn = xattn
165
+ self.xattn_drop = attn_drop
166
+
167
+ self.rope = rope
168
+
169
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
170
+ B, N, C = x.shape
171
+ if self.subln:
172
+ q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
173
+ k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
174
+ v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
175
+
176
+ q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C
177
+ k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
178
+ v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
179
+ else:
180
+
181
+ qkv_bias = None
182
+ if self.q_bias is not None:
183
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
184
+
185
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
186
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C
187
+ q, k, v = qkv[0], qkv[1], qkv[2]
188
+
189
+ if self.rope:
190
+ # slightly fast impl
191
+ q_t = q[:, :, 1:, :]
192
+ ro_q_t = self.rope(q_t)
193
+ q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
194
+
195
+ k_t = k[:, :, 1:, :]
196
+ ro_k_t = self.rope(k_t)
197
+ k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
198
+
199
+ if self.xattn:
200
+ q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C
201
+ k = k.permute(0, 2, 1, 3)
202
+ v = v.permute(0, 2, 1, 3)
203
+
204
+ x = xops.memory_efficient_attention(
205
+ q,
206
+ k,
207
+ v,
208
+ p=self.xattn_drop,
209
+ scale=self.scale,
210
+ )
211
+ x = x.reshape(B, N, -1)
212
+ x = self.inner_attn_ln(x)
213
+ x = self.proj(x)
214
+ x = self.proj_drop(x)
215
+ else:
216
+ q = q * self.scale
217
+ attn = q @ k.transpose(-2, -1)
218
+
219
+ if self.relative_position_bias_table is not None:
220
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
221
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
222
+ attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
223
+
224
+ if rel_pos_bias is not None:
225
+ attn = attn + rel_pos_bias.type_as(attn)
226
+
227
+ if attn_mask is not None:
228
+ attn_mask = attn_mask.bool()
229
+ attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf"))
230
+
231
+ attn = attn.softmax(dim=-1)
232
+ attn = self.attn_drop(attn)
233
+
234
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
235
+ x = self.inner_attn_ln(x)
236
+ x = self.proj(x)
237
+ x = self.proj_drop(x)
238
+ return x
239
+
240
+
241
+ class Block(nn.Module):
242
+
243
+ def __init__(
244
+ self,
245
+ dim,
246
+ num_heads,
247
+ mlp_ratio=4.0,
248
+ qkv_bias=False,
249
+ qk_scale=None,
250
+ drop=0.0,
251
+ attn_drop=0.0,
252
+ drop_path=0.0,
253
+ init_values=None,
254
+ act_layer=nn.GELU,
255
+ norm_layer=nn.LayerNorm,
256
+ window_size=None,
257
+ attn_head_dim=None,
258
+ xattn=False,
259
+ rope=None,
260
+ postnorm=False,
261
+ subln=False,
262
+ naiveswiglu=False,
263
+ ):
264
+ super().__init__()
265
+ self.norm1 = norm_layer(dim)
266
+ self.attn = Attention(
267
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer
268
+ )
269
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
270
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
271
+ self.norm2 = norm_layer(dim)
272
+ mlp_hidden_dim = int(dim * mlp_ratio)
273
+
274
+ if naiveswiglu:
275
+ self.mlp = SwiGLU(
276
+ in_features=dim,
277
+ hidden_features=mlp_hidden_dim,
278
+ subln=subln,
279
+ norm_layer=norm_layer,
280
+ )
281
+ else:
282
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, subln=subln, drop=drop)
283
+
284
+ if init_values is not None and init_values > 0:
285
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
286
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
287
+ else:
288
+ self.gamma_1, self.gamma_2 = None, None
289
+
290
+ self.postnorm = postnorm
291
+
292
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
293
+ if self.gamma_1 is None:
294
+ if self.postnorm:
295
+ x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
296
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
297
+ else:
298
+ x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
299
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
300
+ else:
301
+ if self.postnorm:
302
+ x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
303
+ x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x)))
304
+ else:
305
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
306
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
307
+ return x
308
+
309
+
310
+ class PatchEmbed(nn.Module):
311
+ """Image to Patch Embedding"""
312
+
313
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
314
+ super().__init__()
315
+ img_size = to_2tuple(img_size)
316
+ patch_size = to_2tuple(patch_size)
317
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
318
+ self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
319
+ self.img_size = img_size
320
+ self.patch_size = patch_size
321
+ self.num_patches = num_patches
322
+
323
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
324
+
325
+ def forward(self, x, **kwargs):
326
+ B, C, H, W = x.shape
327
+ # FIXME look at relaxing size constraints
328
+ assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
329
+ x = self.proj(x).flatten(2).transpose(1, 2)
330
+ return x
331
+
332
+
333
+ class RelativePositionBias(nn.Module):
334
+
335
+ def __init__(self, window_size, num_heads):
336
+ super().__init__()
337
+ self.window_size = window_size
338
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
339
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
340
+ # cls to token & token 2 cls & cls to cls
341
+
342
+ # get pair-wise relative position index for each token inside the window
343
+ coords_h = torch.arange(window_size[0])
344
+ coords_w = torch.arange(window_size[1])
345
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
346
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
347
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
348
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
349
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
350
+ relative_coords[:, :, 1] += window_size[1] - 1
351
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
352
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
353
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
354
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
355
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
356
+ relative_position_index[0, 0] = self.num_relative_distance - 1
357
+
358
+ self.register_buffer("relative_position_index", relative_position_index)
359
+
360
+ def forward(self):
361
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
362
+ return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
363
+
364
+
365
+ class EVAVisionTransformer(nn.Module):
366
+ """Vision Transformer with support for patch or hybrid CNN input stage"""
367
+
368
+ def __init__(
369
+ self,
370
+ img_size=224,
371
+ patch_size=16,
372
+ in_chans=3,
373
+ num_classes=1000,
374
+ embed_dim=768,
375
+ depth=12,
376
+ num_heads=12,
377
+ mlp_ratio=4.0,
378
+ qkv_bias=False,
379
+ qk_scale=None,
380
+ drop_rate=0.0,
381
+ attn_drop_rate=0.0,
382
+ drop_path_rate=0.0,
383
+ norm_layer=nn.LayerNorm,
384
+ init_values=None,
385
+ patch_dropout=0.0,
386
+ use_abs_pos_emb=True,
387
+ use_rel_pos_bias=False,
388
+ use_shared_rel_pos_bias=False,
389
+ rope=False,
390
+ use_mean_pooling=True,
391
+ init_scale=0.001,
392
+ grad_checkpointing=False,
393
+ xattn=False,
394
+ postnorm=False,
395
+ pt_hw_seq_len=16,
396
+ intp_freq=False,
397
+ naiveswiglu=False,
398
+ subln=False,
399
+ ):
400
+ super().__init__()
401
+ self.image_size = img_size
402
+ self.num_classes = num_classes
403
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
404
+
405
+ self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
406
+ num_patches = self.patch_embed.num_patches
407
+
408
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
409
+ # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
410
+ if use_abs_pos_emb:
411
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
412
+ else:
413
+ self.pos_embed = None
414
+ self.pos_drop = nn.Dropout(p=drop_rate)
415
+
416
+ if use_shared_rel_pos_bias:
417
+ self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
418
+ else:
419
+ self.rel_pos_bias = None
420
+
421
+ if rope:
422
+ half_head_dim = embed_dim // num_heads // 2
423
+ hw_seq_len = img_size // patch_size
424
+ self.rope = VisionRotaryEmbeddingFast(
425
+ dim=half_head_dim,
426
+ pt_seq_len=pt_hw_seq_len,
427
+ ft_seq_len=hw_seq_len if intp_freq else None,
428
+ # patch_dropout=patch_dropout
429
+ )
430
+ else:
431
+ self.rope = None
432
+
433
+ self.naiveswiglu = naiveswiglu
434
+
435
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
436
+ self.use_rel_pos_bias = use_rel_pos_bias
437
+ self.blocks = nn.ModuleList(
438
+ [
439
+ Block(
440
+ dim=embed_dim,
441
+ num_heads=num_heads,
442
+ mlp_ratio=mlp_ratio,
443
+ qkv_bias=qkv_bias,
444
+ qk_scale=qk_scale,
445
+ drop=drop_rate,
446
+ attn_drop=attn_drop_rate,
447
+ drop_path=dpr[i],
448
+ norm_layer=norm_layer,
449
+ init_values=init_values,
450
+ window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None,
451
+ xattn=xattn,
452
+ rope=self.rope,
453
+ postnorm=postnorm,
454
+ subln=subln,
455
+ naiveswiglu=naiveswiglu,
456
+ )
457
+ for i in range(depth)
458
+ ]
459
+ )
460
+ self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
461
+ self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
462
+ self.head = nn.Linear(embed_dim, num_classes, bias=qkv_bias) if num_classes > 0 else nn.Identity()
463
+
464
+ if self.pos_embed is not None:
465
+ trunc_normal_(self.pos_embed, std=0.02)
466
+
467
+ trunc_normal_(self.cls_token, std=0.02)
468
+
469
+ self.apply(self._init_weights)
470
+ self.fix_init_weight()
471
+
472
+ if isinstance(self.head, nn.Linear):
473
+ trunc_normal_(self.head.weight, std=0.02)
474
+ self.head.weight.data.mul_(init_scale)
475
+ if self.head.bias is not None:
476
+ self.head.bias.data.mul_(init_scale)
477
+
478
+ # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
479
+ self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity()
480
+
481
+ self.grad_checkpointing = grad_checkpointing
482
+
483
+ def fix_init_weight(self):
484
+ def rescale(param, layer_id):
485
+ param.div_(math.sqrt(2.0 * layer_id))
486
+
487
+ for layer_id, layer in enumerate(self.blocks):
488
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
489
+ if self.naiveswiglu:
490
+ rescale(layer.mlp.w3.weight.data, layer_id + 1)
491
+ else:
492
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
493
+
494
+ def get_cast_dtype(self) -> torch.dtype:
495
+ return self.blocks[0].mlp.fc2.weight.dtype
496
+
497
+ def _init_weights(self, m):
498
+ if isinstance(m, nn.Linear):
499
+ trunc_normal_(m.weight, std=0.02)
500
+ if m.bias is not None:
501
+ nn.init.constant_(m.bias, 0)
502
+ elif isinstance(m, nn.LayerNorm):
503
+ nn.init.constant_(m.bias, 0)
504
+ nn.init.constant_(m.weight, 1.0)
505
+
506
+ def get_num_layers(self):
507
+ return len(self.blocks)
508
+
509
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
510
+ assert unlocked_groups == 0, "partial locking not currently supported for this model"
511
+ for param in self.parameters():
512
+ param.requires_grad = False
513
+
514
+ @torch.jit.ignore
515
+ def set_grad_checkpointing(self, enable=True):
516
+ self.grad_checkpointing = enable
517
+
518
+ @torch.jit.ignore
519
+ def no_weight_decay(self):
520
+ return {"pos_embed", "cls_token"}
521
+
522
+ def get_classifier(self):
523
+ return self.head
524
+
525
+ def reset_classifier(self, num_classes, global_pool=""):
526
+ self.num_classes = num_classes
527
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
528
+
529
+ def forward_features(self, x, return_all_features=False):
530
+
531
+ x = self.patch_embed(x)
532
+ batch_size, seq_len, _ = x.size()
533
+
534
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
535
+ x = torch.cat((cls_tokens, x), dim=1)
536
+ if self.pos_embed is not None:
537
+ x = x + self.pos_embed
538
+ x = self.pos_drop(x)
539
+
540
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
541
+ # if os.getenv("RoPE") == "1":
542
+ # if self.training and not isinstance(self.patch_dropout, nn.Identity):
543
+ # x, patch_indices_keep = self.patch_dropout(x)
544
+ # self.rope.forward = partial(self.rope.forward, patch_indices_keep=patch_indices_keep)
545
+ # else:
546
+ # self.rope.forward = partial(self.rope.forward, patch_indices_keep=None)
547
+ # x = self.patch_dropout(x)
548
+ # else:
549
+ x = self.patch_dropout(x)
550
+
551
+ rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
552
+ for blk in self.blocks:
553
+ if self.grad_checkpointing:
554
+ x = checkpoint(blk, x, (rel_pos_bias,))
555
+ else:
556
+ x = blk(x, rel_pos_bias=rel_pos_bias)
557
+
558
+ if not return_all_features:
559
+ x = self.norm(x)
560
+ if self.fc_norm is not None:
561
+ return self.fc_norm(x.mean(1))
562
+ else:
563
+ return x[:, 0]
564
+ return x
565
+
566
+ def forward(self, x, return_all_features=False):
567
+ if return_all_features:
568
+ return self.forward_features(x, return_all_features)
569
+ x = self.forward_features(x)
570
+ x = self.head(x)
571
+ return x
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/factory.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import pathlib
5
+ import re
6
+ from copy import deepcopy
7
+ from pathlib import Path
8
+ from typing import Optional, Tuple, Union, Dict, Any
9
+ import torch
10
+
11
+ try:
12
+ import deepspeed
13
+ except ImportError:
14
+ deepspeed = None
15
+
16
+ from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
17
+ from .model import CLIP, CustomCLIP, convert_weights_to_lp, convert_to_custom_text_state_dict, get_cast_dtype
18
+ from .openai import load_openai_model
19
+ from .pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained, list_pretrained_tags_by_model
20
+ from .transform import image_transform
21
+ from .tokenizer import HFTokenizer, tokenize
22
+ from .utils import resize_clip_pos_embed, resize_evaclip_pos_embed, resize_visual_pos_embed, resize_eva_pos_embed
23
+
24
+
25
+ _MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
26
+ _MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
27
+
28
+
29
+ def _natural_key(string_):
30
+ return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())]
31
+
32
+
33
+ def _rescan_model_configs():
34
+ global _MODEL_CONFIGS
35
+
36
+ config_ext = (".json",)
37
+ config_files = []
38
+ for config_path in _MODEL_CONFIG_PATHS:
39
+ if config_path.is_file() and config_path.suffix in config_ext:
40
+ config_files.append(config_path)
41
+ elif config_path.is_dir():
42
+ for ext in config_ext:
43
+ config_files.extend(config_path.glob(f"*{ext}"))
44
+
45
+ for cf in config_files:
46
+ with open(cf, "r", encoding="utf8") as f:
47
+ model_cfg = json.load(f)
48
+ if all(a in model_cfg for a in ("embed_dim", "vision_cfg", "text_cfg")):
49
+ _MODEL_CONFIGS[cf.stem] = model_cfg
50
+
51
+ _MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0])))
52
+
53
+
54
+ _rescan_model_configs() # initial populate of model config registry
55
+
56
+
57
+ def list_models():
58
+ """enumerate available model architectures based on config files"""
59
+ return list(_MODEL_CONFIGS.keys())
60
+
61
+
62
+ def add_model_config(path):
63
+ """add model config path or file and update registry"""
64
+ if not isinstance(path, Path):
65
+ path = Path(path)
66
+ _MODEL_CONFIG_PATHS.append(path)
67
+ _rescan_model_configs()
68
+
69
+
70
+ def get_model_config(model_name):
71
+ if model_name in _MODEL_CONFIGS:
72
+ return deepcopy(_MODEL_CONFIGS[model_name])
73
+ else:
74
+ return None
75
+
76
+
77
+ def get_tokenizer(model_name):
78
+ config = get_model_config(model_name)
79
+ tokenizer = HFTokenizer(config["text_cfg"]["hf_tokenizer_name"]) if "hf_tokenizer_name" in config["text_cfg"] else tokenize
80
+ return tokenizer
81
+
82
+
83
+ # loading openai CLIP weights when is_openai=True for training
84
+ def load_state_dict(checkpoint_path: str, map_location: str = "cpu", model_key: str = "model|module|state_dict", is_openai: bool = False, skip_list: list = []):
85
+ if is_openai:
86
+ model = torch.jit.load(checkpoint_path, map_location="cpu").eval()
87
+ state_dict = model.state_dict()
88
+ for key in ["input_resolution", "context_length", "vocab_size"]:
89
+ state_dict.pop(key, None)
90
+ else:
91
+ checkpoint = torch.load(checkpoint_path, map_location=map_location)
92
+ for mk in model_key.split("|"):
93
+ if isinstance(checkpoint, dict) and mk in checkpoint:
94
+ state_dict = checkpoint[mk]
95
+ break
96
+ else:
97
+ state_dict = checkpoint
98
+ if next(iter(state_dict.items()))[0].startswith("module"):
99
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
100
+
101
+ for k in skip_list:
102
+ if k in list(state_dict.keys()):
103
+ logging.info(f"Removing key {k} from pretrained checkpoint")
104
+ del state_dict[k]
105
+
106
+ if os.getenv("RoPE") == "1":
107
+ for k in list(state_dict.keys()):
108
+ if "freqs_cos" in k or "freqs_sin" in k:
109
+ del state_dict[k]
110
+ return state_dict
111
+
112
+
113
+ def load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=True):
114
+ state_dict = load_state_dict(checkpoint_path, model_key=model_key, is_openai=False)
115
+ # detect old format and make compatible with new format
116
+ if "positional_embedding" in state_dict and not hasattr(model, "positional_embedding"):
117
+ state_dict = convert_to_custom_text_state_dict(state_dict)
118
+ if "text.logit_scale" in state_dict and hasattr(model, "logit_scale"):
119
+ state_dict["logit_scale"] = state_dict["text.logit_scale"]
120
+ del state_dict["text.logit_scale"]
121
+
122
+ # resize_clip_pos_embed for CLIP and open CLIP
123
+ if "visual.positional_embedding" in state_dict:
124
+ resize_clip_pos_embed(state_dict, model)
125
+ # specified to eva_vit_model
126
+ elif "visual.pos_embed" in state_dict:
127
+ resize_evaclip_pos_embed(state_dict, model)
128
+
129
+ # resize_clip_pos_embed(state_dict, model)
130
+ incompatible_keys = model.load_state_dict(state_dict, strict=strict)
131
+ logging.info(f"incompatible_keys.missing_keys: {incompatible_keys.missing_keys}")
132
+ return incompatible_keys
133
+
134
+
135
+ def load_clip_visual_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []):
136
+ state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list)
137
+
138
+ for k in list(state_dict.keys()):
139
+ if not k.startswith("visual."):
140
+ del state_dict[k]
141
+ for k in list(state_dict.keys()):
142
+ if k.startswith("visual."):
143
+ new_k = k[7:]
144
+ state_dict[new_k] = state_dict[k]
145
+ del state_dict[k]
146
+ return state_dict
147
+
148
+
149
+ def load_clip_text_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []):
150
+ state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list)
151
+
152
+ for k in list(state_dict.keys()):
153
+ if k.startswith("visual."):
154
+ del state_dict[k]
155
+ return state_dict
156
+
157
+
158
+ def get_pretrained_tag(pretrained_model):
159
+ pretrained_model = pretrained_model.lower()
160
+ if "laion" in pretrained_model or "open_clip" in pretrained_model:
161
+ return "open_clip"
162
+ elif "openai" in pretrained_model:
163
+ return "clip"
164
+ elif "eva" in pretrained_model and "clip" in pretrained_model:
165
+ return "eva_clip"
166
+ else:
167
+ return "other"
168
+
169
+
170
+ def load_zero_partitions(model, state_dict, is_deepspeed_zero3_enabled, pretrained_model_path, ignore_mismatched_sizes=False):
171
+ """
172
+ adept from pytorch lightning and transformers
173
+ with deepspeed.zero.Init():
174
+ model = MyModel()
175
+ state_dict = torch.load(model_path, map_location="cpu")
176
+ load_zero_partitions(model, prefix="")
177
+ """
178
+
179
+ # because zero3 puts placeholders in model params, this context
180
+ # manager gathers (unpartitions) the params of the current layer, then loads from
181
+ # the state dict and then re-partitions them again
182
+ model_state_dict = model.state_dict()
183
+ expected_keys = list(model_state_dict.keys())
184
+ loaded_keys = list(state_dict.keys())
185
+ missing_keys = list(set(expected_keys) - set(loaded_keys))
186
+ unexpected_keys = list(set(loaded_keys) - set(expected_keys))
187
+
188
+ # Mistmatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not
189
+ # matching the weights in the model.
190
+ mismatched_keys = []
191
+ if ignore_mismatched_sizes:
192
+ for checkpoint_key in loaded_keys:
193
+ model_key = checkpoint_key
194
+
195
+ if model_key in model_state_dict and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape:
196
+ mismatched_keys.append((checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape))
197
+ del state_dict[checkpoint_key]
198
+ # copy state_dict so _load_from_state_dict can modify it
199
+ metadata = getattr(state_dict, "_metadata", None)
200
+ state_dict = state_dict.copy()
201
+ if metadata is not None:
202
+ state_dict._metadata = metadata
203
+
204
+ error_msgs = []
205
+
206
+ # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
207
+ # so we need to apply the function recursively.
208
+ def load(module, prefix=""):
209
+ local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
210
+ args = (state_dict, prefix, local_metadata, True, [], [], error_msgs)
211
+ if is_deepspeed_zero3_enabled:
212
+ # because zero3 puts placeholders in model params, this context
213
+ # manager gathers (unpartitions) the params of the current layer, then loads from
214
+ # the state dict and then re-partitions them again
215
+ with deepspeed.zero.GatheredParameters(list(module.parameters(recurse=False)), modifier_rank=0):
216
+ if torch.distributed.get_rank() == 0:
217
+ module._load_from_state_dict(*args)
218
+ else:
219
+ module._load_from_state_dict(*args)
220
+
221
+ for name, child in module._modules.items():
222
+ if child is not None:
223
+ load(child, prefix + name + ".")
224
+
225
+ # Make sure we are able to load base models as well as derived models (with heads)
226
+ start_prefix = ""
227
+ model_to_load = model
228
+ load(model_to_load, prefix=start_prefix)
229
+ del state_dict
230
+ if len(error_msgs) > 0:
231
+ error_msg = "\n\t".join(error_msgs)
232
+ if "size mismatch" in error_msg:
233
+ error_msg += "\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."
234
+ raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
235
+ if len(unexpected_keys) > 0:
236
+ logging.warning(
237
+ f"Some weights of the model checkpoint at {pretrained_model_path} were not used when"
238
+ f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
239
+ f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
240
+ " with another architecture (e.g. initializing a BertForSequenceClassification model from a"
241
+ " BertForPreTraining model).\n- This IS NOT expected if you are initializing"
242
+ f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly identical"
243
+ " (initializing a BertForSequenceClassification model from a BertForSequenceClassification model)."
244
+ )
245
+ else:
246
+ logging.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
247
+ if len(missing_keys) > 0:
248
+ logging.warning(
249
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
250
+ f" {pretrained_model_path} and are newly initialized: {missing_keys}\nYou should probably"
251
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
252
+ )
253
+ elif len(mismatched_keys) == 0:
254
+ logging.info(
255
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
256
+ f" {pretrained_model_path}.\nIf your task is similar to the task the model of the checkpoint"
257
+ f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
258
+ " training."
259
+ )
260
+ if len(mismatched_keys) > 0:
261
+ mismatched_warning = "\n".join([f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated" for key, shape1, shape2 in mismatched_keys])
262
+ logging.warning(
263
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
264
+ f" {pretrained_model_path} and are newly initialized because the shapes did not"
265
+ f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be able"
266
+ " to use it for predictions and inference."
267
+ )
268
+
269
+
270
+ def load_pretrained_checkpoint(model, visual_checkpoint_path, text_checkpoint_path, strict=True, visual_model=None, text_model=None, model_key="model|module|state_dict", skip_list=[]):
271
+ visual_tag = get_pretrained_tag(visual_model)
272
+ text_tag = get_pretrained_tag(text_model)
273
+
274
+ logging.info(f"num of model state_dict keys: {len(model.state_dict().keys())}")
275
+ visual_incompatible_keys, text_incompatible_keys = None, None
276
+ if visual_checkpoint_path:
277
+ if visual_tag == "eva_clip" or visual_tag == "open_clip":
278
+ visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=False, skip_list=skip_list)
279
+ elif visual_tag == "clip":
280
+ visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=True, skip_list=skip_list)
281
+ else:
282
+ visual_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list)
283
+
284
+ # resize_clip_pos_embed for CLIP and open CLIP
285
+ if "positional_embedding" in visual_state_dict:
286
+ resize_visual_pos_embed(visual_state_dict, model)
287
+ # specified to EVA model
288
+ elif "pos_embed" in visual_state_dict:
289
+ resize_eva_pos_embed(visual_state_dict, model)
290
+
291
+ visual_incompatible_keys = model.visual.load_state_dict(visual_state_dict, strict=strict)
292
+ logging.info(f"num of loaded visual_state_dict keys: {len(visual_state_dict.keys())}")
293
+ logging.info(f"visual_incompatible_keys.missing_keys: {visual_incompatible_keys.missing_keys}")
294
+
295
+ if text_checkpoint_path:
296
+ if text_tag == "eva_clip" or text_tag == "open_clip":
297
+ text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=False, skip_list=skip_list)
298
+ elif text_tag == "clip":
299
+ text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=True, skip_list=skip_list)
300
+ else:
301
+ text_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list)
302
+
303
+ text_incompatible_keys = model.text.load_state_dict(text_state_dict, strict=strict)
304
+
305
+ logging.info(f"num of loaded text_state_dict keys: {len(text_state_dict.keys())}")
306
+ logging.info(f"text_incompatible_keys.missing_keys: {text_incompatible_keys.missing_keys}")
307
+
308
+ return visual_incompatible_keys, text_incompatible_keys
309
+
310
+
311
+ def create_model(
312
+ model_name: str,
313
+ pretrained: Optional[str] = None,
314
+ precision: str = "fp32",
315
+ device: Union[str, torch.device] = "cpu",
316
+ jit: bool = False,
317
+ force_quick_gelu: bool = False,
318
+ force_custom_clip: bool = False,
319
+ force_patch_dropout: Optional[float] = None,
320
+ pretrained_image: str = "",
321
+ pretrained_text: str = "",
322
+ pretrained_hf: bool = True,
323
+ pretrained_visual_model: str = None,
324
+ pretrained_text_model: str = None,
325
+ cache_dir: Optional[str] = None,
326
+ skip_list: list = [],
327
+ ):
328
+ model_name = model_name.replace("/", "-") # for callers using old naming with / in ViT names
329
+ if isinstance(device, str):
330
+ device = torch.device(device)
331
+
332
+ if pretrained and pretrained.lower() == "openai":
333
+ logging.info(f"Loading pretrained {model_name} from OpenAI.")
334
+ model = load_openai_model(
335
+ model_name,
336
+ precision=precision,
337
+ device=device,
338
+ jit=jit,
339
+ cache_dir=cache_dir,
340
+ )
341
+ else:
342
+ model_cfg = get_model_config(model_name)
343
+ if model_cfg is not None:
344
+ logging.info(f"Loaded {model_name} model config.")
345
+ else:
346
+ logging.error(f"Model config for {model_name} not found; available models {list_models()}.")
347
+ raise RuntimeError(f"Model config for {model_name} not found.")
348
+
349
+ if "rope" in model_cfg.get("vision_cfg", {}):
350
+ if model_cfg["vision_cfg"]["rope"]:
351
+ os.environ["RoPE"] = "1"
352
+ else:
353
+ os.environ["RoPE"] = "0"
354
+
355
+ if force_quick_gelu:
356
+ # override for use of QuickGELU on non-OpenAI transformer models
357
+ model_cfg["quick_gelu"] = True
358
+
359
+ if force_patch_dropout is not None:
360
+ # override the default patch dropout value
361
+ model_cfg["vision_cfg"]["patch_dropout"] = force_patch_dropout
362
+
363
+ cast_dtype = get_cast_dtype(precision)
364
+ custom_clip = model_cfg.pop("custom_text", False) or force_custom_clip or ("hf_model_name" in model_cfg["text_cfg"])
365
+
366
+ if custom_clip:
367
+ if "hf_model_name" in model_cfg.get("text_cfg", {}):
368
+ model_cfg["text_cfg"]["hf_model_pretrained"] = pretrained_hf
369
+ model = CustomCLIP(**model_cfg, cast_dtype=cast_dtype)
370
+ else:
371
+ model = CLIP(**model_cfg, cast_dtype=cast_dtype)
372
+
373
+ pretrained_cfg = {}
374
+ if pretrained:
375
+ checkpoint_path = ""
376
+ pretrained_cfg = get_pretrained_cfg(model_name, pretrained)
377
+ if pretrained_cfg:
378
+ checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir)
379
+ elif os.path.exists(pretrained):
380
+ checkpoint_path = pretrained
381
+
382
+ if checkpoint_path:
383
+ logging.info(f"Loading pretrained {model_name} weights ({pretrained}).")
384
+ load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=False)
385
+ else:
386
+ error_str = f"Pretrained weights ({pretrained}) not found for model {model_name}." f"Available pretrained tags ({list_pretrained_tags_by_model(model_name)}."
387
+ logging.warning(error_str)
388
+ raise RuntimeError(error_str)
389
+ else:
390
+ visual_checkpoint_path = ""
391
+ text_checkpoint_path = ""
392
+
393
+ if pretrained_image:
394
+ pretrained_visual_model = pretrained_visual_model.replace("/", "-") # for callers using old naming with / in ViT names
395
+ pretrained_image_cfg = get_pretrained_cfg(pretrained_visual_model, pretrained_image)
396
+ if "timm_model_name" in model_cfg.get("vision_cfg", {}):
397
+ # pretrained weight loading for timm models set via vision_cfg
398
+ model_cfg["vision_cfg"]["timm_model_pretrained"] = True
399
+ elif pretrained_image_cfg:
400
+ visual_checkpoint_path = download_pretrained(pretrained_image_cfg, cache_dir=cache_dir)
401
+ elif os.path.exists(pretrained_image):
402
+ visual_checkpoint_path = pretrained_image
403
+ else:
404
+ logging.warning(f"Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.")
405
+ raise RuntimeError(f"Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.")
406
+
407
+ if pretrained_text:
408
+ pretrained_text_model = pretrained_text_model.replace("/", "-") # for callers using old naming with / in ViT names
409
+ pretrained_text_cfg = get_pretrained_cfg(pretrained_text_model, pretrained_text)
410
+ if pretrained_image_cfg:
411
+ text_checkpoint_path = download_pretrained(pretrained_text_cfg, cache_dir=cache_dir)
412
+ elif os.path.exists(pretrained_text):
413
+ text_checkpoint_path = pretrained_text
414
+ else:
415
+ logging.warning(f"Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.")
416
+ raise RuntimeError(f"Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.")
417
+
418
+ if visual_checkpoint_path:
419
+ logging.info(f"Loading pretrained {model_name}.visual weights ({visual_checkpoint_path}).")
420
+ if text_checkpoint_path:
421
+ logging.info(f"Loading pretrained {model_name}.text weights ({text_checkpoint_path}).")
422
+
423
+ if visual_checkpoint_path or text_checkpoint_path:
424
+ load_pretrained_checkpoint(model, visual_checkpoint_path, text_checkpoint_path, strict=False, visual_model=pretrained_visual_model, text_model=pretrained_text_model, model_key="model|module|state_dict", skip_list=skip_list)
425
+
426
+ if "fp16" in precision or "bf16" in precision:
427
+ logging.info(f"convert precision to {precision}")
428
+ model = model.to(torch.bfloat16) if "bf16" in precision else model.to(torch.float16)
429
+
430
+ # model.to(device=device)
431
+
432
+ # set image / mean metadata from pretrained_cfg if available, or use default
433
+ model.visual.image_mean = pretrained_cfg.get("mean", None) or OPENAI_DATASET_MEAN
434
+ model.visual.image_std = pretrained_cfg.get("std", None) or OPENAI_DATASET_STD
435
+
436
+ if jit:
437
+ model = torch.jit.script(model)
438
+
439
+ return model
440
+
441
+
442
+ def create_model_and_transforms(
443
+ model_name: str,
444
+ pretrained: Optional[str] = None,
445
+ precision: str = "fp32",
446
+ device: Union[str, torch.device] = "cpu",
447
+ jit: bool = False,
448
+ force_quick_gelu: bool = False,
449
+ force_custom_clip: bool = False,
450
+ force_patch_dropout: Optional[float] = None,
451
+ pretrained_image: str = "",
452
+ pretrained_text: str = "",
453
+ pretrained_hf: bool = True,
454
+ pretrained_visual_model: str = None,
455
+ pretrained_text_model: str = None,
456
+ image_mean: Optional[Tuple[float, ...]] = None,
457
+ image_std: Optional[Tuple[float, ...]] = None,
458
+ cache_dir: Optional[str] = None,
459
+ skip_list: list = [],
460
+ ):
461
+ model = create_model(
462
+ model_name,
463
+ pretrained,
464
+ precision=precision,
465
+ device=device,
466
+ jit=jit,
467
+ force_quick_gelu=force_quick_gelu,
468
+ force_custom_clip=force_custom_clip,
469
+ force_patch_dropout=force_patch_dropout,
470
+ pretrained_image=pretrained_image,
471
+ pretrained_text=pretrained_text,
472
+ pretrained_hf=pretrained_hf,
473
+ pretrained_visual_model=pretrained_visual_model,
474
+ pretrained_text_model=pretrained_text_model,
475
+ cache_dir=cache_dir,
476
+ skip_list=skip_list,
477
+ )
478
+
479
+ image_mean = image_mean or getattr(model.visual, "image_mean", None)
480
+ image_std = image_std or getattr(model.visual, "image_std", None)
481
+ preprocess_train = image_transform(model.visual.image_size, is_train=True, mean=image_mean, std=image_std)
482
+ preprocess_val = image_transform(model.visual.image_size, is_train=False, mean=image_mean, std=image_std)
483
+
484
+ return model, preprocess_train, preprocess_val
485
+
486
+
487
+ def create_model_from_pretrained(
488
+ model_name: str,
489
+ pretrained: str,
490
+ precision: str = "fp32",
491
+ device: Union[str, torch.device] = "cpu",
492
+ jit: bool = False,
493
+ force_quick_gelu: bool = False,
494
+ force_custom_clip: bool = False,
495
+ force_patch_dropout: Optional[float] = None,
496
+ return_transform: bool = True,
497
+ image_mean: Optional[Tuple[float, ...]] = None,
498
+ image_std: Optional[Tuple[float, ...]] = None,
499
+ cache_dir: Optional[str] = None,
500
+ is_frozen: bool = False,
501
+ ):
502
+ if not is_pretrained_cfg(model_name, pretrained) and not os.path.exists(pretrained):
503
+ raise RuntimeError(f"{pretrained} is not a valid pretrained cfg or checkpoint for {model_name}." f" Use open_clip.list_pretrained() to find one.")
504
+
505
+ model = create_model(
506
+ model_name,
507
+ pretrained,
508
+ precision=precision,
509
+ device=device,
510
+ jit=jit,
511
+ force_quick_gelu=force_quick_gelu,
512
+ force_custom_clip=force_custom_clip,
513
+ force_patch_dropout=force_patch_dropout,
514
+ cache_dir=cache_dir,
515
+ )
516
+
517
+ if is_frozen:
518
+ for param in model.parameters():
519
+ param.requires_grad = False
520
+
521
+ if not return_transform:
522
+ return model
523
+
524
+ image_mean = image_mean or getattr(model.visual, "image_mean", None)
525
+ image_std = image_std or getattr(model.visual, "image_std", None)
526
+ preprocess = image_transform(model.visual.image_size, is_train=False, mean=image_mean, std=image_std)
527
+
528
+ return model, preprocess
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_configs.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HF architecture dict:
2
+ arch_dict = {
3
+ # https://huggingface.co/docs/transformers/model_doc/roberta#roberta
4
+ "roberta": {
5
+ "config_names": {
6
+ "context_length": "max_position_embeddings",
7
+ "vocab_size": "vocab_size",
8
+ "width": "hidden_size",
9
+ "heads": "num_attention_heads",
10
+ "layers": "num_hidden_layers",
11
+ "layer_attr": "layer",
12
+ "token_embeddings_attr": "embeddings",
13
+ },
14
+ "pooler": "mean_pooler",
15
+ },
16
+ # https://huggingface.co/docs/transformers/model_doc/xlm-roberta#transformers.XLMRobertaConfig
17
+ "xlm-roberta": {
18
+ "config_names": {
19
+ "context_length": "max_position_embeddings",
20
+ "vocab_size": "vocab_size",
21
+ "width": "hidden_size",
22
+ "heads": "num_attention_heads",
23
+ "layers": "num_hidden_layers",
24
+ "layer_attr": "layer",
25
+ "token_embeddings_attr": "embeddings",
26
+ },
27
+ "pooler": "mean_pooler",
28
+ },
29
+ # https://huggingface.co/docs/transformers/model_doc/mt5#mt5
30
+ "mt5": {
31
+ "config_names": {
32
+ # unlimited seqlen
33
+ # https://github.com/google-research/text-to-text-transfer-transformer/issues/273
34
+ # https://github.com/huggingface/transformers/blob/v4.24.0/src/transformers/models/t5/modeling_t5.py#L374
35
+ "context_length": "",
36
+ "vocab_size": "vocab_size",
37
+ "width": "d_model",
38
+ "heads": "num_heads",
39
+ "layers": "num_layers",
40
+ "layer_attr": "block",
41
+ "token_embeddings_attr": "embed_tokens",
42
+ },
43
+ "pooler": "mean_pooler",
44
+ },
45
+ "bert": {
46
+ "config_names": {
47
+ "context_length": "max_position_embeddings",
48
+ "vocab_size": "vocab_size",
49
+ "width": "hidden_size",
50
+ "heads": "num_attention_heads",
51
+ "layers": "num_hidden_layers",
52
+ "layer_attr": "layer",
53
+ "token_embeddings_attr": "embeddings",
54
+ },
55
+ "pooler": "mean_pooler",
56
+ },
57
+ }
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_model.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ huggingface model adapter
2
+
3
+ Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model.
4
+ """
5
+
6
+ import re
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from torch.nn import functional as F
11
+ from torch import TensorType
12
+
13
+ try:
14
+ import transformers
15
+ from transformers import AutoModel, AutoModelForMaskedLM, AutoTokenizer, AutoConfig, PretrainedConfig
16
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions
17
+ except ImportError as e:
18
+ transformers = None
19
+
20
+ class BaseModelOutput:
21
+ pass
22
+
23
+ class PretrainedConfig:
24
+ pass
25
+
26
+
27
+ from .hf_configs import arch_dict
28
+
29
+
30
+ # utils
31
+ def _camel2snake(s):
32
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", s).lower()
33
+
34
+
35
+ # TODO: ?last - for gpt-like models
36
+ _POOLERS = {}
37
+
38
+
39
+ def register_pooler(cls):
40
+ """Decorator registering pooler class"""
41
+ _POOLERS[_camel2snake(cls.__name__)] = cls
42
+ return cls
43
+
44
+
45
+ @register_pooler
46
+ class MeanPooler(nn.Module):
47
+ """Mean pooling"""
48
+
49
+ def forward(self, x: BaseModelOutput, attention_mask: TensorType):
50
+ masked_output = x.last_hidden_state * attention_mask.unsqueeze(-1)
51
+ return masked_output.sum(dim=1) / attention_mask.sum(-1, keepdim=True)
52
+
53
+
54
+ @register_pooler
55
+ class MaxPooler(nn.Module):
56
+ """Max pooling"""
57
+
58
+ def forward(self, x: BaseModelOutput, attention_mask: TensorType):
59
+ masked_output = x.last_hidden_state.masked_fill(attention_mask.unsqueeze(-1), -torch.inf)
60
+ return masked_output.max(1).values
61
+
62
+
63
+ @register_pooler
64
+ class ClsPooler(nn.Module):
65
+ """CLS token pooling"""
66
+
67
+ def __init__(self, use_pooler_output=True):
68
+ super().__init__()
69
+ self.cls_token_position = 0
70
+ self.use_pooler_output = use_pooler_output
71
+
72
+ def forward(self, x: BaseModelOutput, attention_mask: TensorType):
73
+
74
+ if self.use_pooler_output and isinstance(x, (BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions)) and (x.pooler_output is not None):
75
+ return x.pooler_output
76
+
77
+ return x.last_hidden_state[:, self.cls_token_position, :]
78
+
79
+
80
+ class HFTextEncoder(nn.Module):
81
+ """HuggingFace model adapter"""
82
+
83
+ def __init__(self, model_name_or_path: str, output_dim: int, tokenizer_name: str = None, config: PretrainedConfig = None, pooler_type: str = None, proj: str = None, pretrained: bool = True, masked_language_modeling: bool = False):
84
+ super().__init__()
85
+
86
+ self.output_dim = output_dim
87
+
88
+ # TODO: find better way to get this information
89
+ uses_transformer_pooler = pooler_type == "cls_pooler"
90
+
91
+ if transformers is None:
92
+ raise RuntimeError("Please `pip install transformers` to use pre-trained HuggingFace models")
93
+ if config is None:
94
+ self.config = AutoConfig.from_pretrained(model_name_or_path)
95
+ if masked_language_modeling:
96
+ create_func, model_args = (AutoModelForMaskedLM.from_pretrained, model_name_or_path) if pretrained else (AutoModelForMaskedLM.from_config, self.config)
97
+ else:
98
+ create_func, model_args = (AutoModel.from_pretrained, model_name_or_path) if pretrained else (AutoModel.from_config, self.config)
99
+ # TODO: do all model configs have this attribute? PretrainedConfig does so yes??
100
+ if hasattr(self.config, "is_encoder_decoder") and self.config.is_encoder_decoder:
101
+ self.transformer = create_func(model_args)
102
+ self.transformer = self.transformer.encoder
103
+ else:
104
+ self.transformer = create_func(model_args, add_pooling_layer=uses_transformer_pooler)
105
+ else:
106
+ self.config = config
107
+ if masked_language_modeling:
108
+ self.transformer = AutoModelForMaskedLM.from_config(config)
109
+ else:
110
+ self.transformer = AutoModel.from_config(config)
111
+
112
+ if pooler_type is None: # get default arch pooler
113
+ self.pooler = _POOLERS[(arch_dict[self.config.model_type]["pooler"])]()
114
+ else:
115
+ self.pooler = _POOLERS[pooler_type]()
116
+
117
+ d_model = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["width"])
118
+ if (d_model == output_dim) and (proj is None): # do we always need a proj?
119
+ self.proj = nn.Identity()
120
+ elif proj == "linear":
121
+ self.proj = nn.Linear(d_model, output_dim, bias=False)
122
+ elif proj == "mlp":
123
+ hidden_size = (d_model + output_dim) // 2
124
+ self.proj = nn.Sequential(
125
+ nn.Linear(d_model, hidden_size, bias=False),
126
+ nn.GELU(),
127
+ nn.Linear(hidden_size, output_dim, bias=False),
128
+ )
129
+
130
+ # self.itm_proj = nn.Linear(d_model, 2, bias=False)
131
+ # self.mlm_proj = nn.Linear(d_model, self.config.vocab_size), bias=False)
132
+ self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
133
+
134
+ # def forward_itm(self, x:TensorType, image_embeds:TensorType) -> TensorType:
135
+ # image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(x.device)
136
+ # attn_mask = (x != self.config.pad_token_id).long()
137
+ # out = self.transformer(
138
+ # input_ids=x,
139
+ # attention_mask=attn_mask,
140
+ # encoder_hidden_states = image_embeds,
141
+ # encoder_attention_mask = image_atts,
142
+ # )
143
+ # pooled_out = self.pooler(out, attn_mask)
144
+
145
+ # return self.itm_proj(pooled_out)
146
+
147
+ def mask(self, input_ids, vocab_size, device, targets=None, masked_indices=None, probability_matrix=None):
148
+ if masked_indices is None:
149
+ masked_indices = torch.bernoulli(probability_matrix).bool()
150
+
151
+ masked_indices[input_ids == self.tokenizer.pad_token_id] = False
152
+ masked_indices[input_ids == self.tokenizer.cls_token_id] = False
153
+
154
+ if targets is not None:
155
+ targets[~masked_indices] = -100 # We only compute loss on masked tokens
156
+
157
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
158
+ indices_replaced = torch.bernoulli(torch.full(input_ids.shape, 0.8)).bool() & masked_indices
159
+ input_ids[indices_replaced] = self.tokenizer.mask_token_id
160
+
161
+ # 10% of the time, we replace masked input tokens with random word
162
+ indices_random = torch.bernoulli(torch.full(input_ids.shape, 0.5)).bool() & masked_indices & ~indices_replaced
163
+ random_words = torch.randint(vocab_size, input_ids.shape, dtype=torch.long).to(device)
164
+ input_ids[indices_random] = random_words[indices_random]
165
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
166
+
167
+ if targets is not None:
168
+ return input_ids, targets
169
+ else:
170
+ return input_ids
171
+
172
+ def forward_mlm(self, input_ids, image_embeds, mlm_probability=0.25):
173
+ labels = input_ids.clone()
174
+ attn_mask = (input_ids != self.config.pad_token_id).long()
175
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(input_ids.device)
176
+ vocab_size = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["vocab_size"])
177
+ probability_matrix = torch.full(labels.shape, mlm_probability)
178
+ input_ids, labels = self.mask(input_ids, vocab_size, input_ids.device, targets=labels, probability_matrix=probability_matrix)
179
+ mlm_output = self.transformer(
180
+ input_ids,
181
+ attention_mask=attn_mask,
182
+ encoder_hidden_states=image_embeds,
183
+ encoder_attention_mask=image_atts,
184
+ return_dict=True,
185
+ labels=labels,
186
+ )
187
+ return mlm_output.loss
188
+ # mlm_output = self.transformer(input_ids,
189
+ # attention_mask = attn_mask,
190
+ # encoder_hidden_states = image_embeds,
191
+ # encoder_attention_mask = image_atts,
192
+ # return_dict = True,
193
+ # ).last_hidden_state
194
+ # logits = self.mlm_proj(mlm_output)
195
+
196
+ # # logits = logits[:, :-1, :].contiguous().view(-1, vocab_size)
197
+ # logits = logits[:, 1:, :].contiguous().view(-1, vocab_size)
198
+ # labels = labels[:, 1:].contiguous().view(-1)
199
+
200
+ # mlm_loss = F.cross_entropy(
201
+ # logits,
202
+ # labels,
203
+ # # label_smoothing=0.1,
204
+ # )
205
+ # return mlm_loss
206
+
207
+ def forward(self, x: TensorType) -> TensorType:
208
+ attn_mask = (x != self.config.pad_token_id).long()
209
+ out = self.transformer(input_ids=x, attention_mask=attn_mask)
210
+ pooled_out = self.pooler(out, attn_mask)
211
+
212
+ return self.proj(pooled_out)
213
+
214
+ def lock(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):
215
+ if not unlocked_layers: # full freezing
216
+ for n, p in self.transformer.named_parameters():
217
+ p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
218
+ return
219
+
220
+ encoder = self.transformer.encoder if hasattr(self.transformer, "encoder") else self.transformer
221
+ layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"])
222
+ print(f"Unlocking {unlocked_layers}/{len(layer_list) + 1} layers of hf model")
223
+ embeddings = getattr(self.transformer, arch_dict[self.config.model_type]["config_names"]["token_embeddings_attr"])
224
+ modules = [embeddings, *layer_list][:-unlocked_layers]
225
+ # freeze layers
226
+ for module in modules:
227
+ for n, p in module.named_parameters():
228
+ p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
229
+
230
+ @torch.jit.ignore
231
+ def set_grad_checkpointing(self, enable=True):
232
+ self.transformer.gradient_checkpointing_enable()
233
+
234
+ def get_num_layers(self):
235
+ encoder = self.transformer.encoder if hasattr(self.transformer, "encoder") else self.transformer
236
+ layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"])
237
+ return len(layer_list)
238
+
239
+ def init_parameters(self):
240
+ pass
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/loss.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+
6
+ try:
7
+ import torch.distributed.nn
8
+ from torch import distributed as dist
9
+
10
+ has_distributed = True
11
+ except ImportError:
12
+ has_distributed = False
13
+
14
+ try:
15
+ import horovod.torch as hvd
16
+ except ImportError:
17
+ hvd = None
18
+
19
+ from timm.loss import LabelSmoothingCrossEntropy
20
+
21
+
22
+ def gather_features(image_features, text_features, local_loss=False, gather_with_grad=False, rank=0, world_size=1, use_horovod=False):
23
+ assert has_distributed, "torch.distributed did not import correctly, please use a PyTorch version with support."
24
+ if use_horovod:
25
+ assert hvd is not None, "Please install horovod"
26
+ if gather_with_grad:
27
+ all_image_features = hvd.allgather(image_features)
28
+ all_text_features = hvd.allgather(text_features)
29
+ else:
30
+ with torch.no_grad():
31
+ all_image_features = hvd.allgather(image_features)
32
+ all_text_features = hvd.allgather(text_features)
33
+ if not local_loss:
34
+ # ensure grads for local rank when all_* features don't have a gradient
35
+ gathered_image_features = list(all_image_features.chunk(world_size, dim=0))
36
+ gathered_text_features = list(all_text_features.chunk(world_size, dim=0))
37
+ gathered_image_features[rank] = image_features
38
+ gathered_text_features[rank] = text_features
39
+ all_image_features = torch.cat(gathered_image_features, dim=0)
40
+ all_text_features = torch.cat(gathered_text_features, dim=0)
41
+ else:
42
+ # We gather tensors from all gpus
43
+ if gather_with_grad:
44
+ all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features), dim=0)
45
+ all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features), dim=0)
46
+ # all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features, async_op=True), dim=0)
47
+ # all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features, async_op=True), dim=0)
48
+ else:
49
+ gathered_image_features = [torch.zeros_like(image_features) for _ in range(world_size)]
50
+ gathered_text_features = [torch.zeros_like(text_features) for _ in range(world_size)]
51
+ dist.all_gather(gathered_image_features, image_features)
52
+ dist.all_gather(gathered_text_features, text_features)
53
+ if not local_loss:
54
+ # ensure grads for local rank when all_* features don't have a gradient
55
+ gathered_image_features[rank] = image_features
56
+ gathered_text_features[rank] = text_features
57
+ all_image_features = torch.cat(gathered_image_features, dim=0)
58
+ all_text_features = torch.cat(gathered_text_features, dim=0)
59
+
60
+ return all_image_features, all_text_features
61
+
62
+
63
+ class ClipLoss(nn.Module):
64
+
65
+ def __init__(
66
+ self,
67
+ local_loss=False,
68
+ gather_with_grad=False,
69
+ cache_labels=False,
70
+ rank=0,
71
+ world_size=1,
72
+ use_horovod=False,
73
+ smoothing=0.0,
74
+ ):
75
+ super().__init__()
76
+ self.local_loss = local_loss
77
+ self.gather_with_grad = gather_with_grad
78
+ self.cache_labels = cache_labels
79
+ self.rank = rank
80
+ self.world_size = world_size
81
+ self.use_horovod = use_horovod
82
+ self.label_smoothing_cross_entropy = LabelSmoothingCrossEntropy(smoothing=smoothing) if smoothing > 0 else None
83
+
84
+ # cache state
85
+ self.prev_num_logits = 0
86
+ self.labels = {}
87
+
88
+ def forward(self, image_features, text_features, logit_scale=1.0):
89
+ device = image_features.device
90
+ if self.world_size > 1:
91
+ all_image_features, all_text_features = gather_features(image_features, text_features, self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod)
92
+
93
+ if self.local_loss:
94
+ logits_per_image = logit_scale * image_features @ all_text_features.T
95
+ logits_per_text = logit_scale * text_features @ all_image_features.T
96
+ else:
97
+ logits_per_image = logit_scale * all_image_features @ all_text_features.T
98
+ logits_per_text = logits_per_image.T
99
+ else:
100
+ logits_per_image = logit_scale * image_features @ text_features.T
101
+ logits_per_text = logit_scale * text_features @ image_features.T
102
+ # calculated ground-truth and cache if enabled
103
+ num_logits = logits_per_image.shape[0]
104
+ if self.prev_num_logits != num_logits or device not in self.labels:
105
+ labels = torch.arange(num_logits, device=device, dtype=torch.long)
106
+ if self.world_size > 1 and self.local_loss:
107
+ labels = labels + num_logits * self.rank
108
+ if self.cache_labels:
109
+ self.labels[device] = labels
110
+ self.prev_num_logits = num_logits
111
+ else:
112
+ labels = self.labels[device]
113
+
114
+ if self.label_smoothing_cross_entropy:
115
+ total_loss = (self.label_smoothing_cross_entropy(logits_per_image, labels) + self.label_smoothing_cross_entropy(logits_per_text, labels)) / 2
116
+ else:
117
+ total_loss = (F.cross_entropy(logits_per_image, labels) + F.cross_entropy(logits_per_text, labels)) / 2
118
+
119
+ acc = None
120
+ i2t_acc = (logits_per_image.argmax(-1) == labels).sum() / len(logits_per_image)
121
+ t2i_acc = (logits_per_text.argmax(-1) == labels).sum() / len(logits_per_text)
122
+ acc = {"i2t": i2t_acc, "t2i": t2i_acc}
123
+ return total_loss, acc
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ CLIP Model
2
+
3
+ Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+
6
+ import os
7
+ from dataclasses import dataclass
8
+ from typing import Optional, Tuple, Union
9
+ from functools import partial
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch import nn
15
+
16
+ try:
17
+ from .hf_model import HFTextEncoder
18
+ except:
19
+ HFTextEncoder = None
20
+ from .modified_resnet import ModifiedResNet
21
+ from .timm_model import TimmModel
22
+ from .eva_vit_model import EVAVisionTransformer
23
+ from .transformer import LayerNorm, QuickGELU, Attention, VisionTransformer, TextTransformer
24
+
25
+ try:
26
+ from apex.normalization import FusedLayerNorm
27
+ except:
28
+ FusedLayerNorm = LayerNorm
29
+ # print("Please 'pip install apex'")
30
+
31
+ try:
32
+ import xformers.ops as xops
33
+ except ImportError:
34
+ xops = None
35
+ # print("Please 'pip install xformers'")
36
+
37
+
38
+ class RMSnorm(nn.Module):
39
+ """
40
+ adepted from transformers T5LayerNorm
41
+ """
42
+
43
+ def __init__(self, hidden_size, eps=1e-6):
44
+ """
45
+ Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
46
+ """
47
+ super().__init__()
48
+ self.weight = nn.Parameter(torch.ones(hidden_size))
49
+ self.variance_epsilon = eps
50
+
51
+ def forward(self, hidden_states):
52
+ # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
53
+ # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus varience is calculated
54
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
55
+ # half-precision inputs is done in fp32
56
+
57
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
58
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
59
+
60
+ # convert into half-precision if necessary
61
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
62
+ hidden_states = hidden_states.to(self.weight.dtype)
63
+
64
+ return self.weight * hidden_states
65
+
66
+
67
+ @dataclass
68
+ class CLIPVisionCfg:
69
+ layers: Union[Tuple[int, int, int, int], int] = 12
70
+ width: int = 768
71
+ head_width: int = 64
72
+ mlp_ratio: float = 4.0
73
+ patch_size: int = 16
74
+ image_size: Union[Tuple[int, int], int] = 224
75
+ ls_init_value: Optional[float] = None # layer scale initial value
76
+ patch_dropout: float = 0.0 # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results
77
+ global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580)
78
+ drop_path_rate: Optional[float] = None # drop path rate
79
+ timm_model_name: str = None # a valid model name overrides layers, width, patch_size
80
+ timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
81
+ timm_pool: str = "avg" # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
82
+ timm_proj: str = "linear" # linear projection for timm model output ('linear', 'mlp', '')
83
+ timm_proj_bias: bool = False # enable bias final projection
84
+ eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size
85
+ qkv_bias: bool = True
86
+ fusedLN: bool = False
87
+ xattn: bool = False
88
+ postnorm: bool = False
89
+ rope: bool = False
90
+ pt_hw_seq_len: int = 16 # 224/14
91
+ intp_freq: bool = False
92
+ naiveswiglu: bool = False
93
+ subln: bool = False
94
+ use_rms_norm: bool = False
95
+
96
+
97
+ @dataclass
98
+ class CLIPTextCfg:
99
+ context_length: int = 77
100
+ vocab_size: int = 49408
101
+ width: int = 512
102
+ heads: int = 8
103
+ layers: int = 12
104
+ ls_init_value: Optional[float] = None # layer scale initial value
105
+ hf_model_name: str = None
106
+ hf_tokenizer_name: str = None
107
+ hf_model_pretrained: bool = True
108
+ proj: str = "mlp"
109
+ pooler_type: str = "mean_pooler"
110
+ masked_language_modeling: bool = False
111
+ fusedLN: bool = False
112
+ xattn: bool = False
113
+ attn_mask: bool = True
114
+
115
+
116
+ def get_cast_dtype(precision: str):
117
+ cast_dtype = None
118
+ if precision == "bf16":
119
+ cast_dtype = torch.bfloat16
120
+ elif precision == "fp16":
121
+ cast_dtype = torch.float16
122
+ return cast_dtype
123
+
124
+
125
+ def _build_vision_tower(embed_dim: int, vision_cfg: CLIPVisionCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None):
126
+ if isinstance(vision_cfg, dict):
127
+ vision_cfg = CLIPVisionCfg(**vision_cfg)
128
+
129
+ # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more
130
+ # memory efficient in recent PyTorch releases (>= 1.10).
131
+ # NOTE: timm models always use native GELU regardless of quick_gelu flag.
132
+ act_layer = QuickGELU if quick_gelu else nn.GELU
133
+
134
+ if vision_cfg.eva_model_name:
135
+ vision_heads = vision_cfg.width // vision_cfg.head_width
136
+
137
+ norm_layer = RMSnorm if vision_cfg.use_rms_norm else LayerNorm
138
+
139
+ visual = EVAVisionTransformer(
140
+ img_size=vision_cfg.image_size,
141
+ patch_size=vision_cfg.patch_size,
142
+ num_classes=embed_dim,
143
+ use_mean_pooling=vision_cfg.global_average_pool, # False
144
+ init_values=vision_cfg.ls_init_value,
145
+ patch_dropout=vision_cfg.patch_dropout,
146
+ embed_dim=vision_cfg.width,
147
+ depth=vision_cfg.layers,
148
+ num_heads=vision_heads,
149
+ mlp_ratio=vision_cfg.mlp_ratio,
150
+ qkv_bias=vision_cfg.qkv_bias,
151
+ drop_path_rate=vision_cfg.drop_path_rate,
152
+ norm_layer=partial(norm_layer, eps=1e-6),
153
+ xattn=vision_cfg.xattn,
154
+ rope=vision_cfg.rope,
155
+ postnorm=vision_cfg.postnorm,
156
+ pt_hw_seq_len=vision_cfg.pt_hw_seq_len, # 224/14
157
+ intp_freq=vision_cfg.intp_freq,
158
+ naiveswiglu=vision_cfg.naiveswiglu,
159
+ subln=vision_cfg.subln,
160
+ )
161
+ elif vision_cfg.timm_model_name:
162
+ visual = TimmModel(
163
+ vision_cfg.timm_model_name, pretrained=vision_cfg.timm_model_pretrained, pool=vision_cfg.timm_pool, proj=vision_cfg.timm_proj, proj_bias=vision_cfg.timm_proj_bias, embed_dim=embed_dim, image_size=vision_cfg.image_size
164
+ )
165
+ act_layer = nn.GELU # so that text transformer doesn't use QuickGELU w/ timm models
166
+ elif isinstance(vision_cfg.layers, (tuple, list)):
167
+ vision_heads = vision_cfg.width * 32 // vision_cfg.head_width
168
+ visual = ModifiedResNet(layers=vision_cfg.layers, output_dim=embed_dim, heads=vision_heads, image_size=vision_cfg.image_size, width=vision_cfg.width)
169
+ else:
170
+ vision_heads = vision_cfg.width // vision_cfg.head_width
171
+ norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
172
+ visual = VisionTransformer(
173
+ image_size=vision_cfg.image_size,
174
+ patch_size=vision_cfg.patch_size,
175
+ width=vision_cfg.width,
176
+ layers=vision_cfg.layers,
177
+ heads=vision_heads,
178
+ mlp_ratio=vision_cfg.mlp_ratio,
179
+ ls_init_value=vision_cfg.ls_init_value,
180
+ patch_dropout=vision_cfg.patch_dropout,
181
+ global_average_pool=vision_cfg.global_average_pool,
182
+ output_dim=embed_dim,
183
+ act_layer=act_layer,
184
+ norm_layer=norm_layer,
185
+ )
186
+
187
+ return visual
188
+
189
+
190
+ def _build_text_tower(
191
+ embed_dim: int,
192
+ text_cfg: CLIPTextCfg,
193
+ quick_gelu: bool = False,
194
+ cast_dtype: Optional[torch.dtype] = None,
195
+ ):
196
+ if isinstance(text_cfg, dict):
197
+ text_cfg = CLIPTextCfg(**text_cfg)
198
+
199
+ if text_cfg.hf_model_name:
200
+ text = HFTextEncoder(text_cfg.hf_model_name, output_dim=embed_dim, tokenizer_name=text_cfg.hf_tokenizer_name, proj=text_cfg.proj, pooler_type=text_cfg.pooler_type, masked_language_modeling=text_cfg.masked_language_modeling)
201
+ else:
202
+ act_layer = QuickGELU if quick_gelu else nn.GELU
203
+ norm_layer = LayerNorm
204
+
205
+ text = TextTransformer(
206
+ context_length=text_cfg.context_length,
207
+ vocab_size=text_cfg.vocab_size,
208
+ width=text_cfg.width,
209
+ heads=text_cfg.heads,
210
+ layers=text_cfg.layers,
211
+ ls_init_value=text_cfg.ls_init_value,
212
+ output_dim=embed_dim,
213
+ act_layer=act_layer,
214
+ norm_layer=FusedLayerNorm if text_cfg.fusedLN else norm_layer,
215
+ xattn=text_cfg.xattn,
216
+ attn_mask=text_cfg.attn_mask,
217
+ )
218
+ return text
219
+
220
+
221
+ class CLIP(nn.Module):
222
+ def __init__(
223
+ self,
224
+ embed_dim: int,
225
+ vision_cfg: CLIPVisionCfg,
226
+ text_cfg: CLIPTextCfg,
227
+ quick_gelu: bool = False,
228
+ cast_dtype: Optional[torch.dtype] = None,
229
+ ):
230
+ super().__init__()
231
+ self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype)
232
+
233
+ text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype)
234
+ self.transformer = text.transformer
235
+ self.vocab_size = text.vocab_size
236
+ self.token_embedding = text.token_embedding
237
+ self.positional_embedding = text.positional_embedding
238
+ self.ln_final = text.ln_final
239
+ self.text_projection = text.text_projection
240
+ self.register_buffer("attn_mask", text.attn_mask, persistent=False)
241
+
242
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
243
+
244
+ def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False):
245
+ # lock image tower as per LiT - https://arxiv.org/abs/2111.07991
246
+ self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats)
247
+
248
+ @torch.jit.ignore
249
+ def set_grad_checkpointing(self, enable=True):
250
+ self.visual.set_grad_checkpointing(enable)
251
+ self.transformer.grad_checkpointing = enable
252
+
253
+ @torch.jit.ignore
254
+ def no_weight_decay(self):
255
+ return {"logit_scale"}
256
+
257
+ def encode_image(self, image, normalize: bool = False):
258
+ features = self.visual(image)
259
+ return F.normalize(features, dim=-1) if normalize else features
260
+
261
+ def encode_text(self, text, normalize: bool = False):
262
+ cast_dtype = self.transformer.get_cast_dtype()
263
+
264
+ x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
265
+
266
+ x = x + self.positional_embedding.to(cast_dtype)
267
+ x = x.permute(1, 0, 2) # NLD -> LND
268
+ x = self.transformer(x, attn_mask=self.attn_mask)
269
+ x = x.permute(1, 0, 2) # LND -> NLD
270
+ x = self.ln_final(x) # [batch_size, n_ctx, transformer.width]
271
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
272
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
273
+ return F.normalize(x, dim=-1) if normalize else x
274
+
275
+ def forward(self, image, text):
276
+ image_features = self.encode_image(image, normalize=True)
277
+ text_features = self.encode_text(text, normalize=True)
278
+ return image_features, text_features, self.logit_scale.exp()
279
+
280
+
281
+ class CustomCLIP(nn.Module):
282
+ def __init__(
283
+ self,
284
+ embed_dim: int,
285
+ vision_cfg: CLIPVisionCfg,
286
+ text_cfg: CLIPTextCfg,
287
+ quick_gelu: bool = False,
288
+ cast_dtype: Optional[torch.dtype] = None,
289
+ itm_task: bool = False,
290
+ ):
291
+ super().__init__()
292
+ self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype)
293
+ self.text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype)
294
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
295
+
296
+ def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False):
297
+ # lock image tower as per LiT - https://arxiv.org/abs/2111.07991
298
+ self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats)
299
+
300
+ def lock_text_tower(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):
301
+ self.text.lock(unlocked_layers, freeze_layer_norm)
302
+
303
+ @torch.jit.ignore
304
+ def set_grad_checkpointing(self, enable=True):
305
+ self.visual.set_grad_checkpointing(enable)
306
+ self.text.set_grad_checkpointing(enable)
307
+
308
+ @torch.jit.ignore
309
+ def no_weight_decay(self):
310
+ return {"logit_scale"}
311
+
312
+ def encode_image(self, image, normalize: bool = False):
313
+ features = self.visual(image)
314
+ return F.normalize(features, dim=-1) if normalize else features
315
+
316
+ def encode_text(self, text, normalize: bool = False):
317
+ features = self.text(text)
318
+ return F.normalize(features, dim=-1) if normalize else features
319
+
320
+ def forward(self, image, text):
321
+ image_features = self.encode_image(image, normalize=True)
322
+ text_features = self.encode_text(text, normalize=True)
323
+ return image_features, text_features, self.logit_scale.exp()
324
+
325
+
326
+ def convert_weights_to_lp(model: nn.Module, dtype=torch.float16):
327
+ """Convert applicable model parameters to low-precision (bf16 or fp16)"""
328
+
329
+ def _convert_weights(l):
330
+
331
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
332
+ l.weight.data = l.weight.data.to(dtype)
333
+ if l.bias is not None:
334
+ l.bias.data = l.bias.data.to(dtype)
335
+
336
+ if isinstance(l, (nn.MultiheadAttention, Attention)):
337
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
338
+ tensor = getattr(l, attr, None)
339
+ if tensor is not None:
340
+ tensor.data = tensor.data.to(dtype)
341
+
342
+ if isinstance(l, nn.Parameter):
343
+ l.data = l.data.to(dtype)
344
+
345
+ for name in ["text_projection", "proj"]:
346
+ if hasattr(l, name) and isinstance(l, nn.Parameter):
347
+ attr = getattr(l, name, None)
348
+ if attr is not None:
349
+ attr.data = attr.data.to(dtype)
350
+
351
+ model.apply(_convert_weights)
352
+
353
+
354
+ convert_weights_to_fp16 = convert_weights_to_lp # backwards compat
355
+
356
+
357
+ # used to maintain checkpoint compatibility
358
+ def convert_to_custom_text_state_dict(state_dict: dict):
359
+ if "text_projection" in state_dict:
360
+ # old format state_dict, move text tower -> .text
361
+ new_state_dict = {}
362
+ for k, v in state_dict.items():
363
+ if any(k.startswith(p) for p in ("text_projection", "positional_embedding", "token_embedding", "transformer", "ln_final", "logit_scale")):
364
+ k = "text." + k
365
+ new_state_dict[k] = v
366
+ return new_state_dict
367
+ return state_dict
368
+
369
+
370
+ def build_model_from_openai_state_dict(
371
+ state_dict: dict,
372
+ quick_gelu=True,
373
+ cast_dtype=torch.float16,
374
+ ):
375
+ vit = "visual.proj" in state_dict
376
+
377
+ if vit:
378
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
379
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
380
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
381
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
382
+ image_size = vision_patch_size * grid_size
383
+ else:
384
+ 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]]
385
+ vision_layers = tuple(counts)
386
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
387
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
388
+ vision_patch_size = None
389
+ assert output_width**2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
390
+ image_size = output_width * 32
391
+
392
+ embed_dim = state_dict["text_projection"].shape[1]
393
+ context_length = state_dict["positional_embedding"].shape[0]
394
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
395
+ transformer_width = state_dict["ln_final.weight"].shape[0]
396
+ transformer_heads = transformer_width // 64
397
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
398
+
399
+ vision_cfg = CLIPVisionCfg(
400
+ layers=vision_layers,
401
+ width=vision_width,
402
+ patch_size=vision_patch_size,
403
+ image_size=image_size,
404
+ )
405
+ text_cfg = CLIPTextCfg(context_length=context_length, vocab_size=vocab_size, width=transformer_width, heads=transformer_heads, layers=transformer_layers)
406
+ model = CLIP(
407
+ embed_dim,
408
+ vision_cfg=vision_cfg,
409
+ text_cfg=text_cfg,
410
+ quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU
411
+ cast_dtype=cast_dtype,
412
+ )
413
+
414
+ for key in ["input_resolution", "context_length", "vocab_size"]:
415
+ state_dict.pop(key, None)
416
+
417
+ convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16
418
+ model.load_state_dict(state_dict)
419
+ return model.eval()
420
+
421
+
422
+ def trace_model(model, batch_size=256, device=torch.device("cpu")):
423
+ model.eval()
424
+ image_size = model.visual.image_size
425
+ example_images = torch.ones((batch_size, 3, image_size, image_size), device=device)
426
+ example_text = torch.zeros((batch_size, model.context_length), dtype=torch.int, device=device)
427
+ model = torch.jit.trace_module(model, inputs=dict(forward=(example_images, example_text), encode_text=(example_text,), encode_image=(example_images,)))
428
+ model.visual.image_size = image_size
429
+ return model
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "patch_size": 16,
8
+ "eva_model_name": "eva-clip-b-16",
9
+ "ls_init_value": 0.1,
10
+ "drop_path_rate": 0.0
11
+ },
12
+ "text_cfg": {
13
+ "context_length": 77,
14
+ "vocab_size": 49408,
15
+ "width": 512,
16
+ "heads": 8,
17
+ "layers": 12
18
+ }
19
+ }
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-B-16.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "head_width": 64,
8
+ "patch_size": 16,
9
+ "mlp_ratio": 2.6667,
10
+ "eva_model_name": "eva-clip-b-16-X",
11
+ "drop_path_rate": 0.0,
12
+ "xattn": true,
13
+ "fusedLN": true,
14
+ "rope": true,
15
+ "pt_hw_seq_len": 16,
16
+ "intp_freq": true,
17
+ "naiveswiglu": true,
18
+ "subln": true
19
+ },
20
+ "text_cfg": {
21
+ "context_length": 77,
22
+ "vocab_size": 49408,
23
+ "width": 512,
24
+ "heads": 8,
25
+ "layers": 12,
26
+ "xattn": true,
27
+ "fusedLN": true
28
+ }
29
+ }
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 64,
6
+ "width": 1792,
7
+ "head_width": 112,
8
+ "mlp_ratio": 8.571428571428571,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-4b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": true,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1024,
20
+ "heads": 16,
21
+ "layers": 24,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 77,
6
+ "width": 2304,
7
+ "head_width": 144,
8
+ "mlp_ratio": 10.9722,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-10b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": false,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1280,
20
+ "heads": 20,
21
+ "layers": 32,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/modified_resnet.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ from .utils import freeze_batch_norm_2d
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.act1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.act2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.act3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([("-1", nn.AvgPool2d(stride)), ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), ("1", nn.BatchNorm2d(planes * self.expansion))]))
37
+
38
+ def forward(self, x: torch.Tensor):
39
+ identity = x
40
+
41
+ out = self.act1(self.bn1(self.conv1(x)))
42
+ out = self.act2(self.bn2(self.conv2(out)))
43
+ out = self.avgpool(out)
44
+ out = self.bn3(self.conv3(out))
45
+
46
+ if self.downsample is not None:
47
+ identity = self.downsample(x)
48
+
49
+ out += identity
50
+ out = self.act3(out)
51
+ return out
52
+
53
+
54
+ class AttentionPool2d(nn.Module):
55
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
56
+ super().__init__()
57
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim**2 + 1, embed_dim) / embed_dim**0.5)
58
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
59
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
60
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
61
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
62
+ self.num_heads = num_heads
63
+
64
+ def forward(self, x):
65
+ x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
66
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
67
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
68
+ x, _ = F.multi_head_attention_forward(
69
+ query=x,
70
+ key=x,
71
+ value=x,
72
+ embed_dim_to_check=x.shape[-1],
73
+ num_heads=self.num_heads,
74
+ q_proj_weight=self.q_proj.weight,
75
+ k_proj_weight=self.k_proj.weight,
76
+ v_proj_weight=self.v_proj.weight,
77
+ in_proj_weight=None,
78
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
79
+ bias_k=None,
80
+ bias_v=None,
81
+ add_zero_attn=False,
82
+ dropout_p=0.0,
83
+ out_proj_weight=self.c_proj.weight,
84
+ out_proj_bias=self.c_proj.bias,
85
+ use_separate_proj_weight=True,
86
+ training=self.training,
87
+ need_weights=False,
88
+ )
89
+
90
+ return x[0]
91
+
92
+
93
+ class ModifiedResNet(nn.Module):
94
+ """
95
+ A ResNet class that is similar to torchvision's but contains the following changes:
96
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
97
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
98
+ - The final pooling layer is a QKV attention instead of an average pool
99
+ """
100
+
101
+ def __init__(self, layers, output_dim, heads, image_size=224, width=64):
102
+ super().__init__()
103
+ self.output_dim = output_dim
104
+ self.image_size = image_size
105
+
106
+ # the 3-layer stem
107
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
108
+ self.bn1 = nn.BatchNorm2d(width // 2)
109
+ self.act1 = nn.ReLU(inplace=True)
110
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
111
+ self.bn2 = nn.BatchNorm2d(width // 2)
112
+ self.act2 = nn.ReLU(inplace=True)
113
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
114
+ self.bn3 = nn.BatchNorm2d(width)
115
+ self.act3 = nn.ReLU(inplace=True)
116
+ self.avgpool = nn.AvgPool2d(2)
117
+
118
+ # residual layers
119
+ self._inplanes = width # this is a *mutable* variable used during construction
120
+ self.layer1 = self._make_layer(width, layers[0])
121
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
122
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
123
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
124
+
125
+ embed_dim = width * 32 # the ResNet feature dimension
126
+ self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim)
127
+
128
+ self.init_parameters()
129
+
130
+ def _make_layer(self, planes, blocks, stride=1):
131
+ layers = [Bottleneck(self._inplanes, planes, stride)]
132
+
133
+ self._inplanes = planes * Bottleneck.expansion
134
+ for _ in range(1, blocks):
135
+ layers.append(Bottleneck(self._inplanes, planes))
136
+
137
+ return nn.Sequential(*layers)
138
+
139
+ def init_parameters(self):
140
+ if self.attnpool is not None:
141
+ std = self.attnpool.c_proj.in_features**-0.5
142
+ nn.init.normal_(self.attnpool.q_proj.weight, std=std)
143
+ nn.init.normal_(self.attnpool.k_proj.weight, std=std)
144
+ nn.init.normal_(self.attnpool.v_proj.weight, std=std)
145
+ nn.init.normal_(self.attnpool.c_proj.weight, std=std)
146
+
147
+ for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]:
148
+ for name, param in resnet_block.named_parameters():
149
+ if name.endswith("bn3.weight"):
150
+ nn.init.zeros_(param)
151
+
152
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
153
+ assert unlocked_groups == 0, "partial locking not currently supported for this model"
154
+ for param in self.parameters():
155
+ param.requires_grad = False
156
+ if freeze_bn_stats:
157
+ freeze_batch_norm_2d(self)
158
+
159
+ @torch.jit.ignore
160
+ def set_grad_checkpointing(self, enable=True):
161
+ # FIXME support for non-transformer
162
+ pass
163
+
164
+ def stem(self, x):
165
+ x = self.act1(self.bn1(self.conv1(x)))
166
+ x = self.act2(self.bn2(self.conv2(x)))
167
+ x = self.act3(self.bn3(self.conv3(x)))
168
+ x = self.avgpool(x)
169
+ return x
170
+
171
+ def forward(self, x):
172
+ x = self.stem(x)
173
+ x = self.layer1(x)
174
+ x = self.layer2(x)
175
+ x = self.layer3(x)
176
+ x = self.layer4(x)
177
+ x = self.attnpool(x)
178
+
179
+ return x
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/openai.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ OpenAI pretrained model functions
2
+
3
+ Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+
6
+ import os
7
+ import warnings
8
+ from typing import List, Optional, Union
9
+
10
+ import torch
11
+
12
+ from .model import build_model_from_openai_state_dict, convert_weights_to_lp, get_cast_dtype
13
+ from .pretrained import get_pretrained_url, list_pretrained_models_by_tag, download_pretrained_from_url
14
+
15
+ __all__ = ["list_openai_models", "load_openai_model"]
16
+
17
+
18
+ def list_openai_models() -> List[str]:
19
+ """Returns the names of available CLIP models"""
20
+ return list_pretrained_models_by_tag("openai")
21
+
22
+
23
+ def load_openai_model(
24
+ name: str,
25
+ precision: Optional[str] = None,
26
+ device: Optional[Union[str, torch.device]] = None,
27
+ jit: bool = True,
28
+ cache_dir: Optional[str] = None,
29
+ ):
30
+ """Load a CLIP model
31
+
32
+ Parameters
33
+ ----------
34
+ name : str
35
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
36
+ precision: str
37
+ Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'.
38
+ device : Union[str, torch.device]
39
+ The device to put the loaded model
40
+ jit : bool
41
+ Whether to load the optimized JIT model (default) or more hackable non-JIT model.
42
+ cache_dir : Optional[str]
43
+ The directory to cache the downloaded model weights
44
+
45
+ Returns
46
+ -------
47
+ model : torch.nn.Module
48
+ The CLIP model
49
+ preprocess : Callable[[PIL.Image], torch.Tensor]
50
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
51
+ """
52
+ if device is None:
53
+ device = "cuda" if torch.cuda.is_available() else "cpu"
54
+ if precision is None:
55
+ precision = "fp32" if device == "cpu" else "fp16"
56
+
57
+ if get_pretrained_url(name, "openai"):
58
+ model_path = download_pretrained_from_url(get_pretrained_url(name, "openai"), cache_dir=cache_dir)
59
+ elif os.path.isfile(name):
60
+ model_path = name
61
+ else:
62
+ raise RuntimeError(f"Model {name} not found; available models = {list_openai_models()}")
63
+
64
+ try:
65
+ # loading JIT archive
66
+ model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval()
67
+ state_dict = None
68
+ except RuntimeError:
69
+ # loading saved state dict
70
+ if jit:
71
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
72
+ jit = False
73
+ state_dict = torch.load(model_path, map_location="cpu")
74
+
75
+ if not jit:
76
+ # Build a non-jit model from the OpenAI jitted model state dict
77
+ cast_dtype = get_cast_dtype(precision)
78
+ try:
79
+ model = build_model_from_openai_state_dict(state_dict or model.state_dict(), cast_dtype=cast_dtype)
80
+ except KeyError:
81
+ sd = {k[7:]: v for k, v in state_dict["state_dict"].items()}
82
+ model = build_model_from_openai_state_dict(sd, cast_dtype=cast_dtype)
83
+
84
+ # model from OpenAI state dict is in manually cast fp16 mode, must be converted for AMP/fp32/bf16 use
85
+ model = model.to(device)
86
+ if precision.startswith("amp") or precision == "fp32":
87
+ model.float()
88
+ elif precision == "bf16":
89
+ convert_weights_to_lp(model, dtype=torch.bfloat16)
90
+
91
+ return model
92
+
93
+ # patch the device names
94
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
95
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
96
+
97
+ def patch_device(module):
98
+ try:
99
+ graphs = [module.graph] if hasattr(module, "graph") else []
100
+ except RuntimeError:
101
+ graphs = []
102
+
103
+ if hasattr(module, "forward1"):
104
+ graphs.append(module.forward1.graph)
105
+
106
+ for graph in graphs:
107
+ for node in graph.findAllNodes("prim::Constant"):
108
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
109
+ node.copyAttributes(device_node)
110
+
111
+ model.apply(patch_device)
112
+ patch_device(model.encode_image)
113
+ patch_device(model.encode_text)
114
+
115
+ # patch dtype to float32 (typically for CPU)
116
+ if precision == "fp32":
117
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
118
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
119
+ float_node = float_input.node()
120
+
121
+ def patch_float(module):
122
+ try:
123
+ graphs = [module.graph] if hasattr(module, "graph") else []
124
+ except RuntimeError:
125
+ graphs = []
126
+
127
+ if hasattr(module, "forward1"):
128
+ graphs.append(module.forward1.graph)
129
+
130
+ for graph in graphs:
131
+ for node in graph.findAllNodes("aten::to"):
132
+ inputs = list(node.inputs())
133
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
134
+ if inputs[i].node()["value"] == 5:
135
+ inputs[i].node().copyAttributes(float_node)
136
+
137
+ model.apply(patch_float)
138
+ patch_float(model.encode_image)
139
+ patch_float(model.encode_text)
140
+ model.float()
141
+
142
+ # ensure image_size attr available at consistent location for both jit and non-jit
143
+ model.visual.image_size = model.input_resolution.item()
144
+ return model
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/rope.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import pi
2
+ import torch
3
+ from torch import nn
4
+ from einops import rearrange, repeat
5
+ import logging
6
+
7
+
8
+ def broadcat(tensors, dim=-1):
9
+ num_tensors = len(tensors)
10
+ shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
11
+ assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
12
+ shape_len = list(shape_lens)[0]
13
+ dim = (dim + shape_len) if dim < 0 else dim
14
+ dims = list(zip(*map(lambda t: list(t.shape), tensors)))
15
+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
16
+ assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatentation"
17
+ max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
18
+ expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
19
+ expanded_dims.insert(dim, (dim, dims[dim]))
20
+ expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
21
+ tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
22
+ return torch.cat(tensors, dim=dim)
23
+
24
+
25
+ def rotate_half(x):
26
+ x = rearrange(x, "... (d r) -> ... d r", r=2)
27
+ x1, x2 = x.unbind(dim=-1)
28
+ x = torch.stack((-x2, x1), dim=-1)
29
+ return rearrange(x, "... d r -> ... (d r)")
30
+
31
+
32
+ class VisionRotaryEmbedding(nn.Module):
33
+ def __init__(
34
+ self,
35
+ dim,
36
+ pt_seq_len,
37
+ ft_seq_len=None,
38
+ custom_freqs=None,
39
+ freqs_for="lang",
40
+ theta=10000,
41
+ max_freq=10,
42
+ num_freqs=1,
43
+ ):
44
+ super().__init__()
45
+ if custom_freqs:
46
+ freqs = custom_freqs
47
+ elif freqs_for == "lang":
48
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
49
+ elif freqs_for == "pixel":
50
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
51
+ elif freqs_for == "constant":
52
+ freqs = torch.ones(num_freqs).float()
53
+ else:
54
+ raise ValueError(f"unknown modality {freqs_for}")
55
+
56
+ if ft_seq_len is None:
57
+ ft_seq_len = pt_seq_len
58
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
59
+
60
+ freqs_h = torch.einsum("..., f -> ... f", t, freqs)
61
+ freqs_h = repeat(freqs_h, "... n -> ... (n r)", r=2)
62
+
63
+ freqs_w = torch.einsum("..., f -> ... f", t, freqs)
64
+ freqs_w = repeat(freqs_w, "... n -> ... (n r)", r=2)
65
+
66
+ freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim=-1)
67
+
68
+ self.register_buffer("freqs_cos", freqs.cos())
69
+ self.register_buffer("freqs_sin", freqs.sin())
70
+
71
+ logging.info(f"Shape of rope freq: {self.freqs_cos.shape}")
72
+
73
+ def forward(self, t, start_index=0):
74
+ rot_dim = self.freqs_cos.shape[-1]
75
+ end_index = start_index + rot_dim
76
+ assert rot_dim <= t.shape[-1], f"feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}"
77
+ t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:]
78
+ t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin)
79
+
80
+ return torch.cat((t_left, t, t_right), dim=-1)
81
+
82
+
83
+ class VisionRotaryEmbeddingFast(nn.Module):
84
+ def __init__(self, dim, pt_seq_len, ft_seq_len=None, custom_freqs=None, freqs_for="lang", theta=10000, max_freq=10, num_freqs=1, patch_dropout=0.0):
85
+ super().__init__()
86
+ if custom_freqs:
87
+ freqs = custom_freqs
88
+ elif freqs_for == "lang":
89
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
90
+ elif freqs_for == "pixel":
91
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
92
+ elif freqs_for == "constant":
93
+ freqs = torch.ones(num_freqs).float()
94
+ else:
95
+ raise ValueError(f"unknown modality {freqs_for}")
96
+
97
+ if ft_seq_len is None:
98
+ ft_seq_len = pt_seq_len
99
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
100
+
101
+ freqs = torch.einsum("..., f -> ... f", t, freqs)
102
+ freqs = repeat(freqs, "... n -> ... (n r)", r=2)
103
+ freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
104
+
105
+ freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
106
+ freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
107
+
108
+ self.patch_dropout = patch_dropout
109
+
110
+ self.register_buffer("freqs_cos", freqs_cos)
111
+ self.register_buffer("freqs_sin", freqs_sin)
112
+
113
+ logging.info(f"Shape of rope freq: {self.freqs_cos.shape}")
114
+
115
+ def forward(self, t, patch_indices_keep=None):
116
+ if patch_indices_keep is not None:
117
+ batch = t.size()[0]
118
+ batch_indices = torch.arange(batch)
119
+ batch_indices = batch_indices[..., None]
120
+
121
+ freqs_cos = repeat(self.freqs_cos, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
122
+ freqs_sin = repeat(self.freqs_sin, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
123
+
124
+ freqs_cos = freqs_cos[batch_indices, patch_indices_keep]
125
+ freqs_cos = rearrange(freqs_cos, "n i m j -> n m i j")
126
+ freqs_sin = freqs_sin[batch_indices, patch_indices_keep]
127
+ freqs_sin = rearrange(freqs_sin, "n i m j -> n m i j")
128
+
129
+ return t * freqs_cos + rotate_half(t) * freqs_sin
130
+
131
+ return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/timm_model.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ timm model adapter
2
+
3
+ Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
4
+ """
5
+
6
+ import logging
7
+ from collections import OrderedDict
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ try:
13
+ import timm
14
+ from timm.models.layers import Mlp, to_2tuple
15
+
16
+ try:
17
+ # old timm imports < 0.8.1
18
+ from timm.models.layers.attention_pool2d import RotAttentionPool2d
19
+ from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d
20
+ except ImportError:
21
+ # new timm imports >= 0.8.1
22
+ from timm.layers import RotAttentionPool2d
23
+ from timm.layers import AttentionPool2d as AbsAttentionPool2d
24
+ except ImportError:
25
+ timm = None
26
+
27
+ from .utils import freeze_batch_norm_2d
28
+
29
+
30
+ class TimmModel(nn.Module):
31
+ """timm model adapter
32
+ # FIXME this adapter is a work in progress, may change in ways that break weight compat
33
+ """
34
+
35
+ def __init__(self, model_name, embed_dim, image_size=224, pool="avg", proj="linear", proj_bias=False, drop=0.0, pretrained=False):
36
+ super().__init__()
37
+ if timm is None:
38
+ raise RuntimeError("Please `pip install timm` to use timm models.")
39
+
40
+ self.image_size = to_2tuple(image_size)
41
+ self.trunk = timm.create_model(model_name, pretrained=pretrained)
42
+ feat_size = self.trunk.default_cfg.get("pool_size", None)
43
+ feature_ndim = 1 if not feat_size else 2
44
+ if pool in ("abs_attn", "rot_attn"):
45
+ assert feature_ndim == 2
46
+ # if attn pooling used, remove both classifier and default pool
47
+ self.trunk.reset_classifier(0, global_pool="")
48
+ else:
49
+ # reset global pool if pool config set, otherwise leave as network default
50
+ reset_kwargs = dict(global_pool=pool) if pool else {}
51
+ self.trunk.reset_classifier(0, **reset_kwargs)
52
+ prev_chs = self.trunk.num_features
53
+
54
+ head_layers = OrderedDict()
55
+ if pool == "abs_attn":
56
+ head_layers["pool"] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim)
57
+ prev_chs = embed_dim
58
+ elif pool == "rot_attn":
59
+ head_layers["pool"] = RotAttentionPool2d(prev_chs, out_features=embed_dim)
60
+ prev_chs = embed_dim
61
+ else:
62
+ assert proj, "projection layer needed if non-attention pooling is used."
63
+
64
+ # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used
65
+ if proj == "linear":
66
+ head_layers["drop"] = nn.Dropout(drop)
67
+ head_layers["proj"] = nn.Linear(prev_chs, embed_dim, bias=proj_bias)
68
+ elif proj == "mlp":
69
+ head_layers["mlp"] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=drop, bias=(True, proj_bias))
70
+
71
+ self.head = nn.Sequential(head_layers)
72
+
73
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
74
+ """lock modules
75
+ Args:
76
+ unlocked_groups (int): leave last n layer groups unlocked (default: 0)
77
+ """
78
+ if not unlocked_groups:
79
+ # lock full model
80
+ for param in self.trunk.parameters():
81
+ param.requires_grad = False
82
+ if freeze_bn_stats:
83
+ freeze_batch_norm_2d(self.trunk)
84
+ else:
85
+ # NOTE: partial freeze requires latest timm (master) branch and is subject to change
86
+ try:
87
+ # FIXME import here until API stable and in an official release
88
+ from timm.models.helpers import group_parameters, group_modules
89
+ except ImportError:
90
+ raise RuntimeError("Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`")
91
+ matcher = self.trunk.group_matcher()
92
+ gparams = group_parameters(self.trunk, matcher)
93
+ max_layer_id = max(gparams.keys())
94
+ max_layer_id = max_layer_id - unlocked_groups
95
+ for group_idx in range(max_layer_id + 1):
96
+ group = gparams[group_idx]
97
+ for param in group:
98
+ self.trunk.get_parameter(param).requires_grad = False
99
+ if freeze_bn_stats:
100
+ gmodules = group_modules(self.trunk, matcher, reverse=True)
101
+ gmodules = {k for k, v in gmodules.items() if v <= max_layer_id}
102
+ freeze_batch_norm_2d(self.trunk, gmodules)
103
+
104
+ @torch.jit.ignore
105
+ def set_grad_checkpointing(self, enable=True):
106
+ try:
107
+ self.trunk.set_grad_checkpointing(enable)
108
+ except Exception as e:
109
+ logging.warning("grad checkpointing not supported for this timm image tower, continuing without...")
110
+
111
+ def forward(self, x):
112
+ x = self.trunk(x)
113
+ x = self.head(x)
114
+ return x
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/tokenizer.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ CLIP tokenizer
2
+
3
+ Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+
6
+ import gzip
7
+ import html
8
+ import os
9
+ from functools import lru_cache
10
+ from typing import Union, List
11
+
12
+ import ftfy
13
+ import regex as re
14
+ import torch
15
+
16
+ # https://stackoverflow.com/q/62691279
17
+ import os
18
+
19
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
20
+
21
+
22
+ @lru_cache()
23
+ def default_bpe():
24
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
25
+
26
+
27
+ @lru_cache()
28
+ def bytes_to_unicode():
29
+ """
30
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
31
+ The reversible bpe codes work on unicode strings.
32
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
33
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
34
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
35
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
36
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
37
+ """
38
+ bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
39
+ cs = bs[:]
40
+ n = 0
41
+ for b in range(2**8):
42
+ if b not in bs:
43
+ bs.append(b)
44
+ cs.append(2**8 + n)
45
+ n += 1
46
+ cs = [chr(n) for n in cs]
47
+ return dict(zip(bs, cs))
48
+
49
+
50
+ def get_pairs(word):
51
+ """Return set of symbol pairs in a word.
52
+ Word is represented as tuple of symbols (symbols being variable-length strings).
53
+ """
54
+ pairs = set()
55
+ prev_char = word[0]
56
+ for char in word[1:]:
57
+ pairs.add((prev_char, char))
58
+ prev_char = char
59
+ return pairs
60
+
61
+
62
+ def basic_clean(text):
63
+ text = ftfy.fix_text(text)
64
+ text = html.unescape(html.unescape(text))
65
+ return text.strip()
66
+
67
+
68
+ def whitespace_clean(text):
69
+ text = re.sub(r"\s+", " ", text)
70
+ text = text.strip()
71
+ return text
72
+
73
+
74
+ class SimpleTokenizer(object):
75
+ def __init__(self, bpe_path: str = default_bpe(), special_tokens=None):
76
+ self.byte_encoder = bytes_to_unicode()
77
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
78
+ merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
79
+ merges = merges[1 : 49152 - 256 - 2 + 1]
80
+ merges = [tuple(merge.split()) for merge in merges]
81
+ vocab = list(bytes_to_unicode().values())
82
+ vocab = vocab + [v + "</w>" for v in vocab]
83
+ for merge in merges:
84
+ vocab.append("".join(merge))
85
+ if not special_tokens:
86
+ special_tokens = ["<start_of_text>", "<end_of_text>"]
87
+ else:
88
+ special_tokens = ["<start_of_text>", "<end_of_text>"] + special_tokens
89
+ vocab.extend(special_tokens)
90
+ self.encoder = dict(zip(vocab, range(len(vocab))))
91
+ self.decoder = {v: k for k, v in self.encoder.items()}
92
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
93
+ self.cache = {t: t for t in special_tokens}
94
+ special = "|".join(special_tokens)
95
+ self.pat = re.compile(special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
96
+
97
+ self.vocab_size = len(self.encoder)
98
+ self.all_special_ids = [self.encoder[t] for t in special_tokens]
99
+
100
+ def bpe(self, token):
101
+ if token in self.cache:
102
+ return self.cache[token]
103
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
104
+ pairs = get_pairs(word)
105
+
106
+ if not pairs:
107
+ return token + "</w>"
108
+
109
+ while True:
110
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
111
+ if bigram not in self.bpe_ranks:
112
+ break
113
+ first, second = bigram
114
+ new_word = []
115
+ i = 0
116
+ while i < len(word):
117
+ try:
118
+ j = word.index(first, i)
119
+ new_word.extend(word[i:j])
120
+ i = j
121
+ except:
122
+ new_word.extend(word[i:])
123
+ break
124
+
125
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
126
+ new_word.append(first + second)
127
+ i += 2
128
+ else:
129
+ new_word.append(word[i])
130
+ i += 1
131
+ new_word = tuple(new_word)
132
+ word = new_word
133
+ if len(word) == 1:
134
+ break
135
+ else:
136
+ pairs = get_pairs(word)
137
+ word = " ".join(word)
138
+ self.cache[token] = word
139
+ return word
140
+
141
+ def encode(self, text):
142
+ bpe_tokens = []
143
+ text = whitespace_clean(basic_clean(text)).lower()
144
+ for token in re.findall(self.pat, text):
145
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
146
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" "))
147
+ return bpe_tokens
148
+
149
+ def decode(self, tokens):
150
+ text = "".join([self.decoder[token] for token in tokens])
151
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="replace").replace("</w>", " ")
152
+ return text
153
+
154
+
155
+ _tokenizer = SimpleTokenizer()
156
+
157
+
158
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor:
159
+ """
160
+ Returns the tokenized representation of given input string(s)
161
+
162
+ Parameters
163
+ ----------
164
+ texts : Union[str, List[str]]
165
+ An input string or a list of input strings to tokenize
166
+ context_length : int
167
+ The context length to use; all CLIP models use 77 as the context length
168
+
169
+ Returns
170
+ -------
171
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
172
+ """
173
+ if isinstance(texts, str):
174
+ texts = [texts]
175
+
176
+ sot_token = _tokenizer.encoder["<start_of_text>"]
177
+ eot_token = _tokenizer.encoder["<end_of_text>"]
178
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
179
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
180
+
181
+ for i, tokens in enumerate(all_tokens):
182
+ if len(tokens) > context_length:
183
+ tokens = tokens[:context_length] # Truncate
184
+ tokens[-1] = eot_token
185
+ result[i, : len(tokens)] = torch.tensor(tokens)
186
+
187
+ return result
188
+
189
+
190
+ class HFTokenizer:
191
+ "HuggingFace tokenizer wrapper"
192
+
193
+ def __init__(self, tokenizer_name: str):
194
+ from transformers import AutoTokenizer
195
+
196
+ self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
197
+
198
+ def __call__(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.Tensor:
199
+ # same cleaning as for default tokenizer, except lowercasing
200
+ # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance
201
+ if isinstance(texts, str):
202
+ texts = [texts]
203
+ texts = [whitespace_clean(basic_clean(text)) for text in texts]
204
+ input_ids = self.tokenizer(texts, return_tensors="pt", max_length=context_length, padding="max_length", truncation=True).input_ids
205
+ return input_ids
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transform.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Sequence, Tuple
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torchvision.transforms.functional as F
6
+
7
+ from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, CenterCrop
8
+
9
+ from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
10
+
11
+
12
+ class ResizeMaxSize(nn.Module):
13
+
14
+ def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn="max", fill=0):
15
+ super().__init__()
16
+ if not isinstance(max_size, int):
17
+ raise TypeError(f"Size should be int. Got {type(max_size)}")
18
+ self.max_size = max_size
19
+ self.interpolation = interpolation
20
+ self.fn = min if fn == "min" else min
21
+ self.fill = fill
22
+
23
+ def forward(self, img):
24
+ if isinstance(img, torch.Tensor):
25
+ height, width = img.shape[:2]
26
+ else:
27
+ width, height = img.size
28
+ scale = self.max_size / float(max(height, width))
29
+ if scale != 1.0:
30
+ new_size = tuple(round(dim * scale) for dim in (height, width))
31
+ img = F.resize(img, new_size, self.interpolation)
32
+ pad_h = self.max_size - new_size[0]
33
+ pad_w = self.max_size - new_size[1]
34
+ img = F.pad(img, padding=[pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2], fill=self.fill)
35
+ return img
36
+
37
+
38
+ def _convert_to_rgb(image):
39
+ return image.convert("RGB")
40
+
41
+
42
+ # class CatGen(nn.Module):
43
+ # def __init__(self, num=4):
44
+ # self.num = num
45
+ # def mixgen_batch(image, text):
46
+ # batch_size = image.shape[0]
47
+ # index = np.random.permutation(batch_size)
48
+
49
+ # cat_images = []
50
+ # for i in range(batch_size):
51
+ # # image mixup
52
+ # image[i,:] = lam * image[i,:] + (1 - lam) * image[index[i],:]
53
+ # # text concat
54
+ # text[i] = tokenizer((str(text[i]) + " " + str(text[index[i]])))[0]
55
+ # text = torch.stack(text)
56
+ # return image, text
57
+
58
+
59
+ def image_transform(
60
+ image_size: int,
61
+ is_train: bool,
62
+ mean: Optional[Tuple[float, ...]] = None,
63
+ std: Optional[Tuple[float, ...]] = None,
64
+ resize_longest_max: bool = False,
65
+ fill_color: int = 0,
66
+ ):
67
+ mean = mean or OPENAI_DATASET_MEAN
68
+ if not isinstance(mean, (list, tuple)):
69
+ mean = (mean,) * 3
70
+
71
+ std = std or OPENAI_DATASET_STD
72
+ if not isinstance(std, (list, tuple)):
73
+ std = (std,) * 3
74
+
75
+ if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]:
76
+ # for square size, pass size as int so that Resize() uses aspect preserving shortest edge
77
+ image_size = image_size[0]
78
+
79
+ normalize = Normalize(mean=mean, std=std)
80
+ if is_train:
81
+ return Compose(
82
+ [
83
+ RandomResizedCrop(image_size, scale=(0.9, 1.0), interpolation=InterpolationMode.BICUBIC),
84
+ _convert_to_rgb,
85
+ ToTensor(),
86
+ normalize,
87
+ ]
88
+ )
89
+ else:
90
+ if resize_longest_max:
91
+ transforms = [ResizeMaxSize(image_size, fill=fill_color)]
92
+ else:
93
+ transforms = [
94
+ Resize(image_size, interpolation=InterpolationMode.BICUBIC),
95
+ CenterCrop(image_size),
96
+ ]
97
+ transforms.extend(
98
+ [
99
+ _convert_to_rgb,
100
+ ToTensor(),
101
+ normalize,
102
+ ]
103
+ )
104
+ return Compose(transforms)
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transformer.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from collections import OrderedDict
4
+ import math
5
+ from typing import Callable, Optional, Sequence
6
+ import numpy as np
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import functional as F
10
+
11
+ try:
12
+ from timm.models.layers import trunc_normal_
13
+ except:
14
+ from timm.layers import trunc_normal_
15
+
16
+ from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast
17
+ from .utils import to_2tuple
18
+
19
+ if os.getenv("ENV_TYPE") == "deepspeed":
20
+ try:
21
+ import deepspeed
22
+ from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
23
+ except:
24
+ print("Please 'pip install deepspeed'")
25
+ deepspeed = None
26
+ from torch.utils.checkpoint import checkpoint
27
+ else:
28
+ from torch.utils.checkpoint import checkpoint
29
+
30
+ try:
31
+ import xformers.ops as xops
32
+ except ImportError:
33
+ xops = None
34
+ # print("Please 'pip install xformers'")
35
+
36
+
37
+ class LayerNormFp32(nn.LayerNorm):
38
+ """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
39
+
40
+ def __init__(self, *args, **kwargs):
41
+ super().__init__(*args, **kwargs)
42
+
43
+ def forward(self, x: torch.Tensor):
44
+ output = F.layer_norm(
45
+ x.float(),
46
+ self.normalized_shape,
47
+ self.weight.float() if self.weight is not None else None,
48
+ self.bias.float() if self.bias is not None else None,
49
+ self.eps,
50
+ )
51
+ return output.type_as(x)
52
+
53
+
54
+ class LayerNorm(nn.LayerNorm):
55
+ """Subclass torch's LayerNorm (with cast back to input dtype)."""
56
+
57
+ def forward(self, x: torch.Tensor):
58
+ orig_type = x.dtype
59
+ x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
60
+ return x.to(orig_type)
61
+
62
+
63
+ class QuickGELU(nn.Module):
64
+ # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory
65
+ def forward(self, x: torch.Tensor):
66
+ return x * torch.sigmoid(1.702 * x)
67
+
68
+
69
+ class LayerScale(nn.Module):
70
+ def __init__(self, dim, init_values=1e-5, inplace=False):
71
+ super().__init__()
72
+ self.inplace = inplace
73
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
74
+
75
+ def forward(self, x):
76
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
77
+
78
+
79
+ class PatchDropout(nn.Module):
80
+ """
81
+ https://arxiv.org/abs/2212.00794
82
+ """
83
+
84
+ def __init__(self, prob, exclude_first_token=True):
85
+ super().__init__()
86
+ assert 0 <= prob < 1.0
87
+ self.prob = prob
88
+ self.exclude_first_token = exclude_first_token # exclude CLS token
89
+ logging.info(f"os.getenv('RoPE')={os.getenv('RoPE')}")
90
+
91
+ def forward(self, x):
92
+ if not self.training or self.prob == 0.0:
93
+ return x
94
+
95
+ if self.exclude_first_token:
96
+ cls_tokens, x = x[:, :1], x[:, 1:]
97
+ else:
98
+ cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
99
+
100
+ batch = x.size()[0]
101
+ num_tokens = x.size()[1]
102
+
103
+ batch_indices = torch.arange(batch)
104
+ batch_indices = batch_indices[..., None]
105
+
106
+ keep_prob = 1 - self.prob
107
+ num_patches_keep = max(1, int(num_tokens * keep_prob))
108
+
109
+ rand = torch.randn(batch, num_tokens)
110
+ patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
111
+
112
+ x = x[batch_indices, patch_indices_keep]
113
+
114
+ if self.exclude_first_token:
115
+ x = torch.cat((cls_tokens, x), dim=1)
116
+
117
+ if self.training and os.getenv("RoPE") == "1":
118
+ return x, patch_indices_keep
119
+
120
+ return x
121
+
122
+
123
+ def _in_projection_packed(
124
+ q: torch.Tensor,
125
+ k: torch.Tensor,
126
+ v: torch.Tensor,
127
+ w: torch.Tensor,
128
+ b: Optional[torch.Tensor] = None,
129
+ ):
130
+ """
131
+ https://github.com/pytorch/pytorch/blob/db2a237763eb8693a20788be94f8c192e762baa8/torch/nn/functional.py#L4726
132
+ """
133
+ E = q.size(-1)
134
+ if k is v:
135
+ if q is k:
136
+ # self-attention
137
+ return F.linear(q, w, b).chunk(3, dim=-1)
138
+ else:
139
+ # encoder-decoder attention
140
+ w_q, w_kv = w.split([E, E * 2])
141
+ if b is None:
142
+ b_q = b_kv = None
143
+ else:
144
+ b_q, b_kv = b.split([E, E * 2])
145
+ return (F.linear(q, w_q, b_q),) + F.linear(k, w_kv, b_kv).chunk(2, dim=-1)
146
+ else:
147
+ w_q, w_k, w_v = w.chunk(3)
148
+ if b is None:
149
+ b_q = b_k = b_v = None
150
+ else:
151
+ b_q, b_k, b_v = b.chunk(3)
152
+ return F.linear(q, w_q, b_q), F.linear(k, w_k, b_k), F.linear(v, w_v, b_v)
153
+
154
+
155
+ class Attention(nn.Module):
156
+ def __init__(self, dim, num_heads=8, qkv_bias=True, scaled_cosine=False, scale_heads=False, logit_scale_max=math.log(1.0 / 0.01), attn_drop=0.0, proj_drop=0.0, xattn=False, rope=False):
157
+ super().__init__()
158
+ self.scaled_cosine = scaled_cosine
159
+ self.scale_heads = scale_heads
160
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
161
+ self.num_heads = num_heads
162
+ self.head_dim = dim // num_heads
163
+ self.scale = self.head_dim**-0.5
164
+ self.logit_scale_max = logit_scale_max
165
+
166
+ # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
167
+ self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
168
+ if qkv_bias:
169
+ self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
170
+ else:
171
+ self.in_proj_bias = None
172
+
173
+ if self.scaled_cosine:
174
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
175
+ else:
176
+ self.logit_scale = None
177
+ self.attn_drop = nn.Dropout(attn_drop)
178
+ if self.scale_heads:
179
+ self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
180
+ else:
181
+ self.head_scale = None
182
+ self.out_proj = nn.Linear(dim, dim)
183
+ self.out_drop = nn.Dropout(proj_drop)
184
+ self.xattn = xattn
185
+ self.xattn_drop = attn_drop
186
+ self.rope = rope
187
+
188
+ def forward(self, x, attn_mask: Optional[torch.Tensor] = None):
189
+ L, N, C = x.shape
190
+ q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1)
191
+ if self.xattn:
192
+ q = q.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1)
193
+ k = k.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1)
194
+ v = v.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1)
195
+
196
+ x = xops.memory_efficient_attention(
197
+ q,
198
+ k,
199
+ v,
200
+ p=self.xattn_drop,
201
+ scale=self.scale if self.logit_scale is None else None,
202
+ attn_bias=xops.LowerTriangularMask() if attn_mask is not None else None,
203
+ )
204
+ else:
205
+ q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
206
+ k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
207
+ v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
208
+
209
+ if self.logit_scale is not None:
210
+ attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
211
+ logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
212
+ attn = attn.view(N, self.num_heads, L, L) * logit_scale
213
+ attn = attn.view(-1, L, L)
214
+ else:
215
+ q = q * self.scale
216
+ attn = torch.bmm(q, k.transpose(-1, -2))
217
+
218
+ if attn_mask is not None:
219
+ if attn_mask.dtype == torch.bool:
220
+ new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
221
+ new_attn_mask.masked_fill_(attn_mask, float("-inf"))
222
+ attn_mask = new_attn_mask
223
+ attn += attn_mask
224
+
225
+ attn = attn.softmax(dim=-1)
226
+ attn = self.attn_drop(attn)
227
+
228
+ x = torch.bmm(attn, v)
229
+
230
+ if self.head_scale is not None:
231
+ x = x.view(N, self.num_heads, L, C) * self.head_scale
232
+ x = x.view(-1, L, C)
233
+ x = x.transpose(0, 1).reshape(L, N, C)
234
+ x = self.out_proj(x)
235
+ x = self.out_drop(x)
236
+ return x
237
+
238
+
239
+ class CustomAttention(nn.Module):
240
+ def __init__(self, dim, num_heads=8, qkv_bias=True, scaled_cosine=True, scale_heads=False, logit_scale_max=math.log(1.0 / 0.01), attn_drop=0.0, proj_drop=0.0, xattn=False):
241
+ super().__init__()
242
+ self.scaled_cosine = scaled_cosine
243
+ self.scale_heads = scale_heads
244
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
245
+ self.num_heads = num_heads
246
+ self.head_dim = dim // num_heads
247
+ self.scale = self.head_dim**-0.5
248
+ self.logit_scale_max = logit_scale_max
249
+
250
+ # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
251
+ self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
252
+ if qkv_bias:
253
+ self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
254
+ else:
255
+ self.in_proj_bias = None
256
+
257
+ if self.scaled_cosine:
258
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
259
+ else:
260
+ self.logit_scale = None
261
+ self.attn_drop = nn.Dropout(attn_drop)
262
+ if self.scale_heads:
263
+ self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
264
+ else:
265
+ self.head_scale = None
266
+ self.out_proj = nn.Linear(dim, dim)
267
+ self.out_drop = nn.Dropout(proj_drop)
268
+ self.xattn = xattn
269
+ self.xattn_drop = attn_drop
270
+
271
+ def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
272
+ q, k, v = _in_projection_packed(query, key, value, self.in_proj_weight, self.in_proj_bias)
273
+ N_q, B_q, C_q = q.shape
274
+ N_k, B_k, C_k = k.shape
275
+ N_v, B_v, C_v = v.shape
276
+ if self.xattn:
277
+ # B, N, C -> B, N, num_heads, C
278
+ q = q.permute(1, 0, 2).reshape(B_q, N_q, self.num_heads, -1)
279
+ k = k.permute(1, 0, 2).reshape(B_k, N_k, self.num_heads, -1)
280
+ v = v.permute(1, 0, 2).reshape(B_v, N_v, self.num_heads, -1)
281
+
282
+ x = xops.memory_efficient_attention(q, k, v, p=self.xattn_drop, scale=self.scale if self.logit_scale is None else None, attn_bias=xops.LowerTriangularMask() if attn_mask is not None else None)
283
+ else:
284
+ # B*H, L, C
285
+ q = q.contiguous().view(N_q, B_q * self.num_heads, -1).transpose(0, 1)
286
+ k = k.contiguous().view(N_k, B_k * self.num_heads, -1).transpose(0, 1)
287
+ v = v.contiguous().view(N_v, B_v * self.num_heads, -1).transpose(0, 1)
288
+
289
+ if self.logit_scale is not None:
290
+ # B*H, N_q, N_k
291
+ attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
292
+ logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
293
+ attn = attn.view(B_q, self.num_heads, N_q, N_k) * logit_scale
294
+ attn = attn.view(-1, N_q, N_k)
295
+ else:
296
+ q = q * self.scale
297
+ attn = torch.bmm(q, k.transpose(-1, -2))
298
+
299
+ if attn_mask is not None:
300
+ if attn_mask.dtype == torch.bool:
301
+ new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
302
+ new_attn_mask.masked_fill_(attn_mask, float("-inf"))
303
+ attn_mask = new_attn_mask
304
+ attn += attn_mask
305
+
306
+ attn = attn.softmax(dim=-1)
307
+ attn = self.attn_drop(attn)
308
+
309
+ x = torch.bmm(attn, v)
310
+
311
+ if self.head_scale is not None:
312
+ x = x.view(B_q, self.num_heads, N_q, C_q) * self.head_scale
313
+ x = x.view(-1, N_q, C_q)
314
+ x = x.transpose(0, 1).reshape(N_q, B_q, C_q)
315
+ x = self.out_proj(x)
316
+ x = self.out_drop(x)
317
+ return x
318
+
319
+
320
+ class CustomResidualAttentionBlock(nn.Module):
321
+ def __init__(
322
+ self,
323
+ d_model: int,
324
+ n_head: int,
325
+ mlp_ratio: float = 4.0,
326
+ ls_init_value: float = None,
327
+ act_layer: Callable = nn.GELU,
328
+ norm_layer: Callable = LayerNorm,
329
+ scale_cosine_attn: bool = False,
330
+ scale_heads: bool = False,
331
+ scale_attn: bool = False,
332
+ scale_fc: bool = False,
333
+ cross_attn: bool = False,
334
+ xattn: bool = False,
335
+ ):
336
+ super().__init__()
337
+
338
+ self.ln_1 = norm_layer(d_model)
339
+ self.ln_1_k = norm_layer(d_model) if cross_attn else self.ln_1
340
+ self.ln_1_v = norm_layer(d_model) if cross_attn else self.ln_1
341
+ self.attn = CustomAttention(d_model, n_head, qkv_bias=True, attn_drop=0.0, proj_drop=0.0, scaled_cosine=scale_cosine_attn, scale_heads=scale_heads, xattn=xattn)
342
+
343
+ self.ln_attn = norm_layer(d_model) if scale_attn else nn.Identity()
344
+ self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
345
+
346
+ self.ln_2 = norm_layer(d_model)
347
+ mlp_width = int(d_model * mlp_ratio)
348
+ self.mlp = nn.Sequential(OrderedDict([("c_fc", nn.Linear(d_model, mlp_width)), ("ln", norm_layer(mlp_width) if scale_fc else nn.Identity()), ("gelu", act_layer()), ("c_proj", nn.Linear(mlp_width, d_model))]))
349
+
350
+ self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
351
+
352
+ def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
353
+ q = q + self.ls_1(self.ln_attn(self.attn(self.ln_1(q), self.ln_1_k(k), self.ln_1_v(v), attn_mask=attn_mask)))
354
+ q = q + self.ls_2(self.mlp(self.ln_2(q)))
355
+ return q
356
+
357
+
358
+ class CustomTransformer(nn.Module):
359
+ def __init__(
360
+ self,
361
+ width: int,
362
+ layers: int,
363
+ heads: int,
364
+ mlp_ratio: float = 4.0,
365
+ ls_init_value: float = None,
366
+ act_layer: Callable = nn.GELU,
367
+ norm_layer: Callable = LayerNorm,
368
+ scale_cosine_attn: bool = True,
369
+ scale_heads: bool = False,
370
+ scale_attn: bool = False,
371
+ scale_fc: bool = False,
372
+ cross_attn: bool = False,
373
+ xattn: bool = False,
374
+ ):
375
+ super().__init__()
376
+ self.width = width
377
+ self.layers = layers
378
+ self.grad_checkpointing = False
379
+ self.xattn = xattn
380
+
381
+ self.resblocks = nn.ModuleList(
382
+ [
383
+ CustomResidualAttentionBlock(
384
+ width,
385
+ heads,
386
+ mlp_ratio,
387
+ ls_init_value=ls_init_value,
388
+ act_layer=act_layer,
389
+ norm_layer=norm_layer,
390
+ scale_cosine_attn=scale_cosine_attn,
391
+ scale_heads=scale_heads,
392
+ scale_attn=scale_attn,
393
+ scale_fc=scale_fc,
394
+ cross_attn=cross_attn,
395
+ xattn=xattn,
396
+ )
397
+ for _ in range(layers)
398
+ ]
399
+ )
400
+
401
+ def get_cast_dtype(self) -> torch.dtype:
402
+ return self.resblocks[0].mlp.c_fc.weight.dtype
403
+
404
+ def forward(self, q: torch.Tensor, k: torch.Tensor = None, v: torch.Tensor = None, attn_mask: Optional[torch.Tensor] = None):
405
+ if k is None and v is None:
406
+ k = v = q
407
+ for r in self.resblocks:
408
+ if self.grad_checkpointing and not torch.jit.is_scripting():
409
+ q = checkpoint(r, q, k, v, attn_mask)
410
+ else:
411
+ q = r(q, k, v, attn_mask=attn_mask)
412
+ return q
413
+
414
+
415
+ class ResidualAttentionBlock(nn.Module):
416
+ def __init__(
417
+ self,
418
+ d_model: int,
419
+ n_head: int,
420
+ mlp_ratio: float = 4.0,
421
+ ls_init_value: float = None,
422
+ act_layer: Callable = nn.GELU,
423
+ norm_layer: Callable = LayerNorm,
424
+ xattn: bool = False,
425
+ ):
426
+ super().__init__()
427
+
428
+ self.ln_1 = norm_layer(d_model)
429
+ if xattn:
430
+ self.attn = Attention(d_model, n_head, xattn=True)
431
+ else:
432
+ self.attn = nn.MultiheadAttention(d_model, n_head)
433
+ self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
434
+
435
+ self.ln_2 = norm_layer(d_model)
436
+ mlp_width = int(d_model * mlp_ratio)
437
+ self.mlp = nn.Sequential(OrderedDict([("c_fc", nn.Linear(d_model, mlp_width)), ("gelu", act_layer()), ("c_proj", nn.Linear(mlp_width, d_model))]))
438
+
439
+ self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
440
+ self.xattn = xattn
441
+
442
+ def attention(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
443
+ attn_mask = attn_mask.to(x.dtype) if attn_mask is not None else None
444
+ if self.xattn:
445
+ return self.attn(x, attn_mask=attn_mask)
446
+ return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
447
+
448
+ def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
449
+ x = x + self.ls_1(self.attention(self.ln_1(x), attn_mask=attn_mask))
450
+ x = x + self.ls_2(self.mlp(self.ln_2(x)))
451
+ return x
452
+
453
+
454
+ class Transformer(nn.Module):
455
+ def __init__(
456
+ self,
457
+ width: int,
458
+ layers: int,
459
+ heads: int,
460
+ mlp_ratio: float = 4.0,
461
+ ls_init_value: float = None,
462
+ act_layer: Callable = nn.GELU,
463
+ norm_layer: Callable = LayerNorm,
464
+ xattn: bool = False,
465
+ ):
466
+ super().__init__()
467
+ self.width = width
468
+ self.layers = layers
469
+ self.grad_checkpointing = False
470
+
471
+ self.resblocks = nn.ModuleList([ResidualAttentionBlock(width, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer, xattn=xattn) for _ in range(layers)])
472
+
473
+ def get_cast_dtype(self) -> torch.dtype:
474
+ return self.resblocks[0].mlp.c_fc.weight.dtype
475
+
476
+ def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
477
+ for r in self.resblocks:
478
+ if self.grad_checkpointing and not torch.jit.is_scripting():
479
+ x = checkpoint(r, x, attn_mask)
480
+ else:
481
+ x = r(x, attn_mask=attn_mask)
482
+ return x
483
+
484
+
485
+ class VisionTransformer(nn.Module):
486
+ def __init__(
487
+ self,
488
+ image_size: int,
489
+ patch_size: int,
490
+ width: int,
491
+ layers: int,
492
+ heads: int,
493
+ mlp_ratio: float,
494
+ ls_init_value: float = None,
495
+ patch_dropout: float = 0.0,
496
+ global_average_pool: bool = False,
497
+ output_dim: int = 512,
498
+ act_layer: Callable = nn.GELU,
499
+ norm_layer: Callable = LayerNorm,
500
+ xattn: bool = False,
501
+ ):
502
+ super().__init__()
503
+ self.image_size = to_2tuple(image_size)
504
+ self.patch_size = to_2tuple(patch_size)
505
+ self.grid_size = (self.image_size[0] // self.patch_size[0], self.image_size[1] // self.patch_size[1])
506
+ self.output_dim = output_dim
507
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
508
+
509
+ scale = width**-0.5
510
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
511
+ self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width))
512
+
513
+ # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
514
+ self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity()
515
+ self.ln_pre = norm_layer(width)
516
+
517
+ self.transformer = Transformer(width, layers, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer, xattn=xattn)
518
+
519
+ self.global_average_pool = global_average_pool
520
+ self.ln_post = norm_layer(width)
521
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
522
+
523
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
524
+ for param in self.parameters():
525
+ param.requires_grad = False
526
+
527
+ if unlocked_groups != 0:
528
+ groups = [
529
+ [
530
+ self.conv1,
531
+ self.class_embedding,
532
+ self.positional_embedding,
533
+ self.ln_pre,
534
+ ],
535
+ *self.transformer.resblocks[:-1],
536
+ [
537
+ self.transformer.resblocks[-1],
538
+ self.ln_post,
539
+ ],
540
+ self.proj,
541
+ ]
542
+
543
+ def _unlock(x):
544
+ if isinstance(x, Sequence):
545
+ for g in x:
546
+ _unlock(g)
547
+ else:
548
+ if isinstance(x, torch.nn.Parameter):
549
+ x.requires_grad = True
550
+ else:
551
+ for p in x.parameters():
552
+ p.requires_grad = True
553
+
554
+ _unlock(groups[-unlocked_groups:])
555
+
556
+ def get_num_layers(self):
557
+ return self.transformer.layers
558
+
559
+ @torch.jit.ignore
560
+ def set_grad_checkpointing(self, enable=True):
561
+ self.transformer.grad_checkpointing = enable
562
+
563
+ @torch.jit.ignore
564
+ def no_weight_decay(self):
565
+ return {"positional_embedding", "class_embedding"}
566
+
567
+ def forward(self, x: torch.Tensor, return_all_features: bool = False):
568
+ x = self.conv1(x) # shape = [*, width, grid, grid]
569
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
570
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
571
+ 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]
572
+ x = x + self.positional_embedding.to(x.dtype)
573
+
574
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
575
+ x = self.patch_dropout(x)
576
+ x = self.ln_pre(x)
577
+
578
+ x = x.permute(1, 0, 2) # NLD -> LND
579
+ x = self.transformer(x)
580
+ x = x.permute(1, 0, 2) # LND -> NLD
581
+
582
+ if not return_all_features:
583
+ if self.global_average_pool:
584
+ x = x.mean(dim=1) # x = x[:,1:,:].mean(dim=1)
585
+ else:
586
+ x = x[:, 0]
587
+
588
+ x = self.ln_post(x)
589
+
590
+ if self.proj is not None:
591
+ x = x @ self.proj
592
+
593
+ return x
594
+
595
+
596
+ class TextTransformer(nn.Module):
597
+ def __init__(
598
+ self,
599
+ context_length: int = 77,
600
+ vocab_size: int = 49408,
601
+ width: int = 512,
602
+ heads: int = 8,
603
+ layers: int = 12,
604
+ ls_init_value: float = None,
605
+ output_dim: int = 512,
606
+ act_layer: Callable = nn.GELU,
607
+ norm_layer: Callable = LayerNorm,
608
+ xattn: bool = False,
609
+ attn_mask: bool = True,
610
+ ):
611
+ super().__init__()
612
+ self.context_length = context_length
613
+ self.vocab_size = vocab_size
614
+ self.width = width
615
+ self.output_dim = output_dim
616
+
617
+ self.token_embedding = nn.Embedding(vocab_size, width)
618
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, width))
619
+ self.transformer = Transformer(width=width, layers=layers, heads=heads, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer, xattn=xattn)
620
+
621
+ self.xattn = xattn
622
+ self.ln_final = norm_layer(width)
623
+ self.text_projection = nn.Parameter(torch.empty(width, output_dim))
624
+
625
+ if attn_mask:
626
+ self.register_buffer("attn_mask", self.build_attention_mask(), persistent=False)
627
+ else:
628
+ self.attn_mask = None
629
+
630
+ self.init_parameters()
631
+
632
+ def init_parameters(self):
633
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
634
+ nn.init.normal_(self.positional_embedding, std=0.01)
635
+
636
+ proj_std = (self.transformer.width**-0.5) * ((2 * self.transformer.layers) ** -0.5)
637
+ attn_std = self.transformer.width**-0.5
638
+ fc_std = (2 * self.transformer.width) ** -0.5
639
+ for block in self.transformer.resblocks:
640
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
641
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
642
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
643
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
644
+
645
+ if self.text_projection is not None:
646
+ nn.init.normal_(self.text_projection, std=self.transformer.width**-0.5)
647
+
648
+ @torch.jit.ignore
649
+ def set_grad_checkpointing(self, enable=True):
650
+ self.transformer.grad_checkpointing = enable
651
+
652
+ @torch.jit.ignore
653
+ def no_weight_decay(self):
654
+ # return {'positional_embedding', 'token_embedding'}
655
+ return {"positional_embedding"}
656
+
657
+ def get_num_layers(self):
658
+ return self.transformer.layers
659
+
660
+ def build_attention_mask(self):
661
+ # lazily create causal attention mask, with full attention between the vision tokens
662
+ # pytorch uses additive attention mask; fill with -inf
663
+ mask = torch.empty(self.context_length, self.context_length)
664
+ mask.fill_(float("-inf"))
665
+ mask.triu_(1) # zero out the lower diagonal
666
+ return mask
667
+
668
+ def forward(self, text, return_all_features: bool = False):
669
+ cast_dtype = self.transformer.get_cast_dtype()
670
+ x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
671
+
672
+ x = x + self.positional_embedding.to(cast_dtype)
673
+ x = x.permute(1, 0, 2) # NLD -> LND
674
+ x = self.transformer(x, attn_mask=self.attn_mask)
675
+ # x = self.transformer(x) # no attention mask is applied
676
+ x = x.permute(1, 0, 2) # LND -> NLD
677
+ x = self.ln_final(x)
678
+
679
+ if not return_all_features:
680
+ # x.shape = [batch_size, n_ctx, transformer.width]
681
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
682
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
683
+ return x
之前的代码版本/注意力关键词用于sam的/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/utils.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import repeat
2
+ import collections.abc
3
+ import logging
4
+ import math
5
+ import numpy as np
6
+
7
+ import torch
8
+ from torch import nn as nn
9
+ from torchvision.ops.misc import FrozenBatchNorm2d
10
+ import torch.nn.functional as F
11
+
12
+
13
+ # open CLIP
14
+ def resize_clip_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
15
+ # Rescale the grid of position embeddings when loading from state_dict
16
+ old_pos_embed = state_dict.get("visual.positional_embedding", None)
17
+ if old_pos_embed is None or not hasattr(model.visual, "grid_size"):
18
+ return
19
+ grid_size = to_2tuple(model.visual.grid_size)
20
+ extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
21
+ new_seq_len = grid_size[0] * grid_size[1] + extra_tokens
22
+ if new_seq_len == old_pos_embed.shape[0]:
23
+ return
24
+
25
+ if extra_tokens:
26
+ pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:]
27
+ else:
28
+ pos_emb_tok, pos_emb_img = None, old_pos_embed
29
+ old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img))))
30
+
31
+ logging.info("Resizing position embedding grid-size from %s to %s", old_grid_size, grid_size)
32
+ pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2)
33
+ pos_emb_img = F.interpolate(
34
+ pos_emb_img,
35
+ size=grid_size,
36
+ mode=interpolation,
37
+ align_corners=True,
38
+ )
39
+ pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0]
40
+ if pos_emb_tok is not None:
41
+ new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0)
42
+ else:
43
+ new_pos_embed = pos_emb_img
44
+ state_dict["visual.positional_embedding"] = new_pos_embed
45
+
46
+
47
+ def resize_visual_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
48
+ # Rescale the grid of position embeddings when loading from state_dict
49
+ old_pos_embed = state_dict.get("positional_embedding", None)
50
+ if old_pos_embed is None or not hasattr(model.visual, "grid_size"):
51
+ return
52
+ grid_size = to_2tuple(model.visual.grid_size)
53
+ extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
54
+ new_seq_len = grid_size[0] * grid_size[1] + extra_tokens
55
+ if new_seq_len == old_pos_embed.shape[0]:
56
+ return
57
+
58
+ if extra_tokens:
59
+ pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:]
60
+ else:
61
+ pos_emb_tok, pos_emb_img = None, old_pos_embed
62
+ old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img))))
63
+
64
+ logging.info("Resizing position embedding grid-size from %s to %s", old_grid_size, grid_size)
65
+ pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2)
66
+ pos_emb_img = F.interpolate(
67
+ pos_emb_img,
68
+ size=grid_size,
69
+ mode=interpolation,
70
+ align_corners=True,
71
+ )
72
+ pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0]
73
+ if pos_emb_tok is not None:
74
+ new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0)
75
+ else:
76
+ new_pos_embed = pos_emb_img
77
+ state_dict["positional_embedding"] = new_pos_embed
78
+
79
+
80
+ def resize_evaclip_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
81
+ all_keys = list(state_dict.keys())
82
+ # interpolate position embedding
83
+ if "visual.pos_embed" in state_dict:
84
+ pos_embed_checkpoint = state_dict["visual.pos_embed"]
85
+ embedding_size = pos_embed_checkpoint.shape[-1]
86
+ num_patches = model.visual.patch_embed.num_patches
87
+ # num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches
88
+ num_extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
89
+ # height (== width) for the checkpoint position embedding
90
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
91
+ # height (== width) for the new position embedding
92
+ new_size = int(num_patches**0.5)
93
+ # class_token and dist_token are kept unchanged
94
+ if orig_size != new_size:
95
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
96
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
97
+ # only the position tokens are interpolated
98
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
99
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
100
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False)
101
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
102
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
103
+ state_dict["visual.pos_embed"] = new_pos_embed
104
+
105
+ patch_embed_proj = state_dict["visual.patch_embed.proj.weight"]
106
+ patch_size = model.visual.patch_embed.patch_size
107
+ state_dict["visual.patch_embed.proj.weight"] = torch.nn.functional.interpolate(patch_embed_proj.float(), size=patch_size, mode="bicubic", align_corners=False)
108
+
109
+
110
+ def resize_eva_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
111
+ all_keys = list(state_dict.keys())
112
+ # interpolate position embedding
113
+ if "pos_embed" in state_dict:
114
+ pos_embed_checkpoint = state_dict["pos_embed"]
115
+ embedding_size = pos_embed_checkpoint.shape[-1]
116
+ num_patches = model.visual.patch_embed.num_patches
117
+ # num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches
118
+ num_extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
119
+ # height (== width) for the checkpoint position embedding
120
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
121
+ # height (== width) for the new position embedding
122
+ new_size = int(num_patches**0.5)
123
+ # class_token and dist_token are kept unchanged
124
+ if orig_size != new_size:
125
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
126
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
127
+ # only the position tokens are interpolated
128
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
129
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
130
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False)
131
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
132
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
133
+ state_dict["pos_embed"] = new_pos_embed
134
+
135
+ patch_embed_proj = state_dict["patch_embed.proj.weight"]
136
+ patch_size = model.visual.patch_embed.patch_size
137
+ state_dict["patch_embed.proj.weight"] = torch.nn.functional.interpolate(patch_embed_proj.float(), size=patch_size, mode="bicubic", align_corners=False)
138
+
139
+
140
+ def resize_rel_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
141
+ all_keys = list(state_dict.keys())
142
+ for key in all_keys:
143
+ if "relative_position_index" in key:
144
+ state_dict.pop(key)
145
+
146
+ if "relative_position_bias_table" in key:
147
+ rel_pos_bias = state_dict[key]
148
+ src_num_pos, num_attn_heads = rel_pos_bias.size()
149
+ dst_num_pos, _ = model.visual.state_dict()[key].size()
150
+ dst_patch_shape = model.visual.patch_embed.patch_shape
151
+ if dst_patch_shape[0] != dst_patch_shape[1]:
152
+ raise NotImplementedError()
153
+ num_extra_tokens = dst_num_pos - (dst_patch_shape[0] * 2 - 1) * (dst_patch_shape[1] * 2 - 1)
154
+ src_size = int((src_num_pos - num_extra_tokens) ** 0.5)
155
+ dst_size = int((dst_num_pos - num_extra_tokens) ** 0.5)
156
+ if src_size != dst_size:
157
+ print("Position interpolate for %s from %dx%d to %dx%d" % (key, src_size, src_size, dst_size, dst_size))
158
+ extra_tokens = rel_pos_bias[-num_extra_tokens:, :]
159
+ rel_pos_bias = rel_pos_bias[:-num_extra_tokens, :]
160
+
161
+ def geometric_progression(a, r, n):
162
+ return a * (1.0 - r**n) / (1.0 - r)
163
+
164
+ left, right = 1.01, 1.5
165
+ while right - left > 1e-6:
166
+ q = (left + right) / 2.0
167
+ gp = geometric_progression(1, q, src_size // 2)
168
+ if gp > dst_size // 2:
169
+ right = q
170
+ else:
171
+ left = q
172
+
173
+ # if q > 1.090307:
174
+ # q = 1.090307
175
+
176
+ dis = []
177
+ cur = 1
178
+ for i in range(src_size // 2):
179
+ dis.append(cur)
180
+ cur += q ** (i + 1)
181
+
182
+ r_ids = [-_ for _ in reversed(dis)]
183
+
184
+ x = r_ids + [0] + dis
185
+ y = r_ids + [0] + dis
186
+
187
+ t = dst_size // 2.0
188
+ dx = np.arange(-t, t + 0.1, 1.0)
189
+ dy = np.arange(-t, t + 0.1, 1.0)
190
+
191
+ print("Original positions = %s" % str(x))
192
+ print("Target positions = %s" % str(dx))
193
+
194
+ all_rel_pos_bias = []
195
+
196
+ for i in range(num_attn_heads):
197
+ z = rel_pos_bias[:, i].view(src_size, src_size).float().numpy()
198
+ f = F.interpolate.interp2d(x, y, z, kind="cubic")
199
+ all_rel_pos_bias.append(torch.Tensor(f(dx, dy)).contiguous().view(-1, 1).to(rel_pos_bias.device))
200
+
201
+ rel_pos_bias = torch.cat(all_rel_pos_bias, dim=-1)
202
+
203
+ new_rel_pos_bias = torch.cat((rel_pos_bias, extra_tokens), dim=0)
204
+ state_dict[key] = new_rel_pos_bias
205
+
206
+ # interpolate position embedding
207
+ if "pos_embed" in state_dict:
208
+ pos_embed_checkpoint = state_dict["pos_embed"]
209
+ embedding_size = pos_embed_checkpoint.shape[-1]
210
+ num_patches = model.visual.patch_embed.num_patches
211
+ num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches
212
+ # height (== width) for the checkpoint position embedding
213
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
214
+ # height (== width) for the new position embedding
215
+ new_size = int(num_patches**0.5)
216
+ # class_token and dist_token are kept unchanged
217
+ if orig_size != new_size:
218
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
219
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
220
+ # only the position tokens are interpolated
221
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
222
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
223
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False)
224
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
225
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
226
+ state_dict["pos_embed"] = new_pos_embed
227
+
228
+ patch_embed_proj = state_dict["patch_embed.proj.weight"]
229
+ patch_size = model.visual.patch_embed.patch_size
230
+ state_dict["patch_embed.proj.weight"] = torch.nn.functional.interpolate(patch_embed_proj.float(), size=patch_size, mode="bicubic", align_corners=False)
231
+
232
+
233
+ def freeze_batch_norm_2d(module, module_match={}, name=""):
234
+ """
235
+ Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
236
+ itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and
237
+ returned. Otherwise, the module is walked recursively and submodules are converted in place.
238
+
239
+ Args:
240
+ module (torch.nn.Module): Any PyTorch module.
241
+ module_match (dict): Dictionary of full module names to freeze (all if empty)
242
+ name (str): Full module name (prefix)
243
+
244
+ Returns:
245
+ torch.nn.Module: Resulting module
246
+
247
+ Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
248
+ """
249
+ res = module
250
+ is_match = True
251
+ if module_match:
252
+ is_match = name in module_match
253
+ if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)):
254
+ res = FrozenBatchNorm2d(module.num_features)
255
+ res.num_features = module.num_features
256
+ res.affine = module.affine
257
+ if module.affine:
258
+ res.weight.data = module.weight.data.clone().detach()
259
+ res.bias.data = module.bias.data.clone().detach()
260
+ res.running_mean.data = module.running_mean.data
261
+ res.running_var.data = module.running_var.data
262
+ res.eps = module.eps
263
+ else:
264
+ for child_name, child in module.named_children():
265
+ full_child_name = ".".join([name, child_name]) if name else child_name
266
+ new_child = freeze_batch_norm_2d(child, module_match, full_child_name)
267
+ if new_child is not child:
268
+ res.add_module(child_name, new_child)
269
+ return res
270
+
271
+
272
+ # From PyTorch internals
273
+ def _ntuple(n):
274
+ def parse(x):
275
+ if isinstance(x, collections.abc.Iterable):
276
+ return x
277
+ return tuple(repeat(x, n))
278
+
279
+ return parse
280
+
281
+
282
+ to_1tuple = _ntuple(1)
283
+ to_2tuple = _ntuple(2)
284
+ to_3tuple = _ntuple(3)
285
+ to_4tuple = _ntuple(4)
286
+ to_ntuple = lambda n, x: _ntuple(n)(x)
287
+
288
+
289
+ def is_logging(args):
290
+ def is_global_master(args):
291
+ return args.rank == 0
292
+
293
+ def is_local_master(args):
294
+ return args.local_rank == 0
295
+
296
+ def is_master(args, local=False):
297
+ return is_local_master(args) if local else is_global_master(args)
298
+
299
+ return is_master
300
+
301
+
302
+ class AllGather(torch.autograd.Function):
303
+ """An autograd function that performs allgather on a tensor.
304
+ Performs all_gather operation on the provided tensors.
305
+ *** Warning ***: torch.distributed.all_gather has no gradient.
306
+ """
307
+
308
+ @staticmethod
309
+ def forward(ctx, tensor, rank, world_size):
310
+ tensors_gather = [torch.empty_like(tensor) for _ in range(world_size)]
311
+ torch.distributed.all_gather(tensors_gather, tensor)
312
+ ctx.rank = rank
313
+ ctx.batch_size = tensor.shape[0]
314
+ return torch.cat(tensors_gather, 0)
315
+
316
+ @staticmethod
317
+ def backward(ctx, grad_output):
318
+ return (grad_output[ctx.batch_size * ctx.rank : ctx.batch_size * (ctx.rank + 1)], None, None)
319
+
320
+
321
+ allgather = AllGather.apply