huzey commited on
Commit
7acde1f
·
1 Parent(s): 6447d6c
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. align_weights.pth +3 -0
  2. alignedthreeattn_backbone.py +1136 -0
  3. alignedthreeattn_model.py +38 -0
  4. prs_hook.py +224 -0
  5. utils/__init__.py +841 -0
  6. utils/__pycache__/__init__.cpython-38.pyc +0 -0
  7. utils/__pycache__/constants.cpython-38.pyc +0 -0
  8. utils/__pycache__/factory.cpython-38.pyc +0 -0
  9. utils/__pycache__/hook.cpython-38.pyc +0 -0
  10. utils/__pycache__/imagenet_segmentation.cpython-38.pyc +0 -0
  11. utils/__pycache__/misc.cpython-38.pyc +0 -0
  12. utils/__pycache__/model.cpython-38.pyc +0 -0
  13. utils/__pycache__/modified_resnet.cpython-38.pyc +0 -0
  14. utils/__pycache__/openai_models.cpython-38.pyc +0 -0
  15. utils/__pycache__/openai_templates.cpython-38.pyc +0 -0
  16. utils/__pycache__/pretrained.cpython-38.pyc +0 -0
  17. utils/__pycache__/segmentation_utils.cpython-38.pyc +0 -0
  18. utils/__pycache__/timm_model.cpython-38.pyc +0 -0
  19. utils/__pycache__/tokenizer.cpython-38.pyc +0 -0
  20. utils/__pycache__/transform.cpython-38.pyc +0 -0
  21. utils/__pycache__/transformer.cpython-38.pyc +0 -0
  22. utils/__pycache__/visualization.cpython-38.pyc +0 -0
  23. utils/binary_waterbirds.py +52 -0
  24. utils/constants.py +2 -0
  25. utils/cub_classes.py +2 -0
  26. utils/factory.py +382 -0
  27. utils/hook.py +87 -0
  28. utils/imagenet_classes.py +1 -0
  29. utils/imagenet_segmentation.py +50 -0
  30. utils/misc.py +114 -0
  31. utils/model.py +413 -0
  32. utils/model_configs/EVA01-g-14-plus.json +18 -0
  33. utils/model_configs/EVA01-g-14.json +18 -0
  34. utils/model_configs/EVA02-B-16.json +18 -0
  35. utils/model_configs/EVA02-E-14-plus.json +18 -0
  36. utils/model_configs/EVA02-E-14.json +18 -0
  37. utils/model_configs/EVA02-L-14-336.json +18 -0
  38. utils/model_configs/EVA02-L-14.json +18 -0
  39. utils/model_configs/ViT-B-16-plus-240.json +16 -0
  40. utils/model_configs/ViT-B-16-plus.json +16 -0
  41. utils/model_configs/ViT-B-16.json +16 -0
  42. utils/model_configs/ViT-B-32-plus-256.json +16 -0
  43. utils/model_configs/ViT-B-32-quickgelu.json +17 -0
  44. utils/model_configs/ViT-B-32.json +16 -0
  45. utils/model_configs/ViT-H-14.json +17 -0
  46. utils/model_configs/ViT-H-16.json +17 -0
  47. utils/model_configs/ViT-L-14-280.json +16 -0
  48. utils/model_configs/ViT-L-14-336.json +16 -0
  49. utils/model_configs/ViT-L-14.json +16 -0
  50. utils/model_configs/ViT-L-16-320.json +16 -0
align_weights.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19f6836095e80e1293fd49860f36640e2bb8c2c92e870767dc674eb501e45a42
3
+ size 84935866
alignedthreeattn_backbone.py ADDED
@@ -0,0 +1,1136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import open_clip
2
+ from open_clip.transformer import VisionTransformer
3
+
4
+ import torch
5
+ from torch import Tensor, nn
6
+ import torch.nn.functional as F
7
+
8
+ import numpy as np
9
+
10
+ from einops import rearrange, repeat
11
+
12
+ from typing import List, Optional
13
+
14
+
15
+ from utils.factory import create_model_and_transforms, get_tokenizer
16
+ from prs_hook import hook_prs_logger
17
+
18
+
19
+ class CLIPPerHead(nn.Module):
20
+ def __init__(
21
+ self, pretrained="openai", model_name="ViT-B-16", spatial=False
22
+ ) -> None:
23
+ super().__init__()
24
+ self.spatial = spatial
25
+ model, _, preprocess = create_model_and_transforms(
26
+ model_name, pretrained=pretrained
27
+ )
28
+ model.eval()
29
+ model.requires_grad_(False)
30
+ self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial)
31
+ self.model = model
32
+
33
+ def forward(self, x):
34
+ self.prs.reinit()
35
+ with torch.no_grad():
36
+ attn_method = "head" if self.spatial else "head_no_spatial"
37
+ representation = self.model.encode_image(
38
+ x, attn_method=attn_method, normalize=False
39
+ )
40
+ # attentions, mlps = self.prs.finalize(representation)
41
+ attentions = torch.stack(self.prs.attentions, axis=1).to(x.device)
42
+ # return attentions, mlps
43
+ # attentions = rearrange(attentions, "b l h d -> b (l h) d")
44
+ return attentions
45
+
46
+
47
+ class CLIPAttnNode(nn.Module):
48
+ def __init__(
49
+ self, pretrained="openai", model_name="ViT-B-16", spatial=False
50
+ ) -> None:
51
+ super().__init__()
52
+ self.spatial = spatial
53
+ model, _, preprocess = create_model_and_transforms(
54
+ model_name, pretrained=pretrained
55
+ )
56
+ model.eval()
57
+ model.requires_grad_(False)
58
+ self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial)
59
+ self.model = model
60
+
61
+ def forward(self, x):
62
+ self.prs.reinit()
63
+ with torch.no_grad():
64
+ attn_method = "head" if self.spatial else "head_no_spatial"
65
+ representation = self.model.encode_image(
66
+ x, attn_method=attn_method, normalize=False
67
+ )
68
+ # attentions, mlps = self.prs.finalize(representation)
69
+ attentions = torch.stack(self.prs.attentions, axis=1).to(x.device)
70
+ # mlps = torch.stack(self.prs.mlps, axis=1).to(x.device)
71
+ # return attentions, mlps
72
+ # attentions = rearrange(attentions, "b l h d -> b (l h) d")
73
+ attentions = attentions.sum(dim=-2)
74
+ return attentions
75
+
76
+
77
+ class CLIPMLPNode(nn.Module):
78
+ def __init__(
79
+ self, pretrained="openai", model_name="ViT-B-16", spatial=False
80
+ ) -> None:
81
+ super().__init__()
82
+ self.spatial = spatial
83
+ model, _, preprocess = create_model_and_transforms(
84
+ model_name, pretrained=pretrained
85
+ )
86
+ model.eval()
87
+ model.requires_grad_(False)
88
+ self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial)
89
+ self.model = model
90
+
91
+ def forward(self, x):
92
+ self.prs.reinit()
93
+ with torch.no_grad():
94
+ attn_method = "head" if self.spatial else "head_no_spatial"
95
+ representation = self.model.encode_image(
96
+ x, attn_method=attn_method, normalize=False
97
+ )
98
+ # attentions, mlps = self.prs.finalize(representation)
99
+ # attentions = torch.stack(self.prs.attentions, axis=1).to(x.device)
100
+ mlps = torch.stack(self.prs.mlps[1:], axis=1).to(x.device)
101
+ # return attentions, mlps
102
+ # attentions = rearrange(attentions, "b l h d -> b (l h) d")
103
+ # attentions = attentions.sum(dim=2)
104
+ return mlps if self.spatial else mlps[:, :, 0, :]
105
+
106
+
107
+ class CLIPDebug(nn.Module):
108
+ def __init__(
109
+ self, pretrained="openai", model_name="ViT-B-16", spatial=False
110
+ ) -> None:
111
+ super().__init__()
112
+ model, _, preprocess = create_model_and_transforms(
113
+ model_name, pretrained=pretrained
114
+ )
115
+ model.eval()
116
+ model.requires_grad_(False)
117
+ self.prs = hook_prs_logger(model, "cuda:0", spatial=False)
118
+ self.model = model
119
+
120
+ def forward(self, x):
121
+ self.prs.reinit()
122
+ with torch.no_grad():
123
+ attn_method = "head_no_spatial"
124
+ representation = self.model.encode_image(
125
+ x, attn_method=attn_method, normalize=False
126
+ )
127
+ # attentions, mlps = self.prs.finalize(representation)
128
+ mlps = torch.stack(self.prs.mlps, axis=1).to(x.device)
129
+ # return attentions, mlps
130
+ # attentions = rearrange(attentions, "b l h d -> b (l h) d")
131
+ return mlps[:, 1:, :]
132
+
133
+
134
+ class CLIPLastLayer(nn.Module):
135
+ def __init__(
136
+ self, pretrained="openai", model_name="ViT-B-16", spatial=False
137
+ ) -> None:
138
+ super().__init__()
139
+ self.spatial = spatial
140
+ model, _, preprocess = create_model_and_transforms(
141
+ model_name, pretrained=pretrained
142
+ )
143
+ model.eval()
144
+ model.requires_grad_(False)
145
+ self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial)
146
+ self.model = model
147
+
148
+ def forward(self, x):
149
+ self.prs.reinit()
150
+ with torch.no_grad():
151
+ attn_method = "head" if self.spatial else "head_no_spatial"
152
+ representation = self.model.encode_image(
153
+ x, attn_method=attn_method, normalize=False
154
+ )
155
+ # attentions, mlps = self.prs.finalize(representation)
156
+ attentions = torch.stack(self.prs.attentions, axis=1).to(x.device)
157
+ mlps = torch.stack(self.prs.mlps, axis=1).to(x.device)
158
+ mlps = mlps if self.spatial else mlps[:, :, 0, :]
159
+ # attentions = rearrange(attentions, "b l h d -> b (l h) d")
160
+ ret = attentions[:, :].sum(2).sum(1) + mlps[:, :].sum(1)
161
+ return ret.unsqueeze(1)
162
+
163
+
164
+ class SlowCLIPEndNode(nn.Module):
165
+ def __init__(
166
+ self, pretrained="openai", model_name="ViT-B-16", spatial=False
167
+ ) -> None:
168
+ super().__init__()
169
+ self.spatial = spatial
170
+ model, _, preprocess = create_model_and_transforms(
171
+ model_name, pretrained=pretrained
172
+ )
173
+ model.eval()
174
+ model.requires_grad_(False)
175
+ self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial)
176
+ self.model = model
177
+
178
+ def forward(self, x):
179
+ self.prs.reinit()
180
+ with torch.no_grad():
181
+ attn_method = "head" if self.spatial else "head_no_spatial"
182
+ representation = self.model.encode_image(
183
+ x, attn_method=attn_method, normalize=False
184
+ )
185
+ # attentions, mlps = self.prs.finalize(representation)
186
+ attentions = torch.stack(self.prs.attentions, axis=1).to(x.device)
187
+ mlps = torch.stack(self.prs.mlps, axis=1).to(x.device)
188
+ mlps = mlps if self.spatial else mlps[:, :, 0, :]
189
+ # attentions = rearrange(attentions, "b l h d -> b (l h) d")
190
+
191
+ rets = []
192
+ for i in range(attentions.shape[1]):
193
+ ret = attentions[:, : i + 1].sum(2).sum(1) + mlps[:, : i + 2].sum(1)
194
+ rets.append(ret)
195
+ rets = torch.stack(rets, dim=1)
196
+ return rets
197
+
198
+
199
+ class CLIPEverything(nn.Module):
200
+ def __init__(
201
+ self, pretrained="openai", model_name="ViT-B-16", spatial=False
202
+ ) -> None:
203
+ super().__init__()
204
+ self.spatial = spatial
205
+ model, _, preprocess = create_model_and_transforms(
206
+ model_name, pretrained=pretrained
207
+ )
208
+ model.eval()
209
+ model.requires_grad_(False)
210
+ self.prs = hook_prs_logger(model, "cuda:0", spatial=self.spatial)
211
+ self.model = model
212
+
213
+ def forward(self, x):
214
+ self.prs.reinit()
215
+ with torch.no_grad():
216
+ attn_method = "head" if self.spatial else "head_no_spatial"
217
+ representation = self.model.encode_image(
218
+ x, attn_method=attn_method, normalize=False
219
+ )
220
+ # attentions, mlps = self.prs.finalize(representation)
221
+ attentions = torch.stack(self.prs.attentions, axis=1).to(x.device)
222
+ mlps = torch.stack(self.prs.mlps, axis=1).to(x.device)
223
+ # attentions = rearrange(attentions, "b l h d -> b (l h) d")
224
+
225
+ end_nodes = []
226
+ for i in range(attentions.shape[1]):
227
+ ret = attentions[:, : i + 1].sum(-2).sum(1) + mlps[:, : i + 2].sum(1)
228
+ end_nodes.append(ret)
229
+ end_nodes = torch.stack(end_nodes, dim=1)
230
+
231
+ attn_mats = torch.stack(self.prs.attn_mats, axis=1).to(x.device)
232
+
233
+ return attentions, mlps, end_nodes, attn_mats
234
+
235
+
236
+ class EasyCLIPLastLayer(nn.Module):
237
+ def __init__(self, ver="ViT-B-16", data="openai", **kwargs) -> None:
238
+ super().__init__()
239
+ model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data)
240
+ self.vision_model: VisionTransformer = model.visual
241
+ self.vision_model.requires_grad_(False)
242
+ self.vision_model.eval()
243
+
244
+ def forward(
245
+ self,
246
+ x,
247
+ ):
248
+ #### original code #### begin
249
+
250
+ ##############################
251
+ ### patchify ###
252
+ ##############################
253
+
254
+ # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1
255
+ if self.vision_model.input_patchnorm:
256
+ # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')
257
+ x = x.reshape(
258
+ x.shape[0],
259
+ x.shape[1],
260
+ self.vision_model.grid_size[0],
261
+ self.vision_model.patch_size[0],
262
+ self.vision_model.grid_size[1],
263
+ self.vision_model.patch_size[1],
264
+ )
265
+ x = x.permute(0, 2, 4, 1, 3, 5)
266
+ x = x.reshape(
267
+ x.shape[0],
268
+ self.vision_model.grid_size[0] * self.vision_model.grid_size[1],
269
+ -1,
270
+ )
271
+ x = self.vision_model.patchnorm_pre_ln(x)
272
+ x = self.vision_model.conv1(x)
273
+ else:
274
+ x = self.vision_model.conv1(x) # shape = [*, width, grid, grid]
275
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
276
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
277
+
278
+ # class embeddings and positional embeddings
279
+ x = torch.cat(
280
+ [
281
+ self.vision_model.class_embedding.to(x.dtype)
282
+ + torch.zeros(
283
+ x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device
284
+ ),
285
+ x,
286
+ ],
287
+ dim=1,
288
+ ) # shape = [*, grid ** 2 + 1, width]
289
+ x = x + self.vision_model.positional_embedding.to(x.dtype)
290
+
291
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
292
+ x = self.vision_model.patch_dropout(x)
293
+ x = self.vision_model.ln_pre(x)
294
+
295
+ #### original code #### end
296
+
297
+ #### modified code #### begin
298
+
299
+ ##############################
300
+ ### transformer ###
301
+ ##############################
302
+
303
+ x = x.permute(1, 0, 2) # NLD -> LND
304
+
305
+ local_tokens = {}
306
+ global_tokens = {}
307
+ tokens = []
308
+ for i, r in enumerate(self.vision_model.transformer.resblocks):
309
+ x = r(x) # [1+p**2, B, D]
310
+ x_save = x.clone()
311
+ x_save = x_save[1:, :, :] # [p**2, B, D]
312
+ p = int(np.sqrt(x_save.shape[0]))
313
+ x_save = rearrange(x_save, "(p1 p2) b d -> b d p1 p2", p1=p, p2=p)
314
+ local_tokens[str(i)] = x_save
315
+ global_tokens[str(i)] = x[0, :, :] # [B, D]
316
+ tokens.append(x[0, :, :])
317
+ return tokens[-1].unsqueeze(1)
318
+
319
+
320
+ class CLIPSumResidual(nn.Module):
321
+ def __init__(self, ver="ViT-B-16", data="openai", output_text=False, **kwargs) -> None:
322
+ super().__init__()
323
+ model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data)
324
+ self.vision_model: VisionTransformer = model.visual
325
+ self.vision_model.requires_grad_(False)
326
+ self.vision_model.eval()
327
+
328
+ self.output_text = output_text
329
+
330
+ def forward(
331
+ self,
332
+ x,
333
+ ):
334
+ #### original code #### begin
335
+
336
+ ##############################
337
+ ### patchify ###
338
+ ##############################
339
+
340
+ # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1
341
+ if self.vision_model.input_patchnorm:
342
+ # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')
343
+ x = x.reshape(
344
+ x.shape[0],
345
+ x.shape[1],
346
+ self.vision_model.grid_size[0],
347
+ self.vision_model.patch_size[0],
348
+ self.vision_model.grid_size[1],
349
+ self.vision_model.patch_size[1],
350
+ )
351
+ x = x.permute(0, 2, 4, 1, 3, 5)
352
+ x = x.reshape(
353
+ x.shape[0],
354
+ self.vision_model.grid_size[0] * self.vision_model.grid_size[1],
355
+ -1,
356
+ )
357
+ x = self.vision_model.patchnorm_pre_ln(x)
358
+ x = self.vision_model.conv1(x)
359
+ else:
360
+ x = self.vision_model.conv1(x) # shape = [*, width, grid, grid]
361
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
362
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
363
+
364
+ # class embeddings and positional embeddings
365
+ x = torch.cat(
366
+ [
367
+ self.vision_model.class_embedding.to(x.dtype)
368
+ + torch.zeros(
369
+ x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device
370
+ ),
371
+ x,
372
+ ],
373
+ dim=1,
374
+ ) # shape = [*, grid ** 2 + 1, width]
375
+ x = x + self.vision_model.positional_embedding.to(x.dtype)
376
+
377
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
378
+ x = self.vision_model.patch_dropout(x)
379
+ x = self.vision_model.ln_pre(x)
380
+
381
+ #### original code #### end
382
+
383
+ #### modified code #### begin
384
+
385
+ ##############################
386
+ ### transformer ###
387
+ ##############################
388
+
389
+ x = x.permute(1, 0, 2) # NLD -> LND
390
+
391
+
392
+ tokens = []
393
+ for i, r in enumerate(self.vision_model.transformer.resblocks):
394
+ x = r(x) # [1+p**2, B, D]
395
+ tokens.append(x.permute(1, 0, 2))
396
+ mytokens = torch.stack(tokens, dim=1)
397
+ x = x.permute(1, 0, 2) # LND -> NLD
398
+
399
+ if self.vision_model.attn_pool is not None:
400
+ x = self.vision_model.attn_pool(x)
401
+ x = self.vision_model.ln_post(x)
402
+ pooled, tokens = self.vision_model._global_pool(x)
403
+ else:
404
+ pooled, tokens = self.vision_model._global_pool(x)
405
+ pooled = self.vision_model.ln_post(pooled)
406
+
407
+ if self.vision_model.proj is not None:
408
+ pooled = pooled @ self.vision_model.proj
409
+
410
+ if self.output_text:
411
+ return pooled, mytokens
412
+
413
+ return mytokens
414
+
415
+ class CLIPEndNode(nn.Module):
416
+ def __init__(self, ver="ViT-B-16", data="openai", spatial=False, **kwargs) -> None:
417
+ super().__init__()
418
+ model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data)
419
+ self.vision_model: VisionTransformer = model.visual
420
+ self.vision_model.requires_grad_(False)
421
+ self.vision_model.eval()
422
+
423
+ self.spatial = spatial
424
+
425
+ def forward(
426
+ self,
427
+ x,
428
+ ):
429
+ #### original code #### begin
430
+
431
+ ##############################
432
+ ### patchify ###
433
+ ##############################
434
+
435
+ # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1
436
+ if self.vision_model.input_patchnorm:
437
+ # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')
438
+ x = x.reshape(
439
+ x.shape[0],
440
+ x.shape[1],
441
+ self.vision_model.grid_size[0],
442
+ self.vision_model.patch_size[0],
443
+ self.vision_model.grid_size[1],
444
+ self.vision_model.patch_size[1],
445
+ )
446
+ x = x.permute(0, 2, 4, 1, 3, 5)
447
+ x = x.reshape(
448
+ x.shape[0],
449
+ self.vision_model.grid_size[0] * self.vision_model.grid_size[1],
450
+ -1,
451
+ )
452
+ x = self.vision_model.patchnorm_pre_ln(x)
453
+ x = self.vision_model.conv1(x)
454
+ else:
455
+ x = self.vision_model.conv1(x) # shape = [*, width, grid, grid]
456
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
457
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
458
+
459
+ # class embeddings and positional embeddings
460
+ x = torch.cat(
461
+ [
462
+ self.vision_model.class_embedding.to(x.dtype)
463
+ + torch.zeros(
464
+ x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device
465
+ ),
466
+ x,
467
+ ],
468
+ dim=1,
469
+ ) # shape = [*, grid ** 2 + 1, width]
470
+ x = x + self.vision_model.positional_embedding.to(x.dtype)
471
+
472
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
473
+ x = self.vision_model.patch_dropout(x)
474
+ x = self.vision_model.ln_pre(x)
475
+
476
+ #### original code #### end
477
+
478
+ #### modified code #### begin
479
+
480
+ ##############################
481
+ ### transformer ###
482
+ ##############################
483
+
484
+ x = x.permute(1, 0, 2) # NLD -> LND
485
+
486
+ local_tokens = {}
487
+ global_tokens = {}
488
+ tokens = []
489
+ for i, r in enumerate(self.vision_model.transformer.resblocks):
490
+ x = r(x) # [1+p**2, B, D]
491
+ x_save = x.clone()
492
+ x_save = x_save[1:, :, :] # [p**2, B, D]
493
+ p = int(np.sqrt(x_save.shape[0]))
494
+ x_save = rearrange(x_save, "(p1 p2) b d -> b d p1 p2", p1=p, p2=p)
495
+ local_tokens[str(i)] = x_save
496
+ global_tokens[str(i)] = x[0, :, :] # [B, D]
497
+ if self.spatial:
498
+ tokens.append(rearrange(x, "p b d -> b p d"))
499
+ else:
500
+ tokens.append(x[0, :, :])
501
+ return torch.stack(tokens, dim=1)
502
+
503
+ # return local_tokens, global_tokens
504
+
505
+
506
+ class ModifiedCLIP(nn.Module):
507
+ def __init__(self, ver="ViT-B-16", data="openai", **kwargs) -> None:
508
+ super().__init__()
509
+ model, _, _ = open_clip.create_model_and_transforms(ver, pretrained=data)
510
+ self.vision_model: VisionTransformer = model.visual
511
+ self.vision_model.requires_grad_(False)
512
+ self.vision_model.eval()
513
+
514
+ def get_tokens(
515
+ self,
516
+ x,
517
+ ):
518
+ #### original code #### begin
519
+
520
+ ##############################
521
+ ### patchify ###
522
+ ##############################
523
+
524
+ # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1
525
+ if self.vision_model.input_patchnorm:
526
+ # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')
527
+ x = x.reshape(
528
+ x.shape[0],
529
+ x.shape[1],
530
+ self.vision_model.grid_size[0],
531
+ self.vision_model.patch_size[0],
532
+ self.vision_model.grid_size[1],
533
+ self.vision_model.patch_size[1],
534
+ )
535
+ x = x.permute(0, 2, 4, 1, 3, 5)
536
+ x = x.reshape(
537
+ x.shape[0],
538
+ self.vision_model.grid_size[0] * self.vision_model.grid_size[1],
539
+ -1,
540
+ )
541
+ x = self.vision_model.patchnorm_pre_ln(x)
542
+ x = self.vision_model.conv1(x)
543
+ else:
544
+ x = self.vision_model.conv1(x) # shape = [*, width, grid, grid]
545
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
546
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
547
+
548
+ # class embeddings and positional embeddings
549
+ x = torch.cat(
550
+ [
551
+ self.vision_model.class_embedding.to(x.dtype)
552
+ + torch.zeros(
553
+ x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device
554
+ ),
555
+ x,
556
+ ],
557
+ dim=1,
558
+ ) # shape = [*, grid ** 2 + 1, width]
559
+ x = x + self.vision_model.positional_embedding.to(x.dtype)
560
+
561
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
562
+ x = self.vision_model.patch_dropout(x)
563
+ x = self.vision_model.ln_pre(x)
564
+
565
+ #### original code #### end
566
+
567
+ #### modified code #### begin
568
+
569
+ ##############################
570
+ ### transformer ###
571
+ ##############################
572
+
573
+ x = x.permute(1, 0, 2) # NLD -> LND
574
+
575
+ local_tokens = {}
576
+ global_tokens = {}
577
+ for i, r in enumerate(self.vision_model.transformer.resblocks):
578
+ x = r(x) # [1+p**2, B, D]
579
+ x_save = x.clone()
580
+ x_save = x_save[1:, :, :] # [p**2, B, D]
581
+ p = int(np.sqrt(x_save.shape[0]))
582
+ x_save = rearrange(x_save, "(p1 p2) b d -> b d p1 p2", p1=p, p2=p)
583
+ local_tokens[str(i)] = x_save
584
+ global_tokens[str(i)] = x[0, :, :] # [B, D]
585
+
586
+ return local_tokens, global_tokens
587
+
588
+
589
+ # from dinov2.models.vision_transformer import DinoVisionTransformer
590
+
591
+
592
+ class ModifiedDiNOv2(nn.Module):
593
+ def __init__(self, ver="dinov2_vitb14", **kwargs) -> None:
594
+ super().__init__()
595
+ vision_model = torch.hub.load("facebookresearch/dinov2", ver)
596
+ # self.vision_model: DinoVisionTransformer = vision_model
597
+ self.vision_model = vision_model
598
+ self.vision_model.requires_grad_(False)
599
+ self.vision_model.eval()
600
+
601
+ def get_tokens(
602
+ self,
603
+ x,
604
+ ):
605
+ #### original code #### begin
606
+ x = self.vision_model.prepare_tokens_with_masks(x)
607
+ #### original code #### end
608
+
609
+ #### modified code #### begin
610
+ local_tokens = {}
611
+ global_tokens = {}
612
+ for i, blk in enumerate(self.vision_model.blocks):
613
+ x = blk(x)
614
+ saved_x = x.clone()
615
+ global_tokens[str(i)] = saved_x[:, 0, :] # [B, C]
616
+ saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C]
617
+ p = int(np.sqrt(saved_x.shape[1]))
618
+ saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p)
619
+ local_tokens[str(i)] = saved_x
620
+ return local_tokens, global_tokens
621
+
622
+
623
+ class DiNOv2EndNode(nn.Module):
624
+ def __init__(self, ver="dinov2_vitb14_reg", num_layers=12, spatial=False) -> None:
625
+ super().__init__()
626
+ self.dinov2 = torch.hub.load("facebookresearch/dinov2", ver)
627
+ self.dinov2.requires_grad_(False)
628
+ self.dinov2.eval()
629
+
630
+ self.num_layers = num_layers
631
+ self.spatial = spatial
632
+
633
+ def forward(self, x):
634
+ out = self.dinov2.get_intermediate_layers(
635
+ x, self.num_layers, return_class_token=True, norm=False
636
+ )
637
+ class_tokens, spatial_tokens = [], []
638
+ for i, (sp, cls) in enumerate(out):
639
+ class_tokens.append(cls)
640
+ spatial_tokens.append(sp)
641
+ if self.spatial:
642
+ c = torch.stack(class_tokens, dim=1) # [B, L, C]
643
+ p = torch.stack(spatial_tokens, dim=1) # [B, L, P, C]
644
+ c = repeat(c, "b l c -> b l p c", p=1)
645
+ return torch.cat([c, p], dim=2)
646
+ else:
647
+ return torch.stack(class_tokens, dim=1)
648
+
649
+
650
+ class DiNOv2SumResidual(nn.Module):
651
+ def __init__(self, ver="dinov2_vitb14_reg", num_layers=12, spatial=True) -> None:
652
+ super().__init__()
653
+ self.dinov2 = torch.hub.load("facebookresearch/dinov2", ver)
654
+ self.dinov2.requires_grad_(False)
655
+ self.dinov2.eval()
656
+
657
+ self.num_layers = num_layers
658
+ self.spatial = spatial
659
+
660
+ def forward(self, x):
661
+ # resample to 196x196
662
+ x = torch.nn.functional.interpolate(x, size=(196, 196), mode="bilinear")
663
+ out = self.dinov2.get_intermediate_layers(
664
+ x, self.num_layers, return_class_token=True, norm=False
665
+ )
666
+ class_tokens, spatial_tokens = [], []
667
+ for i, (sp, cls) in enumerate(out):
668
+ class_tokens.append(cls)
669
+ spatial_tokens.append(sp)
670
+ if self.spatial:
671
+ c = torch.stack(class_tokens, dim=1) # [B, L, C]
672
+ p = torch.stack(spatial_tokens, dim=1) # [B, L, P, C]
673
+ c = repeat(c, "b l c -> b l p c", p=1)
674
+ return torch.cat([c, p], dim=2)
675
+ else:
676
+ return torch.stack(class_tokens, dim=1)
677
+
678
+
679
+ class DiNOv2AttnMlpNode(nn.Module):
680
+
681
+ def __init__(self, ver="dinov2_vitb14_reg", num_reg=4) -> None:
682
+ super().__init__()
683
+ dinov2 = torch.hub.load("facebookresearch/dinov2", ver)
684
+ dinov2.requires_grad_(False)
685
+ dinov2.eval()
686
+
687
+ def forward(self, x: Tensor) -> Tensor:
688
+ def attn_residual_func(x: Tensor) -> Tensor:
689
+ return self.ls1(self.attn(self.norm1(x)))
690
+
691
+ def ffn_residual_func(x: Tensor) -> Tensor:
692
+ return self.ls2(self.mlp(self.norm2(x)))
693
+
694
+ self.saved_attn_node = attn_residual_func(x)
695
+ x = x + self.saved_attn_node
696
+ self.saved_mlp_node = ffn_residual_func(x)
697
+ x = x + self.saved_mlp_node
698
+ return x
699
+
700
+ setattr(dinov2.blocks[0].__class__, "forward", forward)
701
+
702
+ self.dinov2 = dinov2
703
+ self.num_reg = num_reg
704
+
705
+ def forward(self, x: Tensor) -> Tensor:
706
+ out = self.dinov2(x)
707
+ attn_nodes = [block.saved_attn_node for block in self.dinov2.blocks]
708
+ mlp_nodes = [block.saved_mlp_node for block in self.dinov2.blocks]
709
+ nodes = torch.stack(attn_nodes + mlp_nodes, dim=1)
710
+ # remove register tokens
711
+ nodes = torch.cat([nodes[:, :, :1], nodes[:, :, self.num_reg + 1 :]], dim=2)
712
+ return nodes
713
+
714
+
715
+ class DiNOv2AttnNode(nn.Module):
716
+ def __init__(self, ver="dinov2_vitb14_reg", num_reg=4) -> None:
717
+ super().__init__()
718
+ self.dino = DiNOv2AttnMlpNode(ver=ver, num_reg=num_reg)
719
+ self.num_reg = num_reg
720
+
721
+ def forward(self, x: Tensor) -> Tensor:
722
+ # resample to 196x196
723
+ # x = torch.nn.functional.interpolate(x, size=(196, 196), mode="bilinear")
724
+ out = self.dino(x)
725
+ nodes = [block.saved_attn_node for block in self.dino.dinov2.blocks]
726
+ nodes = torch.stack(nodes, dim=1)
727
+ # remove register tokens
728
+ nodes = torch.cat([nodes[:, :, :1], nodes[:, :, self.num_reg + 1 :]], dim=2)
729
+ return nodes
730
+
731
+
732
+
733
+ class DINOv1AttnNode(nn.Module):
734
+ def __init__(self, ver='dino_vits16'):
735
+ super().__init__()
736
+ dino = torch.hub.load('facebookresearch/dino:main', ver)
737
+ dino.requires_grad_(False)
738
+ dino.eval()
739
+
740
+ def forward(self, x, return_attention=False):
741
+ y, attn = self.attn(self.norm1(x))
742
+ if return_attention:
743
+ return attn
744
+ self.saved_attn = y
745
+ x = x + self.drop_path(y)
746
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
747
+ return x
748
+
749
+ setattr(dino.blocks[0].__class__, 'forward', forward)
750
+ self.dino = dino
751
+
752
+ def forward(self, x):
753
+ out = self.dino(x)
754
+ attn_nodes = [block.saved_attn for block in self.dino.blocks]
755
+ out = torch.stack(attn_nodes, dim=1)
756
+ d = out.shape[-1]
757
+ if d < 768:
758
+ out = F.pad(out, (0, 768 - d), 'constant', 0)
759
+ return out
760
+
761
+
762
+ from segment_anything import sam_model_registry, SamPredictor
763
+ from segment_anything.modeling.sam import Sam
764
+
765
+
766
+ class ModifiedSAM(torch.nn.Module):
767
+ def __init__(self, **kwargs):
768
+ super().__init__(**kwargs)
769
+ sam: Sam = sam_model_registry["vit_b"](checkpoint=None)
770
+ sd = torch.hub.load_state_dict_from_url(
771
+ "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"
772
+ )
773
+ sam.load_state_dict(sd)
774
+
775
+ def new_forward(self, x: torch.Tensor) -> torch.Tensor:
776
+ x = self.patch_embed(x)
777
+ if self.pos_embed is not None:
778
+ x = x + self.pos_embed
779
+ local_tokens, global_tokens = {}, {}
780
+ for i, blk in enumerate(self.blocks):
781
+ x = blk(x)
782
+ x_save = x.clone()
783
+ x_save = x_save.permute(0, 3, 1, 2)
784
+ local_tokens[f"{i}"] = x_save
785
+ global_tokens[f"{i}"] = x_save.mean(dim=(2, 3))
786
+
787
+ return local_tokens, global_tokens
788
+
789
+ setattr(sam.image_encoder.__class__, "forward", new_forward)
790
+
791
+ self.image_encoder = sam.image_encoder
792
+ self.image_encoder.requires_grad_(False)
793
+ self.image_encoder.eval()
794
+
795
+ def get_tokens(
796
+ self,
797
+ x,
798
+ ):
799
+ with torch.no_grad():
800
+ x = torch.nn.functional.interpolate(x, size=(1024, 1024), mode="bilinear")
801
+ local_tokens, global_tokens = self.image_encoder(x)
802
+ return local_tokens, global_tokens
803
+
804
+
805
+ import timm
806
+
807
+
808
+ class ModifiedMAE(timm.models.vision_transformer.VisionTransformer):
809
+ def __init__(self, **kwargs):
810
+ super(ModifiedMAE, self).__init__(**kwargs)
811
+
812
+ sd = torch.hub.load_state_dict_from_url(
813
+ "https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth"
814
+ )
815
+
816
+ checkpoint_model = sd["model"]
817
+ state_dict = self.state_dict()
818
+ for k in ["head.weight", "head.bias"]:
819
+ if (
820
+ k in checkpoint_model
821
+ and checkpoint_model[k].shape != state_dict[k].shape
822
+ ):
823
+ print(f"Removing key {k} from pretrained checkpoint")
824
+ del checkpoint_model[k]
825
+
826
+ # load pre-trained model
827
+ msg = self.load_state_dict(checkpoint_model, strict=False)
828
+ print(msg)
829
+
830
+ self.requires_grad_(False)
831
+ self.eval()
832
+
833
+ def get_tokens(
834
+ self,
835
+ x,
836
+ ):
837
+ B = x.shape[0]
838
+ x = self.patch_embed(x)
839
+
840
+ cls_tokens = self.cls_token.expand(
841
+ B, -1, -1
842
+ ) # stole cls_tokens impl from Phil Wang, thanks
843
+ x = torch.cat((cls_tokens, x), dim=1)
844
+ x = x + self.pos_embed
845
+ x = self.pos_drop(x)
846
+
847
+ local_tokens = {}
848
+ global_tokens = {}
849
+ for i, blk in enumerate(self.blocks):
850
+ x = blk(x)
851
+ saved_x = x.clone()
852
+ saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C]
853
+ p = int(np.sqrt(saved_x.shape[1]))
854
+ saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p)
855
+ local_tokens[str(i)] = saved_x
856
+ global_tokens[str(i)] = x[:, 0, :] # [B, C]
857
+ return local_tokens, global_tokens
858
+
859
+
860
+ class MAEEndNode(nn.Module):
861
+ def __init__(self, spatial=False, **kwargs):
862
+ super().__init__(**kwargs)
863
+ model = ModifiedMAE()
864
+ model.requires_grad_(False)
865
+ model.eval()
866
+ self.model = model
867
+
868
+ self.spatial = spatial
869
+
870
+ def forward(self, x):
871
+ local_tokens, global_tokens = self.model.get_tokens(x)
872
+ # global_tokens = torch.stack(list(global_tokens.values()), dim=1)
873
+ # return global_tokens
874
+ if not self.spatial:
875
+ local_tokens = [tk.mean(dim=(2, 3)) for tk in local_tokens.values()]
876
+ local_tokens = torch.stack(local_tokens, dim=1)
877
+ return local_tokens
878
+ else:
879
+ local_tokens = [
880
+ rearrange(tk, "b c p1 p2 -> b (p1 p2) c")
881
+ for tk in local_tokens.values()
882
+ ]
883
+ local_tokens = torch.stack(local_tokens, dim=1)
884
+ global_tokens = torch.stack(list(global_tokens.values()), dim=1)
885
+ global_tokens = repeat(global_tokens, "b l c -> b l p c", p=1)
886
+ return torch.cat([global_tokens, local_tokens], dim=2)
887
+
888
+
889
+ class MAEEndNodePatch(nn.Module):
890
+ def __init__(self, **kwargs):
891
+ super().__init__(**kwargs)
892
+ model = ModifiedMAE()
893
+ model.requires_grad_(False)
894
+ model.eval()
895
+ self.model = model
896
+
897
+ def forward(self, x):
898
+ local_tokens, global_tokens = self.model.get_tokens(x)
899
+ for k, v in local_tokens.items():
900
+ local_tokens[k] = v.mean(dim=(2, 3))
901
+ local_tokens = torch.stack(list(local_tokens.values()), dim=1)
902
+ return local_tokens
903
+
904
+
905
+ class MAEAttnMlpNode(timm.models.vision_transformer.VisionTransformer):
906
+ def __init__(self, **kwargs):
907
+ super(MAEAttnMlpNode, self).__init__(**kwargs)
908
+
909
+ sd = torch.hub.load_state_dict_from_url(
910
+ "https://dl.fbaipublicfiles.com/mae/pretrain/mae_pretrain_vit_base.pth"
911
+ )
912
+
913
+ checkpoint_model = sd["model"]
914
+ state_dict = self.state_dict()
915
+ for k in ["head.weight", "head.bias"]:
916
+ if (
917
+ k in checkpoint_model
918
+ and checkpoint_model[k].shape != state_dict[k].shape
919
+ ):
920
+ print(f"Removing key {k} from pretrained checkpoint")
921
+ del checkpoint_model[k]
922
+
923
+ # load pre-trained model
924
+ msg = self.load_state_dict(checkpoint_model, strict=False)
925
+ print(msg)
926
+
927
+ self.requires_grad_(False)
928
+ self.eval()
929
+
930
+ def forward(self, x):
931
+ self.saved_attn_node = self.ls1(self.attn(self.norm1(x)))
932
+ x = x + self.saved_attn_node
933
+ self.saved_mlp_node = self.ls2(self.mlp(self.norm2(x)))
934
+ x = x + self.saved_mlp_node
935
+ # x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x))))
936
+ # x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))
937
+ return x
938
+
939
+ setattr(self.blocks[0].__class__, "forward", forward)
940
+
941
+ def forward(self, x):
942
+ out = super().forward(x)
943
+ attn_nodes = [block.saved_attn_node for block in self.blocks]
944
+ mlp_nodes = [block.saved_mlp_node for block in self.blocks]
945
+ nodes = torch.stack(attn_nodes + mlp_nodes, dim=1)
946
+ return nodes
947
+
948
+
949
+ class MAEAttnNode(nn.Module):
950
+ def __init__(self, **kwargs):
951
+ super().__init__(**kwargs)
952
+ model = MAEAttnMlpNode()
953
+ self.model = model
954
+
955
+ def forward(self, x):
956
+ out = self.model(x)
957
+ attn_nodes = [block.saved_attn_node for block in self.model.blocks]
958
+ return torch.stack(attn_nodes, dim=1)
959
+
960
+
961
+ from torchvision.models import ViT_B_16_Weights, ViT_L_16_Weights, ViT_H_14_Weights
962
+ from torchvision.models import vit_b_16, vit_l_16, vit_h_14
963
+ from torchvision.models import list_models, get_model
964
+ from torchvision.models.feature_extraction import (
965
+ create_feature_extractor,
966
+ get_graph_node_names,
967
+ )
968
+
969
+
970
+ class ModifiedImgNet(nn.Module):
971
+ def __init__(self, **kwargs) -> None:
972
+ super().__init__()
973
+ model = get_model("vit_b_16", weights=ViT_B_16_Weights.IMAGENET1K_V1)
974
+ model.requires_grad_(False)
975
+ model.eval()
976
+ layers = [f"encoder.layers.encoder_layer_{i}.add_1" for i in range(12)]
977
+ model = create_feature_extractor(model, layers)
978
+
979
+ self.model = model
980
+
981
+ def get_tokens(
982
+ self,
983
+ x,
984
+ ):
985
+ em = self.model(x)
986
+ out_list = list(em.values())
987
+
988
+ local_tokens = {}
989
+ global_tokens = {}
990
+ for i, out in enumerate(out_list):
991
+ saved_x = out.clone()
992
+ saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C]
993
+ p = int(np.sqrt(saved_x.shape[1]))
994
+ saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p)
995
+ local_tokens[str(i)] = saved_x
996
+ global_tokens[str(i)] = out[:, 0, :] # [B, C]
997
+ return local_tokens, global_tokens
998
+
999
+
1000
+ import math
1001
+ import torch
1002
+ import torch.nn as nn
1003
+ from functools import partial, reduce
1004
+ from operator import mul
1005
+
1006
+ from timm.models.layers import PatchEmbed
1007
+
1008
+
1009
+ class ModifiedMoCov3(timm.models.vision_transformer.VisionTransformer):
1010
+ def __init__(
1011
+ self,
1012
+ stop_grad_conv1=False,
1013
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
1014
+ **kwargs,
1015
+ ):
1016
+ super().__init__(norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
1017
+ # Use fixed 2D sin-cos position embedding
1018
+ self.build_2d_sincos_position_embedding()
1019
+
1020
+ # weight initialization
1021
+ for name, m in self.named_modules():
1022
+ if isinstance(m, nn.Linear):
1023
+ if "qkv" in name:
1024
+ # treat the weights of Q, K, V separately
1025
+ val = math.sqrt(
1026
+ 6.0 / float(m.weight.shape[0] // 3 + m.weight.shape[1])
1027
+ )
1028
+ nn.init.uniform_(m.weight, -val, val)
1029
+ else:
1030
+ nn.init.xavier_uniform_(m.weight)
1031
+ nn.init.zeros_(m.bias)
1032
+ nn.init.normal_(self.cls_token, std=1e-6)
1033
+
1034
+ if isinstance(self.patch_embed, PatchEmbed):
1035
+ # xavier_uniform initialization
1036
+ val = math.sqrt(
1037
+ 6.0
1038
+ / float(
1039
+ 3 * reduce(mul, self.patch_embed.patch_size, 1) + self.embed_dim
1040
+ )
1041
+ )
1042
+ nn.init.uniform_(self.patch_embed.proj.weight, -val, val)
1043
+ nn.init.zeros_(self.patch_embed.proj.bias)
1044
+
1045
+ if stop_grad_conv1:
1046
+ self.patch_embed.proj.weight.requires_grad = False
1047
+ self.patch_embed.proj.bias.requires_grad = False
1048
+
1049
+ checkpoint = torch.hub.load_state_dict_from_url(
1050
+ "https://dl.fbaipublicfiles.com/moco-v3/vit-b-300ep/vit-b-300ep.pth.tar"
1051
+ )
1052
+
1053
+ linear_keyword = "head"
1054
+ # rename moco pre-trained keys
1055
+ state_dict = checkpoint["state_dict"]
1056
+ for k in list(state_dict.keys()):
1057
+ # retain only base_encoder up to before the embedding layer
1058
+ if k.startswith("module.base_encoder") and not k.startswith(
1059
+ "module.base_encoder.%s" % linear_keyword
1060
+ ):
1061
+ # remove prefix
1062
+ state_dict[k[len("module.base_encoder.") :]] = state_dict[k]
1063
+ # delete renamed or unused k
1064
+ del state_dict[k]
1065
+
1066
+ msg = self.load_state_dict(state_dict, strict=False)
1067
+ assert set(msg.missing_keys) == {
1068
+ "%s.weight" % linear_keyword,
1069
+ "%s.bias" % linear_keyword,
1070
+ }
1071
+
1072
+ # print("=> loaded pre-trained self '{}'".format(checkpoint))
1073
+
1074
+ self.requires_grad_(False)
1075
+ self.eval()
1076
+
1077
+ def build_2d_sincos_position_embedding(self, temperature=10000.0):
1078
+ h, w = self.patch_embed.grid_size
1079
+ grid_w = torch.arange(w, dtype=torch.float32)
1080
+ grid_h = torch.arange(h, dtype=torch.float32)
1081
+ grid_w, grid_h = torch.meshgrid(grid_w, grid_h)
1082
+ assert (
1083
+ self.embed_dim % 4 == 0
1084
+ ), "Embed dimension must be divisible by 4 for 2D sin-cos position embedding"
1085
+ pos_dim = self.embed_dim // 4
1086
+ omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim
1087
+ omega = 1.0 / (temperature**omega)
1088
+ out_w = torch.einsum("m,d->md", [grid_w.flatten(), omega])
1089
+ out_h = torch.einsum("m,d->md", [grid_h.flatten(), omega])
1090
+ pos_emb = torch.cat(
1091
+ [torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)],
1092
+ dim=1,
1093
+ )[None, :, :]
1094
+
1095
+ # assert self.num_tokens == 1, 'Assuming one and only one token, [cls]'
1096
+ pe_token = torch.zeros([1, 1, self.embed_dim], dtype=torch.float32)
1097
+ self.pos_embed = nn.Parameter(torch.cat([pe_token, pos_emb], dim=1))
1098
+ self.pos_embed.requires_grad = False
1099
+
1100
+ def get_tokens(
1101
+ self,
1102
+ x,
1103
+ ):
1104
+ B = x.shape[0]
1105
+ x = self.patch_embed(x)
1106
+
1107
+ cls_tokens = self.cls_token.expand(
1108
+ B, -1, -1
1109
+ ) # stole cls_tokens impl from Phil Wang, thanks
1110
+ x = torch.cat((cls_tokens, x), dim=1)
1111
+ x = x + self.pos_embed
1112
+ x = self.pos_drop(x)
1113
+
1114
+ local_tokens = {}
1115
+ global_tokens = {}
1116
+ for i, blk in enumerate(self.blocks):
1117
+ x = blk(x)
1118
+ saved_x = x.clone()
1119
+ saved_x = saved_x[:, 1:, :] # remove cls token, [B, N, C]
1120
+ p = int(np.sqrt(saved_x.shape[1]))
1121
+ saved_x = rearrange(saved_x, "b (p1 p2) c -> b c p1 p2", p1=p, p2=p)
1122
+ local_tokens[str(i)] = saved_x
1123
+ global_tokens[str(i)] = x[:, 0, :] # [B, C]
1124
+ return local_tokens, global_tokens
1125
+
1126
+
1127
+ if __name__ == "__main__":
1128
+ # clip = CLIPAttnNode().cuda()
1129
+ # dino = DiNOv2AttnNode().cuda()
1130
+ dinov1 = DINOv1AttnNode().cuda()
1131
+ # mae = MAEAttnNode().cuda()
1132
+ x = torch.randn(1, 3, 224, 224).cuda()
1133
+ # print(clip(x).shape)
1134
+ # print(dino(x).shape)
1135
+ # print(mae(x).shape)
1136
+ print(dinov1(x).shape)
alignedthreeattn_model.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import os
3
+ import torch
4
+ from PIL import Image
5
+ from einops import rearrange, repeat
6
+ import numpy as np
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+
11
+ align_weights = torch.load("align_weights.pth")
12
+ from torch import nn
13
+ from backbone import CLIPAttnNode, DiNOv2AttnNode, MAEAttnNode
14
+ class ThreeAttnNodes(nn.Module):
15
+ def __init__(self, align_weights=align_weights):
16
+ super().__init__()
17
+ self.backbone1 = CLIPAttnNode()
18
+ self.backbone2 = DiNOv2AttnNode()
19
+ self.backbone3 = MAEAttnNode()
20
+ for backbone in [self.backbone1, self.backbone2, self.backbone3]:
21
+ backbone.requires_grad_(False)
22
+ backbone.eval()
23
+ self.align_weights = align_weights
24
+
25
+ @torch.no_grad()
26
+ def forward(self, x):
27
+ # resize x to 672x672
28
+ x = F.interpolate(x, size=(672, 672), mode="bilinear")
29
+ feat1 = self.backbone1(x)
30
+ feat3 = self.backbone3(x)
31
+ # resize x to 588x588
32
+ x = F.interpolate(x, size=(588, 588), mode="bilinear")
33
+ feat2 = self.backbone2(x)
34
+ feats = torch.cat([feat1, feat2, feat3], dim=1)
35
+ out = torch.einsum("b l p i, l o i -> b l p o", feats, self.align_weights)
36
+ out = rearrange(out[:, :, 1:], "b l (h w) o -> b l h w o", h=42, w=42)
37
+ return out
38
+
prs_hook.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import numpy as np
3
+ import torch
4
+ from PIL import Image
5
+ import glob
6
+ import sys
7
+ import argparse
8
+ import datetime
9
+ import json
10
+ from pathlib import Path
11
+
12
+
13
+ class PRSLogger(object):
14
+ def __init__(self, model, device, spatial: bool = True):
15
+ self.current_layer = 0
16
+ self.device = device
17
+ self.attentions = []
18
+ self.mlps = []
19
+ self.ks = []
20
+ self.qs = []
21
+ self.vs = []
22
+ self.attn_mats = []
23
+ self.spatial = spatial
24
+ self.post_ln_std = None
25
+ self.post_ln_mean = None
26
+ self.model = model
27
+
28
+ @torch.no_grad()
29
+ def compute_attentions_spatial(self, ret):
30
+ assert (
31
+ len(ret.shape) == 5
32
+ ), "Verify that you use method=`head` and not method=`head_no_spatial`" # [b, n, m, h, d]
33
+ assert (
34
+ self.spatial
35
+ ), "Verify that you use method=`head` and not method=`head_no_spatial`"
36
+ bias_term = self.model.visual.transformer.resblocks[
37
+ self.current_layer
38
+ ].attn.out_proj.bias
39
+ self.current_layer += 1
40
+ return_value = ret[:, 0] # This is only for the cls token
41
+ self.attentions.append(
42
+ return_value
43
+ + bias_term[np.newaxis, np.newaxis, np.newaxis]
44
+ / (return_value.shape[1] * return_value.shape[2])
45
+ ) # [b, n, h, d]
46
+ return ret
47
+
48
+ @torch.no_grad()
49
+ def compute_attentions_non_spatial(self, ret):
50
+ assert (
51
+ len(ret.shape) == 4
52
+ ), "Verify that you use method=`head_no_spatial` and not method=`head`" # [b, n, h, d]
53
+ assert (
54
+ not self.spatial
55
+ ), "Verify that you use method=`head_no_spatial` and not method=`head`"
56
+ bias_term = self.model.visual.transformer.resblocks[
57
+ self.current_layer
58
+ ].attn.out_proj.bias
59
+ self.current_layer += 1
60
+ # return_value = ret[:, 0] # This is only for the cls token
61
+ return_value = ret
62
+ self.attentions.append(
63
+ return_value + bias_term / (return_value.shape[-2])
64
+ ) # [b, h, d]
65
+ return ret
66
+
67
+ @torch.no_grad()
68
+ def compute_k(self, ret):
69
+ self.ks.append(ret) # [b, n, h, d]
70
+ return ret
71
+
72
+ @torch.no_grad()
73
+ def compute_q(self, ret):
74
+ self.qs.append(ret)
75
+ return ret
76
+
77
+ @torch.no_grad()
78
+ def compute_v(self, ret):
79
+ self.vs.append(ret)
80
+ return ret
81
+
82
+ @torch.no_grad()
83
+ def compute_attn_mat(self, ret):
84
+ self.attn_mats.append(ret)
85
+ return ret
86
+
87
+ @torch.no_grad()
88
+ def compute_mlps(self, ret):
89
+ # self.mlps.append(ret[:, 0]) # [b, d]
90
+ self.mlps.append(ret) # [b, d]
91
+ return ret
92
+
93
+ @torch.no_grad()
94
+ def log_post_ln_mean(self, ret):
95
+ self.post_ln_mean = ret # [b, 1]
96
+ return ret
97
+
98
+ @torch.no_grad()
99
+ def log_post_ln_std(self, ret):
100
+ self.post_ln_std = ret # [b, 1]
101
+ return ret
102
+
103
+ def _normalize_mlps(self):
104
+ len_intermediates = self.attentions.shape[1] + self.mlps.shape[1]
105
+ # This is just the normalization layer:
106
+ mean_centered = (
107
+ self.mlps
108
+ - self.post_ln_mean[:, :, np.newaxis].to(self.device) / len_intermediates
109
+ )
110
+ weighted_mean_centered = (
111
+ self.model.visual.ln_post.weight.detach().to(self.device) * mean_centered
112
+ )
113
+ weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[
114
+ :, :, np.newaxis
115
+ ].to(self.device)
116
+ bias_term = (
117
+ self.model.visual.ln_post.bias.detach().to(self.device) / len_intermediates
118
+ )
119
+ post_ln = weighted_mean_by_std + bias_term
120
+ return post_ln @ self.model.visual.proj.detach().to(self.device)
121
+
122
+ def _normalize_attentions_spatial(self):
123
+ len_intermediates = self.attentions.shape[1] + self.mlps.shape[1] # 2*l + 1
124
+ normalization_term = (
125
+ self.attentions.shape[2] * self.attentions.shape[3]
126
+ ) # n * h
127
+ # This is just the normalization layer:
128
+ mean_centered = self.attentions - self.post_ln_mean[
129
+ :, :, np.newaxis, np.newaxis, np.newaxis
130
+ ].to(self.device) / (len_intermediates * normalization_term)
131
+ weighted_mean_centered = (
132
+ self.model.visual.ln_post.weight.detach().to(self.device) * mean_centered
133
+ )
134
+ weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[
135
+ :, :, np.newaxis, np.newaxis, np.newaxis
136
+ ].to(self.device)
137
+ bias_term = self.model.visual.ln_post.bias.detach().to(self.device) / (
138
+ len_intermediates * normalization_term
139
+ )
140
+ post_ln = weighted_mean_by_std + bias_term
141
+ return post_ln @ self.model.visual.proj.detach().to(self.device)
142
+
143
+ def _normalize_attentions_non_spatial(self):
144
+ len_intermediates = self.attentions.shape[1] + self.mlps.shape[1] # 2*l + 1
145
+ normalization_term = self.attentions.shape[2] # h
146
+ # This is just the normalization layer:
147
+ mean_centered = self.attentions - self.post_ln_mean[
148
+ :, :, np.newaxis, np.newaxis
149
+ ].to(self.device) / (len_intermediates * normalization_term)
150
+ weighted_mean_centered = (
151
+ self.model.visual.ln_post.weight.detach().to(self.device) * mean_centered
152
+ )
153
+ weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[
154
+ :, :, np.newaxis, np.newaxis
155
+ ].to(self.device)
156
+ bias_term = self.model.visual.ln_post.bias.detach().to(self.device) / (
157
+ len_intermediates * normalization_term
158
+ )
159
+ post_ln = weighted_mean_by_std + bias_term
160
+ return post_ln @ self.model.visual.proj.detach().to(self.device)
161
+
162
+ @torch.no_grad()
163
+ def finalize(self, representation):
164
+ """We calculate the post-ln scaling, project it and normalize by the last norm."""
165
+ self.attentions = torch.stack(self.attentions, axis=1).to(
166
+ self.device
167
+ ) # [b, l, n, h, d]
168
+ self.mlps = torch.stack(self.mlps, axis=1).to(self.device) # [b, l + 1, d]
169
+ if self.spatial:
170
+ projected_attentions = self._normalize_attentions_spatial()
171
+ else:
172
+ projected_attentions = self._normalize_attentions_non_spatial()
173
+ projected_mlps = self._normalize_mlps()
174
+ norm = representation.norm(dim=-1).detach()
175
+ if self.spatial:
176
+ return (
177
+ projected_attentions
178
+ / norm[:, np.newaxis, np.newaxis, np.newaxis, np.newaxis],
179
+ projected_mlps / norm[:, np.newaxis, np.newaxis],
180
+ )
181
+ return (
182
+ projected_attentions / norm[:, np.newaxis, np.newaxis, np.newaxis],
183
+ projected_mlps / norm[:, np.newaxis, np.newaxis],
184
+ )
185
+
186
+ def reinit(self):
187
+ self.current_layer = 0
188
+ self.attentions = []
189
+ self.mlps = []
190
+ self.ks = []
191
+ self.qs = []
192
+ self.vs = []
193
+ self.attn_mats = []
194
+ self.post_ln_mean = None
195
+ self.post_ln_std = None
196
+ torch.cuda.empty_cache()
197
+
198
+
199
+ def hook_prs_logger(model, device, spatial: bool = True):
200
+ """Hooks a projected residual stream logger to the model."""
201
+ prs = PRSLogger(model, device, spatial=spatial)
202
+ if spatial:
203
+ model.hook_manager.register(
204
+ "visual.transformer.resblocks.*.attn.out.post",
205
+ prs.compute_attentions_spatial,
206
+ )
207
+ else:
208
+ model.hook_manager.register(
209
+ "visual.transformer.resblocks.*.attn.out.post",
210
+ prs.compute_attentions_non_spatial,
211
+ )
212
+ model.hook_manager.register(
213
+ "visual.transformer.resblocks.*.mlp.c_proj.post", prs.compute_mlps
214
+ )
215
+ # model.hook_manager.register("visual.transformer.resblocks.*.attn.in_k.post", prs.compute_k)
216
+ # model.hook_manager.register("visual.transformer.resblocks.*.attn.in_q.post", prs.compute_q)
217
+ # model.hook_manager.register("visual.transformer.resblocks.*.attn.in_v.post", prs.compute_v)
218
+ model.hook_manager.register(
219
+ "visual.transformer.resblocks.*.attn.attention.pre_mask", prs.compute_attn_mat
220
+ )
221
+ model.hook_manager.register("visual.ln_pre_post", prs.compute_mlps)
222
+ model.hook_manager.register("visual.ln_post.mean", prs.log_post_ln_mean)
223
+ model.hook_manager.register("visual.ln_post.sqrt_var", prs.log_post_ln_std)
224
+ return prs
utils/__init__.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
2
+ from utils.factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer, create_loss
3
+ from utils.factory import list_models, add_model_config, get_model_config, load_checkpoint
4
+ from utils.pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, \
5
+ get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained
6
+ from utils.tokenizer import SimpleTokenizer, tokenize, decode
7
+ from utils.transform import image_transform, AugmentationCfg
8
+ from utils.openai_templates import OPENAI_IMAGENET_TEMPLATES
9
+
10
+
11
+ # from DiNOv1
12
+
13
+ # Copyright (c) Facebook, Inc. and its affiliates.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+ """
27
+ Misc functions.
28
+
29
+ Mostly copy-paste from torchvision references or other public repos like DETR:
30
+ https://github.com/facebookresearch/detr/blob/master/util/misc.py
31
+ """
32
+ import os
33
+ import sys
34
+ import time
35
+ import math
36
+ import random
37
+ import datetime
38
+ import subprocess
39
+ from collections import defaultdict, deque
40
+
41
+ import numpy as np
42
+ import torch
43
+ from torch import nn
44
+ import torch.distributed as dist
45
+ from PIL import ImageFilter, ImageOps
46
+
47
+
48
+ class GaussianBlur(object):
49
+ """
50
+ Apply Gaussian Blur to the PIL image.
51
+ """
52
+ def __init__(self, p=0.5, radius_min=0.1, radius_max=2.):
53
+ self.prob = p
54
+ self.radius_min = radius_min
55
+ self.radius_max = radius_max
56
+
57
+ def __call__(self, img):
58
+ do_it = random.random() <= self.prob
59
+ if not do_it:
60
+ return img
61
+
62
+ return img.filter(
63
+ ImageFilter.GaussianBlur(
64
+ radius=random.uniform(self.radius_min, self.radius_max)
65
+ )
66
+ )
67
+
68
+
69
+ class Solarization(object):
70
+ """
71
+ Apply Solarization to the PIL image.
72
+ """
73
+ def __init__(self, p):
74
+ self.p = p
75
+
76
+ def __call__(self, img):
77
+ if random.random() < self.p:
78
+ return ImageOps.solarize(img)
79
+ else:
80
+ return img
81
+
82
+
83
+ def load_pretrained_weights(model, pretrained_weights, checkpoint_key, model_name, patch_size):
84
+ if os.path.isfile(pretrained_weights):
85
+ state_dict = torch.load(pretrained_weights, map_location="cpu")
86
+ if checkpoint_key is not None and checkpoint_key in state_dict:
87
+ print(f"Take key {checkpoint_key} in provided checkpoint dict")
88
+ state_dict = state_dict[checkpoint_key]
89
+ # remove `module.` prefix
90
+ state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
91
+ # remove `backbone.` prefix induced by multicrop wrapper
92
+ state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()}
93
+ msg = model.load_state_dict(state_dict, strict=False)
94
+ print('Pretrained weights found at {} and loaded with msg: {}'.format(pretrained_weights, msg))
95
+ else:
96
+ print("Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate.")
97
+ url = None
98
+ if model_name == "vit_small" and patch_size == 16:
99
+ url = "dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth"
100
+ elif model_name == "vit_small" and patch_size == 8:
101
+ url = "dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth"
102
+ elif model_name == "vit_base" and patch_size == 16:
103
+ url = "dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth"
104
+ elif model_name == "vit_base" and patch_size == 8:
105
+ url = "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth"
106
+ elif model_name == "xcit_small_12_p16":
107
+ url = "dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain.pth"
108
+ elif model_name == "xcit_small_12_p8":
109
+ url = "dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain.pth"
110
+ elif model_name == "xcit_medium_24_p16":
111
+ url = "dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain.pth"
112
+ elif model_name == "xcit_medium_24_p8":
113
+ url = "dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain.pth"
114
+ elif model_name == "resnet50":
115
+ url = "dino_resnet50_pretrain/dino_resnet50_pretrain.pth"
116
+ if url is not None:
117
+ print("Since no pretrained weights have been provided, we load the reference pretrained DINO weights.")
118
+ state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url)
119
+ model.load_state_dict(state_dict, strict=True)
120
+ else:
121
+ print("There is no reference weights available for this model => We use random weights.")
122
+
123
+
124
+ def load_pretrained_linear_weights(linear_classifier, model_name, patch_size):
125
+ url = None
126
+ if model_name == "vit_small" and patch_size == 16:
127
+ url = "dino_deitsmall16_pretrain/dino_deitsmall16_linearweights.pth"
128
+ elif model_name == "vit_small" and patch_size == 8:
129
+ url = "dino_deitsmall8_pretrain/dino_deitsmall8_linearweights.pth"
130
+ elif model_name == "vit_base" and patch_size == 16:
131
+ url = "dino_vitbase16_pretrain/dino_vitbase16_linearweights.pth"
132
+ elif model_name == "vit_base" and patch_size == 8:
133
+ url = "dino_vitbase8_pretrain/dino_vitbase8_linearweights.pth"
134
+ elif model_name == "resnet50":
135
+ url = "dino_resnet50_pretrain/dino_resnet50_linearweights.pth"
136
+ if url is not None:
137
+ print("We load the reference pretrained linear weights.")
138
+ state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url)["state_dict"]
139
+ linear_classifier.load_state_dict(state_dict, strict=True)
140
+ else:
141
+ print("We use random linear weights.")
142
+
143
+
144
+ def clip_gradients(model, clip):
145
+ norms = []
146
+ for name, p in model.named_parameters():
147
+ if p.grad is not None:
148
+ param_norm = p.grad.data.norm(2)
149
+ norms.append(param_norm.item())
150
+ clip_coef = clip / (param_norm + 1e-6)
151
+ if clip_coef < 1:
152
+ p.grad.data.mul_(clip_coef)
153
+ return norms
154
+
155
+
156
+ def cancel_gradients_last_layer(epoch, model, freeze_last_layer):
157
+ if epoch >= freeze_last_layer:
158
+ return
159
+ for n, p in model.named_parameters():
160
+ if "last_layer" in n:
161
+ p.grad = None
162
+
163
+
164
+ def restart_from_checkpoint(ckp_path, run_variables=None, **kwargs):
165
+ """
166
+ Re-start from checkpoint
167
+ """
168
+ if not os.path.isfile(ckp_path):
169
+ return
170
+ print("Found checkpoint at {}".format(ckp_path))
171
+
172
+ # open checkpoint file
173
+ checkpoint = torch.load(ckp_path, map_location="cpu")
174
+
175
+ # key is what to look for in the checkpoint file
176
+ # value is the object to load
177
+ # example: {'state_dict': model}
178
+ for key, value in kwargs.items():
179
+ if key in checkpoint and value is not None:
180
+ try:
181
+ msg = value.load_state_dict(checkpoint[key], strict=False)
182
+ print("=> loaded '{}' from checkpoint '{}' with msg {}".format(key, ckp_path, msg))
183
+ except TypeError:
184
+ try:
185
+ msg = value.load_state_dict(checkpoint[key])
186
+ print("=> loaded '{}' from checkpoint: '{}'".format(key, ckp_path))
187
+ except ValueError:
188
+ print("=> failed to load '{}' from checkpoint: '{}'".format(key, ckp_path))
189
+ else:
190
+ print("=> key '{}' not found in checkpoint: '{}'".format(key, ckp_path))
191
+
192
+ # re load variable important for the run
193
+ if run_variables is not None:
194
+ for var_name in run_variables:
195
+ if var_name in checkpoint:
196
+ run_variables[var_name] = checkpoint[var_name]
197
+
198
+
199
+ def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0):
200
+ warmup_schedule = np.array([])
201
+ warmup_iters = warmup_epochs * niter_per_ep
202
+ if warmup_epochs > 0:
203
+ warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
204
+
205
+ iters = np.arange(epochs * niter_per_ep - warmup_iters)
206
+ schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters)))
207
+
208
+ schedule = np.concatenate((warmup_schedule, schedule))
209
+ assert len(schedule) == epochs * niter_per_ep
210
+ return schedule
211
+
212
+
213
+ def bool_flag(s):
214
+ """
215
+ Parse boolean arguments from the command line.
216
+ """
217
+ FALSY_STRINGS = {"off", "false", "0"}
218
+ TRUTHY_STRINGS = {"on", "true", "1"}
219
+ if s.lower() in FALSY_STRINGS:
220
+ return False
221
+ elif s.lower() in TRUTHY_STRINGS:
222
+ return True
223
+ else:
224
+ raise argparse.ArgumentTypeError("invalid value for a boolean flag")
225
+
226
+
227
+ def fix_random_seeds(seed=31):
228
+ """
229
+ Fix random seeds.
230
+ """
231
+ torch.manual_seed(seed)
232
+ torch.cuda.manual_seed_all(seed)
233
+ np.random.seed(seed)
234
+
235
+
236
+ class SmoothedValue(object):
237
+ """Track a series of values and provide access to smoothed values over a
238
+ window or the global series average.
239
+ """
240
+
241
+ def __init__(self, window_size=20, fmt=None):
242
+ if fmt is None:
243
+ fmt = "{median:.6f} ({global_avg:.6f})"
244
+ self.deque = deque(maxlen=window_size)
245
+ self.total = 0.0
246
+ self.count = 0
247
+ self.fmt = fmt
248
+
249
+ def update(self, value, n=1):
250
+ self.deque.append(value)
251
+ self.count += n
252
+ self.total += value * n
253
+
254
+ def synchronize_between_processes(self):
255
+ """
256
+ Warning: does not synchronize the deque!
257
+ """
258
+ if not is_dist_avail_and_initialized():
259
+ return
260
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
261
+ dist.barrier()
262
+ dist.all_reduce(t)
263
+ t = t.tolist()
264
+ self.count = int(t[0])
265
+ self.total = t[1]
266
+
267
+ @property
268
+ def median(self):
269
+ d = torch.tensor(list(self.deque))
270
+ return d.median().item()
271
+
272
+ @property
273
+ def avg(self):
274
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
275
+ return d.mean().item()
276
+
277
+ @property
278
+ def global_avg(self):
279
+ return self.total / self.count
280
+
281
+ @property
282
+ def max(self):
283
+ return max(self.deque)
284
+
285
+ @property
286
+ def value(self):
287
+ return self.deque[-1]
288
+
289
+ def __str__(self):
290
+ return self.fmt.format(
291
+ median=self.median,
292
+ avg=self.avg,
293
+ global_avg=self.global_avg,
294
+ max=self.max,
295
+ value=self.value)
296
+
297
+
298
+ def reduce_dict(input_dict, average=True):
299
+ """
300
+ Args:
301
+ input_dict (dict): all the values will be reduced
302
+ average (bool): whether to do average or sum
303
+ Reduce the values in the dictionary from all processes so that all processes
304
+ have the averaged results. Returns a dict with the same fields as
305
+ input_dict, after reduction.
306
+ """
307
+ world_size = get_world_size()
308
+ if world_size < 2:
309
+ return input_dict
310
+ with torch.no_grad():
311
+ names = []
312
+ values = []
313
+ # sort the keys so that they are consistent across processes
314
+ for k in sorted(input_dict.keys()):
315
+ names.append(k)
316
+ values.append(input_dict[k])
317
+ values = torch.stack(values, dim=0)
318
+ dist.all_reduce(values)
319
+ if average:
320
+ values /= world_size
321
+ reduced_dict = {k: v for k, v in zip(names, values)}
322
+ return reduced_dict
323
+
324
+
325
+ class MetricLogger(object):
326
+ def __init__(self, delimiter="\t"):
327
+ self.meters = defaultdict(SmoothedValue)
328
+ self.delimiter = delimiter
329
+
330
+ def update(self, **kwargs):
331
+ for k, v in kwargs.items():
332
+ if isinstance(v, torch.Tensor):
333
+ v = v.item()
334
+ assert isinstance(v, (float, int))
335
+ self.meters[k].update(v)
336
+
337
+ def __getattr__(self, attr):
338
+ if attr in self.meters:
339
+ return self.meters[attr]
340
+ if attr in self.__dict__:
341
+ return self.__dict__[attr]
342
+ raise AttributeError("'{}' object has no attribute '{}'".format(
343
+ type(self).__name__, attr))
344
+
345
+ def __str__(self):
346
+ loss_str = []
347
+ for name, meter in self.meters.items():
348
+ loss_str.append(
349
+ "{}: {}".format(name, str(meter))
350
+ )
351
+ return self.delimiter.join(loss_str)
352
+
353
+ def synchronize_between_processes(self):
354
+ for meter in self.meters.values():
355
+ meter.synchronize_between_processes()
356
+
357
+ def add_meter(self, name, meter):
358
+ self.meters[name] = meter
359
+
360
+ def log_every(self, iterable, print_freq, header=None):
361
+ i = 0
362
+ if not header:
363
+ header = ''
364
+ start_time = time.time()
365
+ end = time.time()
366
+ iter_time = SmoothedValue(fmt='{avg:.6f}')
367
+ data_time = SmoothedValue(fmt='{avg:.6f}')
368
+ space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
369
+ if torch.cuda.is_available():
370
+ log_msg = self.delimiter.join([
371
+ header,
372
+ '[{0' + space_fmt + '}/{1}]',
373
+ 'eta: {eta}',
374
+ '{meters}',
375
+ 'time: {time}',
376
+ 'data: {data}',
377
+ 'max mem: {memory:.0f}'
378
+ ])
379
+ else:
380
+ log_msg = self.delimiter.join([
381
+ header,
382
+ '[{0' + space_fmt + '}/{1}]',
383
+ 'eta: {eta}',
384
+ '{meters}',
385
+ 'time: {time}',
386
+ 'data: {data}'
387
+ ])
388
+ MB = 1024.0 * 1024.0
389
+ for obj in iterable:
390
+ data_time.update(time.time() - end)
391
+ yield obj
392
+ iter_time.update(time.time() - end)
393
+ if i % print_freq == 0 or i == len(iterable) - 1:
394
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
395
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
396
+ if torch.cuda.is_available():
397
+ print(log_msg.format(
398
+ i, len(iterable), eta=eta_string,
399
+ meters=str(self),
400
+ time=str(iter_time), data=str(data_time),
401
+ memory=torch.cuda.max_memory_allocated() / MB))
402
+ else:
403
+ print(log_msg.format(
404
+ i, len(iterable), eta=eta_string,
405
+ meters=str(self),
406
+ time=str(iter_time), data=str(data_time)))
407
+ i += 1
408
+ end = time.time()
409
+ total_time = time.time() - start_time
410
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
411
+ print('{} Total time: {} ({:.6f} s / it)'.format(
412
+ header, total_time_str, total_time / len(iterable)))
413
+
414
+
415
+ def get_sha():
416
+ cwd = os.path.dirname(os.path.abspath(__file__))
417
+
418
+ def _run(command):
419
+ return subprocess.check_output(command, cwd=cwd).decode('ascii').strip()
420
+ sha = 'N/A'
421
+ diff = "clean"
422
+ branch = 'N/A'
423
+ try:
424
+ sha = _run(['git', 'rev-parse', 'HEAD'])
425
+ subprocess.check_output(['git', 'diff'], cwd=cwd)
426
+ diff = _run(['git', 'diff-index', 'HEAD'])
427
+ diff = "has uncommited changes" if diff else "clean"
428
+ branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
429
+ except Exception:
430
+ pass
431
+ message = f"sha: {sha}, status: {diff}, branch: {branch}"
432
+ return message
433
+
434
+
435
+ def is_dist_avail_and_initialized():
436
+ if not dist.is_available():
437
+ return False
438
+ if not dist.is_initialized():
439
+ return False
440
+ return True
441
+
442
+
443
+ def get_world_size():
444
+ if not is_dist_avail_and_initialized():
445
+ return 1
446
+ return dist.get_world_size()
447
+
448
+
449
+ def get_rank():
450
+ if not is_dist_avail_and_initialized():
451
+ return 0
452
+ return dist.get_rank()
453
+
454
+
455
+ def is_main_process():
456
+ return get_rank() == 0
457
+
458
+
459
+ def save_on_master(*args, **kwargs):
460
+ if is_main_process():
461
+ torch.save(*args, **kwargs)
462
+
463
+
464
+ def setup_for_distributed(is_master):
465
+ """
466
+ This function disables printing when not in master process
467
+ """
468
+ import builtins as __builtin__
469
+ builtin_print = __builtin__.print
470
+
471
+ def print(*args, **kwargs):
472
+ force = kwargs.pop('force', False)
473
+ if is_master or force:
474
+ builtin_print(*args, **kwargs)
475
+
476
+ __builtin__.print = print
477
+
478
+
479
+ def init_distributed_mode(args):
480
+ # launched with torch.distributed.launch
481
+ if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
482
+ args.rank = int(os.environ["RANK"])
483
+ args.world_size = int(os.environ['WORLD_SIZE'])
484
+ args.gpu = int(os.environ['LOCAL_RANK'])
485
+ # launched with submitit on a slurm cluster
486
+ elif 'SLURM_PROCID' in os.environ:
487
+ args.rank = int(os.environ['SLURM_PROCID'])
488
+ args.gpu = args.rank % torch.cuda.device_count()
489
+ # launched naively with `python main_dino.py`
490
+ # we manually add MASTER_ADDR and MASTER_PORT to env variables
491
+ elif torch.cuda.is_available():
492
+ print('Will run the code on one GPU.')
493
+ args.rank, args.gpu, args.world_size = 0, 0, 1
494
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
495
+ os.environ['MASTER_PORT'] = '29500'
496
+ else:
497
+ print('Does not support training without GPU.')
498
+ sys.exit(1)
499
+
500
+ dist.init_process_group(
501
+ backend="nccl",
502
+ init_method=args.dist_url,
503
+ world_size=args.world_size,
504
+ rank=args.rank,
505
+ )
506
+
507
+ torch.cuda.set_device(args.gpu)
508
+ print('| distributed init (rank {}): {}'.format(
509
+ args.rank, args.dist_url), flush=True)
510
+ dist.barrier()
511
+ setup_for_distributed(args.rank == 0)
512
+
513
+
514
+ def accuracy(output, target, topk=(1,)):
515
+ """Computes the accuracy over the k top predictions for the specified values of k"""
516
+ maxk = max(topk)
517
+ batch_size = target.size(0)
518
+ _, pred = output.topk(maxk, 1, True, True)
519
+ pred = pred.t()
520
+ correct = pred.eq(target.reshape(1, -1).expand_as(pred))
521
+ return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
522
+
523
+
524
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
525
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
526
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
527
+ def norm_cdf(x):
528
+ # Computes standard normal cumulative distribution function
529
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
530
+
531
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
532
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
533
+ "The distribution of values may be incorrect.",
534
+ stacklevel=2)
535
+
536
+ with torch.no_grad():
537
+ # Values are generated by using a truncated uniform distribution and
538
+ # then using the inverse CDF for the normal distribution.
539
+ # Get upper and lower cdf values
540
+ l = norm_cdf((a - mean) / std)
541
+ u = norm_cdf((b - mean) / std)
542
+
543
+ # Uniformly fill tensor with values from [l, u], then translate to
544
+ # [2l-1, 2u-1].
545
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
546
+
547
+ # Use inverse cdf transform for normal distribution to get truncated
548
+ # standard normal
549
+ tensor.erfinv_()
550
+
551
+ # Transform to proper mean, std
552
+ tensor.mul_(std * math.sqrt(2.))
553
+ tensor.add_(mean)
554
+
555
+ # Clamp to ensure it's in the proper range
556
+ tensor.clamp_(min=a, max=b)
557
+ return tensor
558
+
559
+
560
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
561
+ # type: (Tensor, float, float, float, float) -> Tensor
562
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
563
+
564
+
565
+ class LARS(torch.optim.Optimizer):
566
+ """
567
+ Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py
568
+ """
569
+ def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, eta=0.001,
570
+ weight_decay_filter=None, lars_adaptation_filter=None):
571
+ defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum,
572
+ eta=eta, weight_decay_filter=weight_decay_filter,
573
+ lars_adaptation_filter=lars_adaptation_filter)
574
+ super().__init__(params, defaults)
575
+
576
+ @torch.no_grad()
577
+ def step(self):
578
+ for g in self.param_groups:
579
+ for p in g['params']:
580
+ dp = p.grad
581
+
582
+ if dp is None:
583
+ continue
584
+
585
+ if p.ndim != 1:
586
+ dp = dp.add(p, alpha=g['weight_decay'])
587
+
588
+ if p.ndim != 1:
589
+ param_norm = torch.norm(p)
590
+ update_norm = torch.norm(dp)
591
+ one = torch.ones_like(param_norm)
592
+ q = torch.where(param_norm > 0.,
593
+ torch.where(update_norm > 0,
594
+ (g['eta'] * param_norm / update_norm), one), one)
595
+ dp = dp.mul(q)
596
+
597
+ param_state = self.state[p]
598
+ if 'mu' not in param_state:
599
+ param_state['mu'] = torch.zeros_like(p)
600
+ mu = param_state['mu']
601
+ mu.mul_(g['momentum']).add_(dp)
602
+
603
+ p.add_(mu, alpha=-g['lr'])
604
+
605
+
606
+ class MultiCropWrapper(nn.Module):
607
+ """
608
+ Perform forward pass separately on each resolution input.
609
+ The inputs corresponding to a single resolution are clubbed and single
610
+ forward is run on the same resolution inputs. Hence we do several
611
+ forward passes = number of different resolutions used. We then
612
+ concatenate all the output features and run the head forward on these
613
+ concatenated features.
614
+ """
615
+ def __init__(self, backbone, head):
616
+ super(MultiCropWrapper, self).__init__()
617
+ # disable layers dedicated to ImageNet labels classification
618
+ backbone.fc, backbone.head = nn.Identity(), nn.Identity()
619
+ self.backbone = backbone
620
+ self.head = head
621
+
622
+ def forward(self, x):
623
+ # convert to list
624
+ if not isinstance(x, list):
625
+ x = [x]
626
+ idx_crops = torch.cumsum(torch.unique_consecutive(
627
+ torch.tensor([inp.shape[-1] for inp in x]),
628
+ return_counts=True,
629
+ )[1], 0)
630
+ start_idx, output = 0, torch.empty(0).to(x[0].device)
631
+ for end_idx in idx_crops:
632
+ _out = self.backbone(torch.cat(x[start_idx: end_idx]))
633
+ # The output is a tuple with XCiT model. See:
634
+ # https://github.com/facebookresearch/xcit/blob/master/xcit.py#L404-L405
635
+ if isinstance(_out, tuple):
636
+ _out = _out[0]
637
+ # accumulate outputs
638
+ output = torch.cat((output, _out))
639
+ start_idx = end_idx
640
+ # Run the head forward on the concatenated features.
641
+ return self.head(output)
642
+
643
+
644
+ def get_params_groups(model):
645
+ regularized = []
646
+ not_regularized = []
647
+ for name, param in model.named_parameters():
648
+ if not param.requires_grad:
649
+ continue
650
+ # we do not regularize biases nor Norm parameters
651
+ if name.endswith(".bias") or len(param.shape) == 1:
652
+ not_regularized.append(param)
653
+ else:
654
+ regularized.append(param)
655
+ return [{'params': regularized}, {'params': not_regularized, 'weight_decay': 0.}]
656
+
657
+
658
+ def has_batchnorms(model):
659
+ bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)
660
+ for name, module in model.named_modules():
661
+ if isinstance(module, bn_types):
662
+ return True
663
+ return False
664
+
665
+
666
+ class PCA():
667
+ """
668
+ Class to compute and apply PCA.
669
+ """
670
+ def __init__(self, dim=256, whit=0.5):
671
+ self.dim = dim
672
+ self.whit = whit
673
+ self.mean = None
674
+
675
+ def train_pca(self, cov):
676
+ """
677
+ Takes a covariance matrix (np.ndarray) as input.
678
+ """
679
+ d, v = np.linalg.eigh(cov)
680
+ eps = d.max() * 1e-5
681
+ n_0 = (d < eps).sum()
682
+ if n_0 > 0:
683
+ d[d < eps] = eps
684
+
685
+ # total energy
686
+ totenergy = d.sum()
687
+
688
+ # sort eigenvectors with eigenvalues order
689
+ idx = np.argsort(d)[::-1][:self.dim]
690
+ d = d[idx]
691
+ v = v[:, idx]
692
+
693
+ print("keeping %.2f %% of the energy" % (d.sum() / totenergy * 100.0))
694
+
695
+ # for the whitening
696
+ d = np.diag(1. / d**self.whit)
697
+
698
+ # principal components
699
+ self.dvt = np.dot(d, v.T)
700
+
701
+ def apply(self, x):
702
+ # input is from numpy
703
+ if isinstance(x, np.ndarray):
704
+ if self.mean is not None:
705
+ x -= self.mean
706
+ return np.dot(self.dvt, x.T).T
707
+
708
+ # input is from torch and is on GPU
709
+ if x.is_cuda:
710
+ if self.mean is not None:
711
+ x -= torch.cuda.FloatTensor(self.mean)
712
+ return torch.mm(torch.cuda.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1)
713
+
714
+ # input if from torch, on CPU
715
+ if self.mean is not None:
716
+ x -= torch.FloatTensor(self.mean)
717
+ return torch.mm(torch.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1)
718
+
719
+
720
+ def compute_ap(ranks, nres):
721
+ """
722
+ Computes average precision for given ranked indexes.
723
+ Arguments
724
+ ---------
725
+ ranks : zerro-based ranks of positive images
726
+ nres : number of positive images
727
+ Returns
728
+ -------
729
+ ap : average precision
730
+ """
731
+
732
+ # number of images ranked by the system
733
+ nimgranks = len(ranks)
734
+
735
+ # accumulate trapezoids in PR-plot
736
+ ap = 0
737
+
738
+ recall_step = 1. / nres
739
+
740
+ for j in np.arange(nimgranks):
741
+ rank = ranks[j]
742
+
743
+ if rank == 0:
744
+ precision_0 = 1.
745
+ else:
746
+ precision_0 = float(j) / rank
747
+
748
+ precision_1 = float(j + 1) / (rank + 1)
749
+
750
+ ap += (precision_0 + precision_1) * recall_step / 2.
751
+
752
+ return ap
753
+
754
+
755
+ def compute_map(ranks, gnd, kappas=[]):
756
+ """
757
+ Computes the mAP for a given set of returned results.
758
+ Usage:
759
+ map = compute_map (ranks, gnd)
760
+ computes mean average precsion (map) only
761
+ map, aps, pr, prs = compute_map (ranks, gnd, kappas)
762
+ computes mean average precision (map), average precision (aps) for each query
763
+ computes mean precision at kappas (pr), precision at kappas (prs) for each query
764
+ Notes:
765
+ 1) ranks starts from 0, ranks.shape = db_size X #queries
766
+ 2) The junk results (e.g., the query itself) should be declared in the gnd stuct array
767
+ 3) If there are no positive images for some query, that query is excluded from the evaluation
768
+ """
769
+
770
+ map = 0.
771
+ nq = len(gnd) # number of queries
772
+ aps = np.zeros(nq)
773
+ pr = np.zeros(len(kappas))
774
+ prs = np.zeros((nq, len(kappas)))
775
+ nempty = 0
776
+
777
+ for i in np.arange(nq):
778
+ qgnd = np.array(gnd[i]['ok'])
779
+
780
+ # no positive images, skip from the average
781
+ if qgnd.shape[0] == 0:
782
+ aps[i] = float('nan')
783
+ prs[i, :] = float('nan')
784
+ nempty += 1
785
+ continue
786
+
787
+ try:
788
+ qgndj = np.array(gnd[i]['junk'])
789
+ except:
790
+ qgndj = np.empty(0)
791
+
792
+ # sorted positions of positive and junk images (0 based)
793
+ pos = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgnd)]
794
+ junk = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgndj)]
795
+
796
+ k = 0;
797
+ ij = 0;
798
+ if len(junk):
799
+ # decrease positions of positives based on the number of
800
+ # junk images appearing before them
801
+ ip = 0
802
+ while (ip < len(pos)):
803
+ while (ij < len(junk) and pos[ip] > junk[ij]):
804
+ k += 1
805
+ ij += 1
806
+ pos[ip] = pos[ip] - k
807
+ ip += 1
808
+
809
+ # compute ap
810
+ ap = compute_ap(pos, len(qgnd))
811
+ map = map + ap
812
+ aps[i] = ap
813
+
814
+ # compute precision @ k
815
+ pos += 1 # get it to 1-based
816
+ for j in np.arange(len(kappas)):
817
+ kq = min(max(pos), kappas[j]);
818
+ prs[i, j] = (pos <= kq).sum() / kq
819
+ pr = pr + prs[i, :]
820
+
821
+ map = map / (nq - nempty)
822
+ pr = pr / (nq - nempty)
823
+
824
+ return map, aps, pr, prs
825
+
826
+
827
+ def multi_scale(samples, model):
828
+ v = None
829
+ for s in [1, 1/2**(1/2), 1/2]: # we use 3 different scales
830
+ if s == 1:
831
+ inp = samples.clone()
832
+ else:
833
+ inp = nn.functional.interpolate(samples, scale_factor=s, mode='bilinear', align_corners=False)
834
+ feats = model(inp).clone()
835
+ if v is None:
836
+ v = feats
837
+ else:
838
+ v += feats
839
+ v /= 3
840
+ v /= v.norm()
841
+ return v
utils/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (25.3 kB). View file
 
utils/__pycache__/constants.cpython-38.pyc ADDED
Binary file (245 Bytes). View file
 
utils/__pycache__/factory.cpython-38.pyc ADDED
Binary file (9.55 kB). View file
 
utils/__pycache__/hook.cpython-38.pyc ADDED
Binary file (3.73 kB). View file
 
utils/__pycache__/imagenet_segmentation.cpython-38.pyc ADDED
Binary file (1.62 kB). View file
 
utils/__pycache__/misc.cpython-38.pyc ADDED
Binary file (4.04 kB). View file
 
utils/__pycache__/model.cpython-38.pyc ADDED
Binary file (11.6 kB). View file
 
utils/__pycache__/modified_resnet.cpython-38.pyc ADDED
Binary file (6.28 kB). View file
 
utils/__pycache__/openai_models.cpython-38.pyc ADDED
Binary file (2.78 kB). View file
 
utils/__pycache__/openai_templates.cpython-38.pyc ADDED
Binary file (9.51 kB). View file
 
utils/__pycache__/pretrained.cpython-38.pyc ADDED
Binary file (14.1 kB). View file
 
utils/__pycache__/segmentation_utils.cpython-38.pyc ADDED
Binary file (20.2 kB). View file
 
utils/__pycache__/timm_model.cpython-38.pyc ADDED
Binary file (4.04 kB). View file
 
utils/__pycache__/tokenizer.cpython-38.pyc ADDED
Binary file (8.78 kB). View file
 
utils/__pycache__/transform.cpython-38.pyc ADDED
Binary file (4.14 kB). View file
 
utils/__pycache__/transformer.cpython-38.pyc ADDED
Binary file (25.8 kB). View file
 
utils/__pycache__/visualization.cpython-38.pyc ADDED
Binary file (870 Bytes). View file
 
utils/binary_waterbirds.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path
3
+ from typing import Any, Callable, cast, Dict, List, Optional, Tuple
4
+ from typing import Union
5
+
6
+ from PIL import Image
7
+ import pandas as pd
8
+ from torchvision.datasets import VisionDataset
9
+ import torch
10
+
11
+
12
+ def pil_loader(path: str) -> Image.Image:
13
+ # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
14
+ with open(path, "rb") as f:
15
+ img = Image.open(f)
16
+ return img.convert("RGB")
17
+
18
+ class BinaryWaterbirds(VisionDataset):
19
+ def __init__(
20
+ self,
21
+ root: str,
22
+ split: str,
23
+ loader: Callable[[str], Any] = pil_loader,
24
+ transform: Optional[Callable] = None,
25
+ target_transform: Optional[Callable] = None,
26
+ ) -> None:
27
+ super().__init__(root, transform=transform, target_transform=target_transform)
28
+
29
+ self.loader = loader
30
+ csv = pd.read_csv(os.path.join(root, 'metadata.csv'))
31
+ split = {'test': 2, 'valid': 1, 'train': 0}[split]
32
+ csv = csv[csv['split'] == split]
33
+ self.samples = [(os.path.join(root, csv.iloc[i]['img_filename']), csv.iloc[i]['y']) for i in range(len(csv))]
34
+
35
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
36
+ """
37
+ Args:
38
+ index (int): Index
39
+ Returns:
40
+ tuple: (sample, target) where target is class_index of the target class.
41
+ """
42
+ path, target = self.samples[index]
43
+ sample = self.loader(path)
44
+ if self.transform is not None:
45
+ sample = self.transform(sample)
46
+ if self.target_transform is not None:
47
+ target = self.target_transform(target)
48
+
49
+ return sample, target
50
+
51
+ def __len__(self) -> int:
52
+ return len(self.samples)
utils/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)
utils/cub_classes.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ cub_classes = ['Black footed Albatross', 'Laysan Albatross', 'Sooty Albatross', 'Groove billed Ani', 'Crested Auklet', 'Least Auklet', 'Parakeet Auklet', 'Rhinoceros Auklet', 'Brewer Blackbird', 'Red winged Blackbird', 'Rusty Blackbird', 'Yellow headed Blackbird', 'Bobolink', 'Indigo Bunting', 'Lazuli Bunting', 'Painted Bunting', 'Cardinal', 'Spotted Catbird', 'Gray Catbird', 'Yellow breasted Chat', 'Eastern Towhee', 'Chuck will Widow', 'Brandt Cormorant', 'Red faced Cormorant', 'Pelagic Cormorant', 'Bronzed Cowbird', 'Shiny Cowbird', 'Brown Creeper', 'American Crow', 'Fish Crow', 'Black billed Cuckoo', 'Mangrove Cuckoo', 'Yellow billed Cuckoo', 'Gray crowned Rosy Finch', 'Purple Finch', 'Northern Flicker', 'Acadian Flycatcher', 'Great Crested Flycatcher', 'Least Flycatcher', 'Olive sided Flycatcher', 'Scissor tailed Flycatcher', 'Vermilion Flycatcher', 'Yellow bellied Flycatcher', 'Frigatebird', 'Northern Fulmar', 'Gadwall', 'American Goldfinch', 'European Goldfinch', 'Boat tailed Grackle', 'Eared Grebe', 'Horned Grebe', 'Pied billed Grebe', 'Western Grebe', 'Blue Grosbeak', 'Evening Grosbeak', 'Pine Grosbeak', 'Rose breasted Grosbeak', 'Pigeon Guillemot', 'California Gull', 'Glaucous winged Gull', 'Heermann Gull', 'Herring Gull', 'Ivory Gull', 'Ring billed Gull', 'Slaty backed Gull', 'Western Gull', 'Anna Hummingbird', 'Ruby throated Hummingbird', 'Rufous Hummingbird', 'Green Violetear', 'Long tailed Jaeger', 'Pomarine Jaeger', 'Blue Jay', 'Florida Jay', 'Green Jay', 'Dark eyed Junco', 'Tropical Kingbird', 'Gray Kingbird', 'Belted Kingfisher', 'Green Kingfisher', 'Pied Kingfisher', 'Ringed Kingfisher', 'White breasted Kingfisher', 'Red legged Kittiwake', 'Horned Lark', 'Pacific Loon', 'Mallard', 'Western Meadowlark', 'Hooded Merganser', 'Red breasted Merganser', 'Mockingbird', 'Nighthawk', 'Clark Nutcracker', 'White breasted Nuthatch', 'Baltimore Oriole', 'Hooded Oriole', 'Orchard Oriole', 'Scott Oriole', 'Ovenbird', 'Brown Pelican', 'White Pelican', 'Western Wood Pewee', 'Sayornis', 'American Pipit', 'Whip poor Will', 'Horned Puffin', 'Common Raven', 'White necked Raven', 'American Redstart', 'Geococcyx', 'Loggerhead Shrike', 'Great Grey Shrike', 'Baird Sparrow', 'Black throated Sparrow', 'Brewer Sparrow', 'Chipping Sparrow', 'Clay colored Sparrow', 'House Sparrow', 'Field Sparrow', 'Fox Sparrow', 'Grasshopper Sparrow', 'Harris Sparrow', 'Henslow Sparrow', 'Le Conte Sparrow', 'Lincoln Sparrow', 'Nelson Sharp tailed Sparrow', 'Savannah Sparrow', 'Seaside Sparrow', 'Song Sparrow', 'Tree Sparrow', 'Vesper Sparrow', 'White crowned Sparrow', 'White throated Sparrow', 'Cape Glossy Starling', 'Bank Swallow', 'Barn Swallow', 'Cliff Swallow', 'Tree Swallow', 'Scarlet Tanager', 'Summer Tanager', 'Artic Tern', 'Black Tern', 'Caspian Tern', 'Common Tern', 'Elegant Tern', 'Forsters Tern', 'Least Tern', 'Green tailed Towhee', 'Brown Thrasher', 'Sage Thrasher', 'Black capped Vireo', 'Blue headed Vireo', 'Philadelphia Vireo', 'Red eyed Vireo', 'Warbling Vireo', 'White eyed Vireo', 'Yellow throated Vireo', 'Bay breasted Warbler', 'Black and white Warbler', 'Black throated Blue Warbler', 'Blue winged Warbler', 'Canada Warbler', 'Cape May Warbler', 'Cerulean Warbler', 'Chestnut sided Warbler', 'Golden winged Warbler', 'Hooded Warbler', 'Kentucky Warbler', 'Magnolia Warbler', 'Mourning Warbler', 'Myrtle Warbler', 'Nashville Warbler', 'Orange crowned Warbler', 'Palm Warbler', 'Pine Warbler', 'Prairie Warbler', 'Prothonotary Warbler', 'Swainson Warbler', 'Tennessee Warbler', 'Wilson Warbler', 'Worm eating Warbler', 'Yellow Warbler', 'Northern Waterthrush', 'Louisiana Waterthrush', 'Bohemian Waxwing', 'Cedar Waxwing', 'American Three toed Woodpecker', 'Pileated Woodpecker', 'Red bellied Woodpecker', 'Red cockaded Woodpecker', 'Red headed Woodpecker', 'Downy Woodpecker', 'Bewick Wren', 'Cactus Wren', 'Carolina Wren', 'House Wren', 'Marsh Wren', 'Rock Wren', 'Winter Wren', 'Common Yellowthroat']
2
+ waterbird_classes = ['landbird', 'waterbird']
utils/factory.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Any, Dict, Optional, Tuple, Union
9
+
10
+ import torch
11
+
12
+ from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
13
+ from utils.model import CLIP, convert_to_custom_text_state_dict,\
14
+ resize_pos_embed, get_cast_dtype
15
+ from utils.openai_models import load_openai_model
16
+ from utils.pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained,\
17
+ list_pretrained_tags_by_model, download_pretrained_from_hf
18
+ from utils.transform import image_transform, AugmentationCfg
19
+ from utils.tokenizer import HFTokenizer, tokenize
20
+
21
+
22
+ HF_HUB_PREFIX = 'hf-hub:'
23
+ _MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
24
+ _MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
25
+
26
+
27
+ def _natural_key(string_):
28
+ return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())]
29
+
30
+
31
+ def _rescan_model_configs():
32
+ global _MODEL_CONFIGS
33
+
34
+ config_ext = ('.json',)
35
+ config_files = []
36
+ for config_path in _MODEL_CONFIG_PATHS:
37
+ if config_path.is_file() and config_path.suffix in config_ext:
38
+ config_files.append(config_path)
39
+ elif config_path.is_dir():
40
+ for ext in config_ext:
41
+ config_files.extend(config_path.glob(f'*{ext}'))
42
+
43
+ for cf in config_files:
44
+ with open(cf, 'r') as f:
45
+ model_cfg = json.load(f)
46
+ if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')):
47
+ _MODEL_CONFIGS[cf.stem] = model_cfg
48
+
49
+ _MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))}
50
+
51
+
52
+ _rescan_model_configs() # initial populate of model config registry
53
+
54
+
55
+ def list_models():
56
+ """ enumerate available model architectures based on config files """
57
+ return list(_MODEL_CONFIGS.keys())
58
+
59
+
60
+ def add_model_config(path):
61
+ """ add model config path or file and update registry """
62
+ if not isinstance(path, Path):
63
+ path = Path(path)
64
+ _MODEL_CONFIG_PATHS.append(path)
65
+ _rescan_model_configs()
66
+
67
+
68
+ def get_model_config(model_name):
69
+ if model_name in _MODEL_CONFIGS:
70
+ return deepcopy(_MODEL_CONFIGS[model_name])
71
+ else:
72
+ return None
73
+
74
+
75
+ def get_tokenizer(model_name):
76
+ if model_name.startswith(HF_HUB_PREFIX):
77
+ tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):])
78
+ else:
79
+ config = get_model_config(model_name)
80
+ tokenizer = HFTokenizer(
81
+ config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize
82
+ return tokenizer
83
+
84
+
85
+ def load_state_dict(checkpoint_path: str, map_location='cpu'):
86
+ checkpoint = torch.load(checkpoint_path, map_location=map_location)
87
+ if isinstance(checkpoint, dict) and 'state_dict' in checkpoint:
88
+ state_dict = checkpoint['state_dict']
89
+ else:
90
+ state_dict = checkpoint
91
+ if next(iter(state_dict.items()))[0].startswith('module'):
92
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
93
+ return state_dict
94
+
95
+
96
+ def load_checkpoint(model, checkpoint_path, strict=True):
97
+ state_dict = load_state_dict(checkpoint_path)
98
+ # detect old format and make compatible with new format
99
+ if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'):
100
+ state_dict = convert_to_custom_text_state_dict(state_dict)
101
+ resize_pos_embed(state_dict, model)
102
+ incompatible_keys = model.load_state_dict(state_dict, strict=strict)
103
+ return incompatible_keys
104
+
105
+
106
+ def create_model(
107
+ model_name: str,
108
+ pretrained: Optional[str] = None,
109
+ precision: str = 'fp32',
110
+ device: Union[str, torch.device] = 'cpu',
111
+ jit: bool = False,
112
+ force_quick_gelu: bool = False,
113
+ force_custom_text: bool = False,
114
+ force_patch_dropout: Optional[float] = None,
115
+ force_image_size: Optional[Union[int, Tuple[int, int]]] = None,
116
+ pretrained_image: bool = False,
117
+ pretrained_hf: bool = True,
118
+ cache_dir: Optional[str] = None,
119
+ output_dict: Optional[bool] = None,
120
+ require_pretrained: bool = False,
121
+ ):
122
+ has_hf_hub_prefix = model_name.startswith(HF_HUB_PREFIX)
123
+ if has_hf_hub_prefix:
124
+ model_id = model_name[len(HF_HUB_PREFIX):]
125
+ checkpoint_path = download_pretrained_from_hf(model_id, cache_dir=cache_dir)
126
+ config_path = download_pretrained_from_hf(model_id, filename='open_clip_config.json', cache_dir=cache_dir)
127
+
128
+ with open(config_path, 'r', encoding='utf-8') as f:
129
+ config = json.load(f)
130
+ pretrained_cfg = config['preprocess_cfg']
131
+ model_cfg = config['model_cfg']
132
+ else:
133
+ model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names
134
+ checkpoint_path = None
135
+ pretrained_cfg = {}
136
+ model_cfg = None
137
+
138
+ if isinstance(device, str):
139
+ device = torch.device(device)
140
+
141
+ if pretrained and pretrained.lower() == 'openai':
142
+ logging.info(f'Loading pretrained {model_name} from OpenAI.')
143
+ model = load_openai_model(
144
+ model_name,
145
+ precision=precision,
146
+ device=device,
147
+ cache_dir=cache_dir,
148
+ )
149
+ else:
150
+ model_cfg = model_cfg or get_model_config(model_name)
151
+ if model_cfg is not None:
152
+ logging.info(f'Loaded {model_name} model config.')
153
+ else:
154
+ logging.error(f'Model config for {model_name} not found; available models {list_models()}.')
155
+ raise RuntimeError(f'Model config for {model_name} not found.')
156
+
157
+ if force_quick_gelu:
158
+ # override for use of QuickGELU on non-OpenAI transformer models
159
+ model_cfg["quick_gelu"] = True
160
+
161
+ if force_patch_dropout is not None:
162
+ # override the default patch dropout value
163
+ model_cfg["vision_cfg"]["patch_dropout"] = force_patch_dropout
164
+
165
+ if force_image_size is not None:
166
+ # override model config's image size
167
+ model_cfg["vision_cfg"]["image_size"] = force_image_size
168
+
169
+ is_timm_model = 'timm_model_name' in model_cfg.get('vision_cfg', {})
170
+ if pretrained_image:
171
+ if is_timm_model:
172
+ # pretrained weight loading for timm models set via vision_cfg
173
+ model_cfg['vision_cfg']['timm_model_pretrained'] = True
174
+ else:
175
+ assert False, 'pretrained image towers currently only supported for timm models'
176
+
177
+ # cast_dtype set for fp16 and bf16 (manual mixed-precision), not set for 'amp' or 'pure' modes
178
+ cast_dtype = get_cast_dtype(precision)
179
+ is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {})
180
+ custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model
181
+
182
+ if custom_text:
183
+ if is_hf_model:
184
+ model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf
185
+ if "coca" in model_name:
186
+ raise ValueError('Coca is not implemented')
187
+ model = CoCa(**model_cfg, cast_dtype=cast_dtype)
188
+ else:
189
+ raise ValueError('CustomTextCLIP is not implemented')
190
+ model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype)
191
+ else:
192
+ model = CLIP(**model_cfg, cast_dtype=cast_dtype)
193
+
194
+ if precision in ("fp16", "bf16"):
195
+ dtype = torch.float16 if 'fp16' in precision else torch.bfloat16
196
+ # manual mixed precision that matches original OpenAI behaviour
197
+ if is_timm_model:
198
+ # FIXME this is a bit janky, create timm based model in low-precision and
199
+ # then cast only LayerNormFp32 instances back to float32 so they don't break.
200
+ # Why? The convert_weights_to_lp fn only works with native models.
201
+ model.to(device=device, dtype=dtype)
202
+ from transformer import LayerNormFp32
203
+ def _convert_ln(m):
204
+ if isinstance(m, LayerNormFp32):
205
+ m.weight.data = m.weight.data.to(torch.float32)
206
+ m.bias.data = m.bias.data.to(torch.float32)
207
+ model.apply(_convert_ln)
208
+ else:
209
+ model.to(device=device)
210
+ convert_weights_to_lp(model, dtype=dtype)
211
+ elif precision in ("pure_fp16", "pure_bf16"):
212
+ dtype = torch.float16 if 'fp16' in precision else torch.bfloat16
213
+ model.to(device=device, dtype=dtype)
214
+ else:
215
+ model.to(device=device)
216
+
217
+ pretrained_loaded = False
218
+ if pretrained:
219
+ checkpoint_path = ''
220
+ pretrained_cfg = get_pretrained_cfg(model_name, pretrained)
221
+ if pretrained_cfg:
222
+ checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir)
223
+ elif os.path.exists(pretrained):
224
+ checkpoint_path = pretrained
225
+
226
+ if checkpoint_path:
227
+ logging.info(f'Loading pretrained {model_name} weights ({pretrained}).')
228
+ load_checkpoint(model, checkpoint_path)
229
+ else:
230
+ error_str = (
231
+ f'Pretrained weights ({pretrained}) not found for model {model_name}.'
232
+ f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.')
233
+ logging.warning(error_str)
234
+ raise RuntimeError(error_str)
235
+ pretrained_loaded = True
236
+ elif has_hf_hub_prefix:
237
+ logging.info(f'Loading pretrained {model_name} weights ({pretrained}).')
238
+ load_checkpoint(model, checkpoint_path)
239
+ pretrained_loaded = True
240
+
241
+ if require_pretrained and not pretrained_loaded:
242
+ # callers of create_model_from_pretrained always expect pretrained weights
243
+ raise RuntimeError(
244
+ f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.')
245
+
246
+ # set image / mean metadata from pretrained_cfg if available, or use default
247
+ model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN
248
+ model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD
249
+
250
+ if output_dict and hasattr(model, "output_dict"):
251
+ model.output_dict = True
252
+
253
+ if jit:
254
+ model = torch.jit.script(model)
255
+
256
+ return model
257
+
258
+
259
+ def create_loss(args):
260
+ if args.distill:
261
+ return DistillClipLoss(
262
+ local_loss=args.local_loss,
263
+ gather_with_grad=args.gather_with_grad,
264
+ cache_labels=True,
265
+ rank=args.rank,
266
+ world_size=args.world_size,
267
+ use_horovod=args.horovod,
268
+ )
269
+ elif "coca" in args.model.lower():
270
+ return CoCaLoss(
271
+ caption_loss_weight=args.coca_caption_loss_weight,
272
+ clip_loss_weight=args.coca_contrastive_loss_weight,
273
+ local_loss=args.local_loss,
274
+ gather_with_grad=args.gather_with_grad,
275
+ cache_labels=True,
276
+ rank=args.rank,
277
+ world_size=args.world_size,
278
+ use_horovod=args.horovod,
279
+ )
280
+ return ClipLoss(
281
+ local_loss=args.local_loss,
282
+ gather_with_grad=args.gather_with_grad,
283
+ cache_labels=True,
284
+ rank=args.rank,
285
+ world_size=args.world_size,
286
+ use_horovod=args.horovod,
287
+ )
288
+
289
+
290
+ def create_model_and_transforms(
291
+ model_name: str,
292
+ pretrained: Optional[str] = None,
293
+ precision: str = 'fp32',
294
+ device: Union[str, torch.device] = 'cpu',
295
+ jit: bool = False,
296
+ force_quick_gelu: bool = False,
297
+ force_custom_text: bool = False,
298
+ force_patch_dropout: Optional[float] = None,
299
+ force_image_size: Optional[Union[int, Tuple[int, int]]] = None,
300
+ pretrained_image: bool = False,
301
+ pretrained_hf: bool = True,
302
+ image_mean: Optional[Tuple[float, ...]] = None,
303
+ image_std: Optional[Tuple[float, ...]] = None,
304
+ aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None,
305
+ cache_dir: Optional[str] = None,
306
+ output_dict: Optional[bool] = None,
307
+ ):
308
+ model = create_model(
309
+ model_name,
310
+ pretrained,
311
+ precision=precision,
312
+ device=device,
313
+ jit=jit,
314
+ force_quick_gelu=force_quick_gelu,
315
+ force_custom_text=force_custom_text,
316
+ force_patch_dropout=force_patch_dropout,
317
+ force_image_size=force_image_size,
318
+ pretrained_image=pretrained_image,
319
+ pretrained_hf=pretrained_hf,
320
+ cache_dir=cache_dir,
321
+ output_dict=output_dict,
322
+ )
323
+
324
+ image_mean = image_mean or getattr(model.visual, 'image_mean', None)
325
+ image_std = image_std or getattr(model.visual, 'image_std', None)
326
+ preprocess_train = image_transform(
327
+ model.visual.image_size,
328
+ is_train=True,
329
+ mean=image_mean,
330
+ std=image_std,
331
+ aug_cfg=aug_cfg,
332
+ )
333
+ preprocess_val = image_transform(
334
+ model.visual.image_size,
335
+ is_train=False,
336
+ mean=image_mean,
337
+ std=image_std,
338
+ )
339
+
340
+ return model, preprocess_train, preprocess_val
341
+
342
+
343
+ def create_model_from_pretrained(
344
+ model_name: str,
345
+ pretrained: Optional[str] = None,
346
+ precision: str = 'fp32',
347
+ device: Union[str, torch.device] = 'cpu',
348
+ jit: bool = False,
349
+ force_quick_gelu: bool = False,
350
+ force_custom_text: bool = False,
351
+ force_image_size: Optional[Union[int, Tuple[int, int]]] = None,
352
+ return_transform: bool = True,
353
+ image_mean: Optional[Tuple[float, ...]] = None,
354
+ image_std: Optional[Tuple[float, ...]] = None,
355
+ cache_dir: Optional[str] = None,
356
+ ):
357
+ model = create_model(
358
+ model_name,
359
+ pretrained,
360
+ precision=precision,
361
+ device=device,
362
+ jit=jit,
363
+ force_quick_gelu=force_quick_gelu,
364
+ force_custom_text=force_custom_text,
365
+ force_image_size=force_image_size,
366
+ cache_dir=cache_dir,
367
+ require_pretrained=True,
368
+ )
369
+
370
+ if not return_transform:
371
+ return model
372
+
373
+ image_mean = image_mean or getattr(model.visual, 'image_mean', None)
374
+ image_std = image_std or getattr(model.visual, 'image_std', None)
375
+ preprocess = image_transform(
376
+ model.visual.image_size,
377
+ is_train=False,
378
+ mean=image_mean,
379
+ std=image_std,
380
+ )
381
+
382
+ return model, preprocess
utils/hook.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Text, Callable, List
2
+ from collections import defaultdict
3
+
4
+
5
+ class HookManager(object):
6
+ def __init__(self, hook_dict: Dict[Text, List[Callable]] = None):
7
+ self.hook_dict = hook_dict or defaultdict(list)
8
+ self.called = defaultdict(int)
9
+ self.forks = dict()
10
+
11
+ def register(self, name: Text, func: Callable):
12
+ assert name
13
+ found_successor = False
14
+ for header, d in self.forks.items():
15
+ if name.startswith(header.split('.')[0]+'.'):
16
+ next_ = name[len(header.split('.')[0]+'.'):].split('.')[0]
17
+ prev_ = header.split('.')[0]
18
+ if next_.isnumeric() and prev_ + '.' + next_ == header:
19
+ d.register(name[len(header)+1:], func)
20
+ elif next_ == '*':
21
+ d.register(name[len(prev_ + '.*')+1:], func)
22
+ else:
23
+ d.register(name[len(header)+1:], func)
24
+ found_successor = True
25
+ if not found_successor:
26
+ self.hook_dict[name].append(func)
27
+
28
+ def unregister(self, name: Text, func: Callable):
29
+ assert name
30
+ found_successor = False
31
+ for header, d in self.forks.items():
32
+ if name.startswith(header.split('.')[0]+'.'):
33
+ next_ = name[len(header.split('.')[0]+'.'):].split('.')[0]
34
+ prev_ = header.split('.')[0]
35
+ if next_.isnumeric() and prev_ + '.' + next_ == header:
36
+ d.register(name[len(header)+1:], func)
37
+ elif next_ == '*':
38
+ d.register(name[len(prev_ + '.*')+1:], func)
39
+ else:
40
+ d.register(name[len(header)+1:], func)
41
+ found_successor = True
42
+ if not found_successor and func in self.hook_dict[name]:
43
+ self.hook_dict[name].remove(func)
44
+
45
+ def __call__(self, name: Text, **kwargs):
46
+ if name in self.hook_dict:
47
+ self.called[name] += 1
48
+ for function in self.hook_dict[name]:
49
+ ret = function(**kwargs)
50
+ if len(self.hook_dict[name]) > 1:
51
+ last = self.hook_dict[name][-1]
52
+ # print(f'The last returned value comes from func {last}')
53
+ return ret
54
+ else:
55
+ return kwargs['ret']
56
+
57
+ def fork(self, name):
58
+ if name in self.forks:
59
+ raise ValueError(f'Forking with the same name is not allowed. Already forked with {name}.')
60
+ filtered_hooks = [(k[len(name)+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.')]
61
+ filtered_hooks_d = defaultdict(list)
62
+ for i, j in filtered_hooks:
63
+ if isinstance(j, list):
64
+ filtered_hooks_d[i].extend(j)
65
+ else:
66
+ filtered_hooks_d[i].append(j)
67
+ new_hook = HookManager(filtered_hooks_d)
68
+ self.forks[name] = new_hook
69
+ return new_hook
70
+
71
+ def fork_iterative(self, name, iteration):
72
+ filtered_hooks = [(k[len(name+'.'+str(iteration))+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.'+str(iteration)+'.')]
73
+ filtered_hooks += [(k[len(name+'.*')+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.*.')]
74
+ filtered_hooks_d = defaultdict(list)
75
+ for i, j in filtered_hooks:
76
+ if isinstance(j, list):
77
+ filtered_hooks_d[i].extend(j)
78
+ else:
79
+ filtered_hooks_d[i].append(j)
80
+ new_hook = HookManager(filtered_hooks_d)
81
+ self.forks[name+'.'+str(iteration)] = new_hook
82
+ return new_hook
83
+
84
+ def finalize(self):
85
+ for name in self.hook_dict.keys():
86
+ if self.called[name] == 0:
87
+ raise ValueError(f'Hook {name} was registered but never used!')
utils/imagenet_classes.py ADDED
@@ -0,0 +1 @@
 
 
1
+ imagenet_classes = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"]
utils/imagenet_segmentation.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.utils.data as data
4
+ import numpy as np
5
+
6
+ from torchvision.datasets import ImageNet
7
+
8
+ from PIL import Image, ImageFilter
9
+ import h5py
10
+ from glob import glob
11
+
12
+
13
+ class ImagenetSegmentation(data.Dataset):
14
+ CLASSES = 2
15
+
16
+ def __init__(self,
17
+ path,
18
+ transform=None,
19
+ target_transform=None):
20
+ self.path = path
21
+ self.transform = transform
22
+ self.target_transform = target_transform
23
+ self.h5py = None
24
+ tmp = h5py.File(path, 'r')
25
+ self.data_length = len(tmp['/value/img'])
26
+ tmp.close()
27
+ del tmp
28
+
29
+ def __getitem__(self, index):
30
+
31
+ if self.h5py is None:
32
+ self.h5py = h5py.File(self.path, 'r')
33
+
34
+ img = np.array(self.h5py[self.h5py['/value/img'][index, 0]]).transpose((2, 1, 0))
35
+ target = np.array(self.h5py[self.h5py[self.h5py['/value/gt'][index, 0]][0, 0]]).transpose((1, 0))
36
+
37
+ img = Image.fromarray(img).convert('RGB')
38
+ target = Image.fromarray(target)
39
+
40
+ if self.transform is not None:
41
+ img = self.transform(img)
42
+
43
+ if self.target_transform is not None:
44
+ target = np.array(self.target_transform(target)).astype('int32')
45
+ target = torch.from_numpy(target).long()
46
+
47
+ return img, target
48
+
49
+ def __len__(self):
50
+ return self.data_length
utils/misc.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import repeat
2
+ import collections.abc
3
+
4
+ import torch
5
+ from torch import nn as nn
6
+ from torchvision.ops.misc import FrozenBatchNorm2d
7
+
8
+
9
+ def freeze_batch_norm_2d(module, module_match={}, name=''):
10
+ """
11
+ Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
12
+ itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and
13
+ returned. Otherwise, the module is walked recursively and submodules are converted in place.
14
+
15
+ Args:
16
+ module (torch.nn.Module): Any PyTorch module.
17
+ module_match (dict): Dictionary of full module names to freeze (all if empty)
18
+ name (str): Full module name (prefix)
19
+
20
+ Returns:
21
+ torch.nn.Module: Resulting module
22
+
23
+ Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
24
+ """
25
+ res = module
26
+ is_match = True
27
+ if module_match:
28
+ is_match = name in module_match
29
+ if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)):
30
+ res = FrozenBatchNorm2d(module.num_features)
31
+ res.num_features = module.num_features
32
+ res.affine = module.affine
33
+ if module.affine:
34
+ res.weight.data = module.weight.data.clone().detach()
35
+ res.bias.data = module.bias.data.clone().detach()
36
+ res.running_mean.data = module.running_mean.data
37
+ res.running_var.data = module.running_var.data
38
+ res.eps = module.eps
39
+ else:
40
+ for child_name, child in module.named_children():
41
+ full_child_name = '.'.join([name, child_name]) if name else child_name
42
+ new_child = freeze_batch_norm_2d(child, module_match, full_child_name)
43
+ if new_child is not child:
44
+ res.add_module(child_name, new_child)
45
+ return res
46
+
47
+
48
+ # From PyTorch internals
49
+ def _ntuple(n):
50
+ def parse(x):
51
+ if isinstance(x, collections.abc.Iterable):
52
+ return x
53
+ return tuple(repeat(x, n))
54
+ return parse
55
+
56
+
57
+ to_1tuple = _ntuple(1)
58
+ to_2tuple = _ntuple(2)
59
+ to_3tuple = _ntuple(3)
60
+ to_4tuple = _ntuple(4)
61
+ to_ntuple = lambda n, x: _ntuple(n)(x)
62
+
63
+ # Replaces all linear layers with linear_replacement
64
+ # TODO: add int8 support for other linear layers including attn and convnets
65
+ def replace_linear(model, linear_replacement, include_modules=['c_fc', 'c_proj'], copy_weights=True):
66
+ for name, module in model.named_children():
67
+ if len(list(module.children())) > 0:
68
+ replace_linear(module, linear_replacement, include_modules, copy_weights)
69
+
70
+ if isinstance(module, torch.nn.Linear) and name in include_modules:
71
+ old_module = model._modules[name]
72
+ model._modules[name] = linear_replacement(
73
+ module.in_features,
74
+ module.out_features,
75
+ module.bias is not None,
76
+ )
77
+ if copy_weights:
78
+ model._modules[name].weight.data.copy_(old_module.weight.data)
79
+ if model._modules[name].bias is not None:
80
+ model._modules[name].bias.data.copy_(old_module.bias)
81
+
82
+ return model
83
+
84
+ def convert_int8_model_to_inference_mode(model):
85
+ for m in model.modules():
86
+ if hasattr(m, 'prepare_for_eval'):
87
+ int8_original_dtype = m.weight.dtype
88
+ m.prepare_for_eval()
89
+ m.int8_original_dtype = int8_original_dtype
90
+
91
+
92
+ def accuracy(output, target, topk=(1,)):
93
+ """
94
+ Compute top-k accuracy
95
+
96
+ output: torch.Tensor
97
+ shape (N, C) where N is the number of examples, C the number of classes.
98
+ these are the logits.
99
+
100
+ target: torch.Tensor
101
+ shape (N,) where N is the number of examples. Groundtruth class id of each example.
102
+
103
+ topk: tuple
104
+ which topk to compute, e.g., topk=(1,5) will compute top-1 and top-5 accuracies
105
+
106
+ Returns
107
+ -------
108
+
109
+ list of top-k accuracies in the same order as `topk`
110
+ """
111
+ pred = output.topk(max(topk), 1, True, True)[1].t()
112
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
113
+ n = len(target)
114
+ return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) / n for k in topk]
utils/model.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ CLIP Model
2
+
3
+ Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+ from dataclasses import dataclass
6
+ import logging
7
+ import math
8
+ from typing import Optional, Tuple, Union, Text
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from torch import nn
14
+ from torch.utils.checkpoint import checkpoint
15
+
16
+
17
+ from utils.modified_resnet import ModifiedResNet
18
+ from utils.timm_model import TimmModel
19
+ from utils.transformer import LayerNorm, QuickGELU, VisionTransformer, TextTransformer, Attention
20
+ from utils.misc import to_2tuple
21
+ from utils.hook import HookManager
22
+
23
+
24
+ @dataclass
25
+ class CLIPVisionCfg:
26
+ layers: Union[Tuple[int, int, int, int], int] = 12
27
+ width: int = 768
28
+ head_width: int = 64
29
+ mlp_ratio: float = 4.0
30
+ patch_size: int = 16
31
+ image_size: Union[Tuple[int, int], int] = 224
32
+
33
+ ls_init_value: Optional[float] = None # layer scale initial value
34
+ patch_dropout: float = 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
35
+ input_patchnorm: bool = False # whether to use dual patchnorm - would only apply the input layernorm on each patch, as post-layernorm already exist in original clip vit design
36
+ 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)
37
+ attentional_pool: bool = False # whether to use attentional pooler in the last embedding layer
38
+ n_queries: int = 256 # n_queries for attentional pooler
39
+ attn_pooler_heads: int = 8 # n heads for attentional_pooling
40
+ output_tokens: bool = False
41
+
42
+ timm_model_name: str = None # a valid model name overrides layers, width, patch_size
43
+ timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
44
+ timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
45
+ timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '')
46
+ timm_proj_bias: bool = False # enable bias final projection
47
+ timm_drop: float = 0. # head dropout
48
+ timm_drop_path: Optional[float] = None # backbone stochastic depth
49
+
50
+
51
+
52
+
53
+ def convert_weights_to_lp(model: nn.Module, dtype=torch.float16):
54
+ """Convert applicable model parameters to low-precision (bf16 or fp16)"""
55
+
56
+ def _convert_weights(l):
57
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
58
+ l.weight.data = l.weight.data.to(dtype)
59
+ if l.bias is not None:
60
+ l.bias.data = l.bias.data.to(dtype)
61
+
62
+ if isinstance(l, (nn.MultiheadAttention, Attention)):
63
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
64
+ tensor = getattr(l, attr)
65
+ if tensor is not None:
66
+ tensor.data = tensor.data.to(dtype)
67
+
68
+ if isinstance(l, (CLIP, TextTransformer)):
69
+ # convert text nn.Parameter projections
70
+ attr = getattr(l, "text_projection", None)
71
+ if attr is not None:
72
+ attr.data = attr.data.to(dtype)
73
+
74
+ if isinstance(l, VisionTransformer):
75
+ # convert vision nn.Parameter projections
76
+ attr = getattr(l, "proj", None)
77
+ if attr is not None:
78
+ attr.data = attr.data.to(dtype)
79
+
80
+ model.apply(_convert_weights)
81
+
82
+ convert_weights_to_fp16 = convert_weights_to_lp # backwards compat
83
+
84
+
85
+ @dataclass
86
+ class CLIPTextCfg:
87
+ context_length: int = 77
88
+ vocab_size: int = 49408
89
+ width: int = 512
90
+ heads: int = 8
91
+ layers: int = 12
92
+ ls_init_value: Optional[float] = None # layer scale initial value
93
+ hf_model_name: str = None
94
+ hf_tokenizer_name: str = None
95
+ hf_model_pretrained: bool = True
96
+ proj: str = 'mlp'
97
+ pooler_type: str = 'mean_pooler'
98
+ embed_cls: bool = False
99
+ pad_id: int = 0
100
+ output_tokens: bool = False
101
+
102
+
103
+ def get_cast_dtype(precision: str):
104
+ cast_dtype = None
105
+ if precision == 'bf16':
106
+ cast_dtype = torch.bfloat16
107
+ elif precision == 'fp16':
108
+ cast_dtype = torch.float16
109
+ return cast_dtype
110
+
111
+
112
+ def get_input_dtype(precision: str):
113
+ input_dtype = None
114
+ if precision in ('bf16', 'pure_bf16'):
115
+ input_dtype = torch.bfloat16
116
+ elif precision in ('fp16', 'pure_fp16'):
117
+ input_dtype = torch.float16
118
+ return input_dtype
119
+
120
+
121
+ def _build_vision_tower(
122
+ embed_dim: int,
123
+ vision_cfg: CLIPVisionCfg,
124
+ quick_gelu: bool = False,
125
+ cast_dtype: Optional[torch.dtype] = None,
126
+ hook: Optional[HookManager]= None,
127
+ ):
128
+ if isinstance(vision_cfg, dict):
129
+ vision_cfg = CLIPVisionCfg(**vision_cfg)
130
+
131
+ # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more
132
+ # memory efficient in recent PyTorch releases (>= 1.10).
133
+ # NOTE: timm models always use native GELU regardless of quick_gelu flag.
134
+ act_layer = QuickGELU if quick_gelu else nn.GELU
135
+
136
+ if vision_cfg.timm_model_name:
137
+ visual = TimmModel(
138
+ vision_cfg.timm_model_name,
139
+ pretrained=vision_cfg.timm_model_pretrained,
140
+ pool=vision_cfg.timm_pool,
141
+ proj=vision_cfg.timm_proj,
142
+ proj_bias=vision_cfg.timm_proj_bias,
143
+ drop=vision_cfg.timm_drop,
144
+ drop_path=vision_cfg.timm_drop_path,
145
+ patch_drop=vision_cfg.patch_dropout if vision_cfg.patch_dropout > 0 else None,
146
+ embed_dim=embed_dim,
147
+ image_size=vision_cfg.image_size,
148
+ hook=hook,
149
+ )
150
+ elif isinstance(vision_cfg.layers, (tuple, list)):
151
+ vision_heads = vision_cfg.width * 32 // vision_cfg.head_width
152
+ visual = ModifiedResNet(
153
+ layers=vision_cfg.layers,
154
+ output_dim=embed_dim,
155
+ heads=vision_heads,
156
+ image_size=vision_cfg.image_size,
157
+ width=vision_cfg.width,
158
+ hook=hook,
159
+ )
160
+ else:
161
+ vision_heads = vision_cfg.width // vision_cfg.head_width
162
+ norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
163
+ visual = VisionTransformer(
164
+ image_size=vision_cfg.image_size,
165
+ patch_size=vision_cfg.patch_size,
166
+ width=vision_cfg.width,
167
+ layers=vision_cfg.layers,
168
+ heads=vision_heads,
169
+ mlp_ratio=vision_cfg.mlp_ratio,
170
+ ls_init_value=vision_cfg.ls_init_value,
171
+ patch_dropout=vision_cfg.patch_dropout,
172
+ input_patchnorm=vision_cfg.input_patchnorm,
173
+ global_average_pool=vision_cfg.global_average_pool,
174
+ attentional_pool=vision_cfg.attentional_pool,
175
+ n_queries=vision_cfg.n_queries,
176
+ attn_pooler_heads=vision_cfg.attn_pooler_heads,
177
+ output_tokens=vision_cfg.output_tokens,
178
+ output_dim=embed_dim,
179
+ act_layer=act_layer,
180
+ norm_layer=norm_layer,
181
+ hook=hook,
182
+ )
183
+
184
+ return visual
185
+
186
+
187
+ def _build_text_tower(
188
+ embed_dim: int,
189
+ text_cfg: CLIPTextCfg,
190
+ quick_gelu: bool = False,
191
+ cast_dtype: Optional[torch.dtype] = None,
192
+ hook: Optional[HookManager] = None,
193
+ ):
194
+ if isinstance(text_cfg, dict):
195
+ text_cfg = CLIPTextCfg(**text_cfg)
196
+
197
+ if text_cfg.hf_model_name:
198
+ from hf_model import HFTextEncoder
199
+ text = HFTextEncoder(
200
+ text_cfg.hf_model_name,
201
+ output_dim=embed_dim,
202
+ proj=text_cfg.proj,
203
+ pooler_type=text_cfg.pooler_type,
204
+ pretrained=text_cfg.hf_model_pretrained,
205
+ output_tokens=text_cfg.output_tokens,
206
+ )
207
+ else:
208
+ act_layer = QuickGELU if quick_gelu else nn.GELU
209
+ norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
210
+
211
+ text = TextTransformer(
212
+ context_length=text_cfg.context_length,
213
+ vocab_size=text_cfg.vocab_size,
214
+ width=text_cfg.width,
215
+ heads=text_cfg.heads,
216
+ layers=text_cfg.layers,
217
+ ls_init_value=text_cfg.ls_init_value,
218
+ output_dim=embed_dim,
219
+ embed_cls=text_cfg.embed_cls,
220
+ output_tokens=text_cfg.output_tokens,
221
+ pad_id=text_cfg.pad_id,
222
+ act_layer=act_layer,
223
+ norm_layer=norm_layer,
224
+ )
225
+ return text
226
+
227
+
228
+ class CLIP(nn.Module):
229
+ output_dict: torch.jit.Final[bool]
230
+
231
+ def __init__(
232
+ self,
233
+ embed_dim: int,
234
+ vision_cfg: CLIPVisionCfg,
235
+ text_cfg: CLIPTextCfg,
236
+ quick_gelu: bool = False,
237
+ cast_dtype: Optional[torch.dtype] = None,
238
+ output_dict: bool = False,
239
+ hook: Optional[HookManager] = None,
240
+ ):
241
+ super().__init__()
242
+ self.hook_manager = hook or HookManager()
243
+ self.output_dict = output_dict
244
+ self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('visual'))
245
+
246
+ text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('textual'))
247
+ self.transformer = text.transformer
248
+ self.context_length = text.context_length
249
+ self.vocab_size = text.vocab_size
250
+ self.token_embedding = text.token_embedding
251
+ self.positional_embedding = text.positional_embedding
252
+ self.ln_final = text.ln_final
253
+ self.text_projection = text.text_projection
254
+ self.register_buffer('attn_mask', text.attn_mask, persistent=False)
255
+
256
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
257
+
258
+ @torch.jit.ignore
259
+ def set_grad_checkpointing(self, enable=True):
260
+ self.visual.set_grad_checkpointing(enable)
261
+ self.transformer.grad_checkpointing = enable
262
+
263
+ def encode_image(self, image, normalize: bool = False, attn_method: Text = 'direct'):
264
+ features = self.visual(image, attn_method=attn_method)
265
+ return F.normalize(features, dim=-1) if normalize else features
266
+
267
+ def encode_text(self, text, normalize: bool = False, full_sentence: bool = False, projection: bool = True):
268
+ cast_dtype = self.transformer.get_cast_dtype()
269
+
270
+ x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
271
+
272
+ x = x + self.positional_embedding.to(cast_dtype)
273
+ # x = x.permute(1, 0, 2) # NLD -> LND
274
+ x = self.transformer(x, attn_mask=self.attn_mask)
275
+ # x = x.permute(1, 0, 2) # LND -> NLD
276
+ x = self.ln_final(x) # [batch_size, n_ctx, transformer.width]
277
+ if full_sentence:
278
+ if projection:
279
+ x = x @ self.text_projection
280
+ else:
281
+ x = x
282
+ else:
283
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
284
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
285
+ return F.normalize(x, dim=-1) if normalize else x
286
+
287
+ def forward(
288
+ self,
289
+ image: Optional[torch.Tensor] = None,
290
+ text: Optional[torch.Tensor] = None,
291
+ ):
292
+ image_features = self.encode_image(image, normalize=True) if image is not None else None
293
+ text_features = self.encode_text(text, normalize=True) if text is not None else None
294
+ if self.output_dict:
295
+ return {
296
+ "image_features": image_features,
297
+ "text_features": text_features,
298
+ "logit_scale": self.logit_scale.exp()
299
+ }
300
+ return image_features, text_features, self.logit_scale.exp()
301
+
302
+
303
+ # used to maintain checkpoint compatibility
304
+ def convert_to_custom_text_state_dict(state_dict: dict):
305
+ if 'text_projection' in state_dict:
306
+ # old format state_dict, move text tower -> .text
307
+ new_state_dict = {}
308
+ for k, v in state_dict.items():
309
+ if any(k.startswith(p) for p in (
310
+ 'text_projection',
311
+ 'positional_embedding',
312
+ 'token_embedding',
313
+ 'transformer',
314
+ 'ln_final',
315
+ )):
316
+ k = 'text.' + k
317
+ new_state_dict[k] = v
318
+ return new_state_dict
319
+ return state_dict
320
+
321
+
322
+ def build_model_from_openai_state_dict(
323
+ state_dict: dict,
324
+ quick_gelu=True,
325
+ cast_dtype=torch.float16,
326
+ ):
327
+ vit = "visual.proj" in state_dict
328
+
329
+ if vit:
330
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
331
+ vision_layers = len(
332
+ [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
333
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
334
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
335
+ image_size = vision_patch_size * grid_size
336
+ else:
337
+ counts: list = [
338
+ len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
339
+ vision_layers = tuple(counts)
340
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
341
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
342
+ vision_patch_size = None
343
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
344
+ image_size = output_width * 32
345
+
346
+ embed_dim = state_dict["text_projection"].shape[1]
347
+ context_length = state_dict["positional_embedding"].shape[0]
348
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
349
+ transformer_width = state_dict["ln_final.weight"].shape[0]
350
+ transformer_heads = transformer_width // 64
351
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
352
+
353
+ vision_cfg = CLIPVisionCfg(
354
+ layers=vision_layers,
355
+ width=vision_width,
356
+ patch_size=vision_patch_size,
357
+ image_size=image_size,
358
+ )
359
+ text_cfg = CLIPTextCfg(
360
+ context_length=context_length,
361
+ vocab_size=vocab_size,
362
+ width=transformer_width,
363
+ heads=transformer_heads,
364
+ layers=transformer_layers,
365
+ )
366
+ model = CLIP(
367
+ embed_dim,
368
+ vision_cfg=vision_cfg,
369
+ text_cfg=text_cfg,
370
+ quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU
371
+ cast_dtype=cast_dtype,
372
+ )
373
+
374
+ for key in ["input_resolution", "context_length", "vocab_size"]:
375
+ state_dict.pop(key, None)
376
+
377
+ convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16
378
+ model.load_state_dict(state_dict)
379
+ return model.eval()
380
+
381
+
382
+ def resize_pos_embed(state_dict, model, interpolation: str = 'bicubic', antialias: bool = True):
383
+ # Rescale the grid of position embeddings when loading from state_dict
384
+ old_pos_embed = state_dict.get('visual.positional_embedding', None)
385
+ if old_pos_embed is None or not hasattr(model.visual, 'grid_size'):
386
+ return
387
+ grid_size = to_2tuple(model.visual.grid_size)
388
+ extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
389
+ new_seq_len = grid_size[0] * grid_size[1] + extra_tokens
390
+ if new_seq_len == old_pos_embed.shape[0]:
391
+ return
392
+
393
+ if extra_tokens:
394
+ pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:]
395
+ else:
396
+ pos_emb_tok, pos_emb_img = None, old_pos_embed
397
+ old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img))))
398
+
399
+ logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size)
400
+ pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2)
401
+ pos_emb_img = F.interpolate(
402
+ pos_emb_img,
403
+ size=grid_size,
404
+ mode=interpolation,
405
+ antialias=antialias,
406
+ align_corners=False,
407
+ )
408
+ pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0]
409
+ if pos_emb_tok is not None:
410
+ new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0)
411
+ else:
412
+ new_pos_embed = pos_emb_img
413
+ state_dict['visual.positional_embedding'] = new_pos_embed
utils/model_configs/EVA01-g-14-plus.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "timm_model_name": "eva_giant_patch14_224",
6
+ "timm_model_pretrained": false,
7
+ "timm_pool": "token",
8
+ "timm_proj": null
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 1024,
14
+ "heads": 16,
15
+ "layers": 24
16
+ },
17
+ "custom_text": true
18
+ }
utils/model_configs/EVA01-g-14.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "timm_model_name": "eva_giant_patch14_224",
6
+ "timm_model_pretrained": false,
7
+ "timm_pool": "token",
8
+ "timm_proj": null
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 768,
14
+ "heads": 12,
15
+ "layers": 12
16
+ },
17
+ "custom_text": true
18
+ }
utils/model_configs/EVA02-B-16.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "timm_model_name": "eva02_base_patch16_clip_224",
6
+ "timm_model_pretrained": false,
7
+ "timm_pool": "token",
8
+ "timm_proj": null
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 512,
14
+ "heads": 8,
15
+ "layers": 12
16
+ },
17
+ "custom_text": true
18
+ }
utils/model_configs/EVA02-E-14-plus.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "timm_model_name": "eva02_enormous_patch14_clip_224",
6
+ "timm_model_pretrained": false,
7
+ "timm_pool": "token",
8
+ "timm_proj": null
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 1280,
14
+ "heads": 20,
15
+ "layers": 32
16
+ },
17
+ "custom_text": true
18
+ }
utils/model_configs/EVA02-E-14.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "timm_model_name": "eva02_enormous_patch14_clip_224",
6
+ "timm_model_pretrained": false,
7
+ "timm_pool": "token",
8
+ "timm_proj": null
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 1024,
14
+ "heads": 16,
15
+ "layers": 24
16
+ },
17
+ "custom_text": true
18
+ }
utils/model_configs/EVA02-L-14-336.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 336,
5
+ "timm_model_name": "eva02_large_patch14_clip_336",
6
+ "timm_model_pretrained": false,
7
+ "timm_pool": "token",
8
+ "timm_proj": null
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 768,
14
+ "heads": 12,
15
+ "layers": 12
16
+ },
17
+ "custom_text": true
18
+ }
utils/model_configs/EVA02-L-14.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "timm_model_name": "eva02_large_patch14_clip_224",
6
+ "timm_model_pretrained": false,
7
+ "timm_pool": "token",
8
+ "timm_proj": null
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 768,
14
+ "heads": 12,
15
+ "layers": 12
16
+ },
17
+ "custom_text": true
18
+ }
utils/model_configs/ViT-B-16-plus-240.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 640,
3
+ "vision_cfg": {
4
+ "image_size": 240,
5
+ "layers": 12,
6
+ "width": 896,
7
+ "patch_size": 16
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 640,
13
+ "heads": 10,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-B-16-plus.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 640,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 896,
7
+ "patch_size": 16
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 640,
13
+ "heads": 10,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-B-16.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "patch_size": 16
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 512,
13
+ "heads": 8,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-B-32-plus-256.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 640,
3
+ "vision_cfg": {
4
+ "image_size": 256,
5
+ "layers": 12,
6
+ "width": 896,
7
+ "patch_size": 32
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 640,
13
+ "heads": 10,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-B-32-quickgelu.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "quick_gelu": true,
4
+ "vision_cfg": {
5
+ "image_size": 224,
6
+ "layers": 12,
7
+ "width": 768,
8
+ "patch_size": 32
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 512,
14
+ "heads": 8,
15
+ "layers": 12
16
+ }
17
+ }
utils/model_configs/ViT-B-32.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "patch_size": 32
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 512,
13
+ "heads": 8,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-H-14.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 32,
6
+ "width": 1280,
7
+ "head_width": 80,
8
+ "patch_size": 14
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 1024,
14
+ "heads": 16,
15
+ "layers": 24
16
+ }
17
+ }
utils/model_configs/ViT-H-16.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 32,
6
+ "width": 1280,
7
+ "head_width": 80,
8
+ "patch_size": 16
9
+ },
10
+ "text_cfg": {
11
+ "context_length": 77,
12
+ "vocab_size": 49408,
13
+ "width": 1024,
14
+ "heads": 16,
15
+ "layers": 24
16
+ }
17
+ }
utils/model_configs/ViT-L-14-280.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 280,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "patch_size": 14
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 768,
13
+ "heads": 12,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-L-14-336.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 336,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "patch_size": 14
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 768,
13
+ "heads": 12,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-L-14.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "patch_size": 14
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 768,
13
+ "heads": 12,
14
+ "layers": 12
15
+ }
16
+ }
utils/model_configs/ViT-L-16-320.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 320,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "patch_size": 16
8
+ },
9
+ "text_cfg": {
10
+ "context_length": 77,
11
+ "vocab_size": 49408,
12
+ "width": 768,
13
+ "heads": 12,
14
+ "layers": 12
15
+ }
16
+ }