XavierJiezou commited on
Commit
4e0ff2f
·
verified ·
1 Parent(s): 915d50e

Upload folder using huggingface_hub

Browse files
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ **__pycache__**
2
+ __pycache__\
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ import numpy as np
4
+ import os
5
+ import torch
6
+ import torchvision.transforms as transforms
7
+ from models import get_model
8
+
9
+ # os.environ["http_proxt"] = ""
10
+ # 常量定义
11
+ MEAN = {
12
+ "imagenet": [0.485, 0.456, 0.406],
13
+ "clip": [0.48145466, 0.4578275, 0.40821073]
14
+ }
15
+
16
+ STD = {
17
+ "imagenet": [0.229, 0.224, 0.225],
18
+ "clip": [0.26862954, 0.26130258, 0.27577711]
19
+ }
20
+
21
+
22
+
23
+ def collect_examples(base_dir="examples"):
24
+ """
25
+ 递归扫描 base_dir 下所有图片,返回形如
26
+ [
27
+ ["examples/real/00001.jpg"],
28
+ ["examples/real/00002.jpg"],
29
+ ...
30
+ ["examples/fake/00001.jpg"],
31
+ ...
32
+ ]
33
+ 的二维列表(每个 inner list 对应一次调用的所有输入,这里只有一张图)
34
+ """
35
+ exts = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
36
+ examples = []
37
+
38
+ # 让 real 在前、fake 在后,内层文件名按数字排序
39
+ for cls in ["real", "fake"]:
40
+ subdir = os.path.join(base_dir, cls)
41
+ if not os.path.isdir(subdir):
42
+ continue
43
+ for fname in sorted(os.listdir(subdir)):
44
+ if fname.lower().endswith(exts):
45
+ examples.append([os.path.join(subdir, fname)])
46
+ return examples
47
+
48
+ class ForgeryDetector:
49
+ def __init__(self, arch='CLIP:ViT-L/14', ckpt_path='checkpoints/model_epoch_best.pth', device='cuda'):
50
+ """
51
+ 初始化伪造检测器
52
+
53
+ Args:
54
+ arch: 模型架构 (如 'res50', 'CLIP:ViT-B/32' 等)
55
+ ckpt_path: 预训练模型权重路径
56
+ device: 运行设备 ('cuda' 或 'cpu')
57
+ """
58
+ self.arch = arch
59
+ self.device = torch.device(device if torch.cuda.is_available() else 'cpu')
60
+
61
+ # 根据架构选择统计信息
62
+ stat_from = "imagenet" if arch.lower().startswith("imagenet") else "clip"
63
+
64
+ # 数据预处理
65
+ self.transform = transforms.Compose([
66
+ transforms.Resize(256), # 与验证代码保持一致
67
+ transforms.CenterCrop(224),
68
+ transforms.ToTensor(),
69
+ transforms.Normalize(mean=MEAN[stat_from], std=STD[stat_from]),
70
+ ])
71
+
72
+ # 创建模型选项对象 (模拟TrainOptions)
73
+ self.opt = self._create_opt(arch)
74
+
75
+ # 加载模型
76
+ self.model = self._load_model(ckpt_path)
77
+
78
+ def _create_opt(self, arch):
79
+ """创建模型配置选项"""
80
+ class Options:
81
+ pass
82
+
83
+ opt = Options()
84
+ opt.arch = arch
85
+ opt.head_type = "attention" if arch.startswith("CLIP:") else "fc"
86
+ opt.shuffle = True
87
+ opt.shuffle_times = 1
88
+ opt.original_times = 1
89
+ opt.patch_size = [14]
90
+ opt.penultimate_feature = False
91
+ opt.patch_base = False
92
+
93
+ return opt
94
+
95
+ def _load_model(self, ckpt_path):
96
+ """加载预训练模型"""
97
+ print(f"正在加载模型架构: {self.arch}")
98
+ model = get_model(self.opt)
99
+
100
+ # 加载权重
101
+ print(f"正在加载权重: {ckpt_path}")
102
+ state_dict = torch.load(ckpt_path, map_location=self.device)
103
+
104
+ # 根据模型类型加载不同的权重
105
+ if self.opt.head_type == "fc":
106
+ model.fc.load_state_dict(state_dict)
107
+ elif self.opt.head_type == "attention":
108
+ model.attention_head.load_state_dict(state_dict)
109
+ else:
110
+ model.load_state_dict(state_dict)
111
+
112
+ model.eval()
113
+ model.to(self.device)
114
+ print("模型加载完成!")
115
+
116
+ return model
117
+
118
+ def preprocess_image(self, image:Image.Image):
119
+ """
120
+ 预处理单张图片
121
+
122
+ Args:
123
+ image_path: 图片路径
124
+
125
+ Returns:
126
+ 处理后的tensor
127
+ """
128
+
129
+
130
+ try:
131
+ image_tensor = self.transform(image).unsqueeze(0) # 添加batch维度
132
+ return image_tensor.to(self.device)
133
+ except Exception as e:
134
+ raise ValueError(f"图片预处理失败: {e}")
135
+
136
+ def predict(self, image: Image.Image, return_probabilities=True):
137
+ """
138
+ 对单张图片进行伪造检测
139
+
140
+ Args:
141
+ image: Image.Image
142
+ return_probabilities: 是否返回概率值,否则返回类别
143
+
144
+ Returns:
145
+ 如果return_probabilities=True: 返回 (real_prob, fake_prob)
146
+ 如果return_probabilities=False: 返回 "real" 或 "fake"
147
+ """
148
+ # 预处理图片
149
+ image_tensor = self.preprocess_image(image)
150
+
151
+ # 推理
152
+ with torch.no_grad():
153
+ output = self.model(image_tensor)
154
+ # 处理不同的输出格式
155
+ if output.shape[-1] == 2:
156
+ # 二分类输出
157
+ probs = torch.softmax(output, dim=1)[0]
158
+
159
+ real_prob = probs[0].item()
160
+ fake_prob = probs[1].item()
161
+ else:
162
+ # 单值输出 (通常用sigmoid)
163
+ fake_prob = torch.sigmoid(output).item()
164
+ real_prob = 1 - fake_prob
165
+
166
+ if return_probabilities:
167
+ return real_prob, fake_prob
168
+ else:
169
+ return "real" if real_prob > fake_prob else "fake"
170
+
171
+ def batch_predict(self, image_paths, return_probabilities=True):
172
+ """
173
+ 批量预测多张图片
174
+
175
+ Args:
176
+ image_paths: 图片路径列表
177
+ return_probabilities: 是否返回概率值
178
+
179
+ Returns:
180
+ 预测结果列表
181
+ """
182
+ results = []
183
+ for image_path in image_paths:
184
+ try:
185
+ result = self.predict(image_path, return_probabilities)
186
+ results.append({
187
+ 'image_path': image_path,
188
+ 'result': result,
189
+ 'status': 'success'
190
+ })
191
+ except Exception as e:
192
+ results.append({
193
+ 'image_path': image_path,
194
+ 'result': None,
195
+ 'status': f'error: {e}'
196
+ })
197
+ return results
198
+
199
+
200
+ model = ForgeryDetector()
201
+
202
+ # ------- 1) (示例)假模型 -------
203
+ def predict(img: Image.Image):
204
+ result = model.predict(img)
205
+
206
+ probs = np.array(result)
207
+ return {"Real Image": float(probs[0]), "Fake Image": float(probs[1])}
208
+
209
+ EXAMPLES = collect_examples()
210
+
211
+
212
+ # ------- 2) UI -------
213
+ with gr.Blocks() as demo:
214
+ gr.Markdown("## Real-vs-Fake Image Detector")
215
+
216
+ with gr.Row():
217
+ # —— 左列:图片 + 按钮 ——
218
+ with gr.Column(scale=1):
219
+ img_input = gr.Image(label="img", type="pil")
220
+
221
+ # ✨ 示例图片组件
222
+ gr.Examples(
223
+ examples=EXAMPLES, # 刚才收集到的二维列表
224
+ inputs=img_input, # 点击示例 -> 填到这个组件
225
+ cache_examples=False, # 鉴于模型可能较大,关闭缓存以免占显存
226
+ label="Examples",
227
+ )
228
+
229
+ # 把按钮放到 **同一列** 下方
230
+ with gr.Row():
231
+ submit_btn = gr.Button("Submit", variant="primary")
232
+ clear_btn = gr.ClearButton(value="Clear", components=[img_input])
233
+
234
+ # —— 右列:结果条形图 ——
235
+ with gr.Column(scale=1):
236
+ label_output = gr.Label(label="output", num_top_classes=2)
237
+
238
+ # 交互
239
+ submit_btn.click(predict, inputs=img_input, outputs=label_output)
240
+ clear_btn.add([label_output]) # 同时清空右侧结果
241
+
242
+ if __name__ == "__main__":
243
+ demo.launch()
checkpoints/model_epoch_best.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35273bf0539d3fc235ec24e5ce9bec3f17ff0572a48c0522b33fb89404213ff0
3
+ size 12606764
examples/fake/00001.jpg ADDED
examples/fake/00002.jpg ADDED
examples/fake/00003.jpg ADDED
examples/real/00001.jpg ADDED
examples/real/00002.jpg ADDED
examples/real/00003.jpg ADDED
models/__init__.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .clip_models import CLIPModel, CLIPModelShuffleAttentionPenultimateLayer
2
+ from .imagenet_models import ImagenetModel
3
+ from .moco_models import MOCOModel_v3, MOCOModel_v3_ShuffleAttention, MOCOModel_v1, MOCOModel_v1_PatchesAttention, MOCOModel_v1_ShuffleAttention
4
+
5
+
6
+ VALID_NAMES = [
7
+ 'Imagenet:resnet18',
8
+ 'Imagenet:resnet34',
9
+ 'Imagenet:resnet50',
10
+ 'Imagenet:resnet101',
11
+ 'Imagenet:resnet152',
12
+ 'Imagenet:vgg11',
13
+ 'Imagenet:vgg19',
14
+ 'Imagenet:swin-b',
15
+ 'Imagenet:swin-s',
16
+ 'Imagenet:swin-t',
17
+ 'Imagenet:vit_b_16',
18
+ 'Imagenet:vit_b_32',
19
+ 'Imagenet:vit_l_16',
20
+ 'Imagenet:vit_l_32',
21
+
22
+ 'CLIP:RN50',
23
+ 'CLIP:RN101',
24
+ 'CLIP:RN50x4',
25
+ 'CLIP:RN50x16',
26
+ 'CLIP:RN50x64',
27
+ 'CLIP:ViT-B/32',
28
+ 'CLIP:ViT-B/16',
29
+ 'CLIP:ViT-L/14',
30
+ 'CLIP:ViT-L/14@336px',
31
+
32
+ 'MOCO_v3:ViT',
33
+ 'MOCO_v3:ViT_shuffle_attention',
34
+ 'MOCO_v1:RN50',
35
+ ]
36
+
37
+
38
+
39
+
40
+
41
+ def get_model(opt):
42
+ name = opt.arch
43
+ assert name in VALID_NAMES
44
+ if name.startswith("Imagenet:"):
45
+ return ImagenetModel(name[9:])
46
+ elif name.startswith("CLIP:"):
47
+ if opt.head_type == "fc":
48
+ if opt.penultimate_feature:
49
+ return CLIPModelPenultimateLayer(name[5:])
50
+ else:
51
+ return CLIPModel(name[5:])
52
+ elif opt.head_type == "attention":
53
+ # penultimate feature
54
+ if opt.shuffle:
55
+ return CLIPModelShuffleAttentionPenultimateLayer(name[5:], shuffle_times=opt.shuffle_times, original_times=opt.original_times, patch_size=opt.patch_size)
56
+
57
+ elif name.startswith("MOCO_v1:"):
58
+ if opt.head_type == "fc":
59
+ return MOCOModel_v1()
60
+ elif opt.head_type == "attention":
61
+ if opt.patch_base:
62
+ return MOCOModel_v1_PatchesAttention()
63
+ else:
64
+ return MOCOModel_v1_ShuffleAttention()
65
+
66
+
67
+ elif name.startswith("MOCO_v3:"):
68
+ if opt.head_type == "attention":
69
+ return MOCOModel_v3_ShuffleAttention(opt)
70
+ else:
71
+ return MOCOModel_v3(opt)
72
+ else:
73
+ assert False
models/clip/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .clip import *
models/clip/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
models/clip/clip.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Any, Union, List
6
+ from pkg_resources import packaging
7
+
8
+ import torch
9
+ from PIL import Image
10
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
11
+ from tqdm import tqdm
12
+
13
+ from .model import build_model
14
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
15
+
16
+ try:
17
+ from torchvision.transforms import InterpolationMode
18
+ BICUBIC = InterpolationMode.BICUBIC
19
+ except ImportError:
20
+ BICUBIC = Image.BICUBIC
21
+
22
+
23
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
24
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
25
+
26
+
27
+ __all__ = ["available_models", "load", "tokenize"]
28
+ _tokenizer = _Tokenizer()
29
+
30
+ _MODELS = {
31
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
32
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
33
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
34
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
35
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
36
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
37
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
38
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
39
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
40
+ }
41
+
42
+
43
+ def _download(url: str, root: str):
44
+ os.makedirs(root, exist_ok=True)
45
+ filename = os.path.basename(url)
46
+
47
+ expected_sha256 = url.split("/")[-2]
48
+ download_target = os.path.join(root, filename)
49
+
50
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
51
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
52
+
53
+ if os.path.isfile(download_target):
54
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
55
+ return download_target
56
+ else:
57
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
58
+
59
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
60
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
61
+ while True:
62
+ buffer = source.read(8192)
63
+ if not buffer:
64
+ break
65
+
66
+ output.write(buffer)
67
+ loop.update(len(buffer))
68
+
69
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
70
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
71
+
72
+ return download_target
73
+
74
+
75
+ def _convert_image_to_rgb(image):
76
+ return image.convert("RGB")
77
+
78
+
79
+ def _transform(n_px):
80
+ return Compose([
81
+ Resize(n_px, interpolation=BICUBIC),
82
+ CenterCrop(n_px),
83
+ _convert_image_to_rgb,
84
+ ToTensor(),
85
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
86
+ ])
87
+
88
+
89
+ def available_models() -> List[str]:
90
+ """Returns the names of available CLIP models"""
91
+ return list(_MODELS.keys())
92
+
93
+
94
+ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
95
+ """Load a CLIP model
96
+
97
+ Parameters
98
+ ----------
99
+ name : str
100
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
101
+
102
+ device : Union[str, torch.device]
103
+ The device to put the loaded model
104
+
105
+ jit : bool
106
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
107
+
108
+ download_root: str
109
+ path to download the model files; by default, it uses "~/.cache/clip"
110
+
111
+ Returns
112
+ -------
113
+ model : torch.nn.Module
114
+ The CLIP model
115
+
116
+ preprocess : Callable[[PIL.Image], torch.Tensor]
117
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
118
+ """
119
+ if name in _MODELS:
120
+ model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
121
+ elif os.path.isfile(name):
122
+ model_path = name
123
+ else:
124
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
125
+
126
+ with open(model_path, 'rb') as opened_file:
127
+ try:
128
+ # loading JIT archive
129
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
130
+ state_dict = None
131
+ except RuntimeError:
132
+ # loading saved state dict
133
+ if jit:
134
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
135
+ jit = False
136
+ state_dict = torch.load(opened_file, map_location="cpu")
137
+
138
+ if not jit:
139
+ model = build_model(state_dict or model.state_dict()).to(device)
140
+ if str(device) == "cpu":
141
+ model.float()
142
+ return model, _transform(model.visual.input_resolution)
143
+
144
+ # patch the device names
145
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
146
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
147
+
148
+ def patch_device(module):
149
+ try:
150
+ graphs = [module.graph] if hasattr(module, "graph") else []
151
+ except RuntimeError:
152
+ graphs = []
153
+
154
+ if hasattr(module, "forward1"):
155
+ graphs.append(module.forward1.graph)
156
+
157
+ for graph in graphs:
158
+ for node in graph.findAllNodes("prim::Constant"):
159
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
160
+ node.copyAttributes(device_node)
161
+
162
+ model.apply(patch_device)
163
+ patch_device(model.encode_image)
164
+ patch_device(model.encode_text)
165
+
166
+ # patch dtype to float32 on CPU
167
+ if str(device) == "cpu":
168
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
169
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
170
+ float_node = float_input.node()
171
+
172
+ def patch_float(module):
173
+ try:
174
+ graphs = [module.graph] if hasattr(module, "graph") else []
175
+ except RuntimeError:
176
+ graphs = []
177
+
178
+ if hasattr(module, "forward1"):
179
+ graphs.append(module.forward1.graph)
180
+
181
+ for graph in graphs:
182
+ for node in graph.findAllNodes("aten::to"):
183
+ inputs = list(node.inputs())
184
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
185
+ if inputs[i].node()["value"] == 5:
186
+ inputs[i].node().copyAttributes(float_node)
187
+
188
+ model.apply(patch_float)
189
+ patch_float(model.encode_image)
190
+ patch_float(model.encode_text)
191
+
192
+ model.float()
193
+
194
+ return model, _transform(model.input_resolution.item())
195
+
196
+
197
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
198
+ """
199
+ Returns the tokenized representation of given input string(s)
200
+
201
+ Parameters
202
+ ----------
203
+ texts : Union[str, List[str]]
204
+ An input string or a list of input strings to tokenize
205
+
206
+ context_length : int
207
+ The context length to use; all CLIP models use 77 as the context length
208
+
209
+ truncate: bool
210
+ Whether to truncate the text in case its encoding is longer than the context length
211
+
212
+ Returns
213
+ -------
214
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
215
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
216
+ """
217
+ if isinstance(texts, str):
218
+ texts = [texts]
219
+
220
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
221
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
222
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
223
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
224
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
225
+ else:
226
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
227
+
228
+ for i, tokens in enumerate(all_tokens):
229
+ if len(tokens) > context_length:
230
+ if truncate:
231
+ tokens = tokens[:context_length]
232
+ tokens[-1] = eot_token
233
+ else:
234
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
235
+ result[i, :len(tokens)] = torch.tensor(tokens)
236
+
237
+ return result
models/clip/model.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.relu1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.relu2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.relu3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([
37
+ ("-1", nn.AvgPool2d(stride)),
38
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
39
+ ("1", nn.BatchNorm2d(planes * self.expansion))
40
+ ]))
41
+
42
+ def forward(self, x: torch.Tensor):
43
+ identity = x
44
+
45
+ out = self.relu1(self.bn1(self.conv1(x)))
46
+ out = self.relu2(self.bn2(self.conv2(out)))
47
+ out = self.avgpool(out)
48
+ out = self.bn3(self.conv3(out))
49
+
50
+ if self.downsample is not None:
51
+ identity = self.downsample(x)
52
+
53
+ out += identity
54
+ out = self.relu3(out)
55
+ return out
56
+
57
+
58
+ class AttentionPool2d(nn.Module):
59
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
60
+ super().__init__()
61
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
62
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
64
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
66
+ self.num_heads = num_heads
67
+
68
+ def forward(self, x):
69
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
70
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
71
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
72
+ x, _ = F.multi_head_attention_forward(
73
+ query=x[:1], key=x, value=x,
74
+ embed_dim_to_check=x.shape[-1],
75
+ num_heads=self.num_heads,
76
+ q_proj_weight=self.q_proj.weight,
77
+ k_proj_weight=self.k_proj.weight,
78
+ v_proj_weight=self.v_proj.weight,
79
+ in_proj_weight=None,
80
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
81
+ bias_k=None,
82
+ bias_v=None,
83
+ add_zero_attn=False,
84
+ dropout_p=0,
85
+ out_proj_weight=self.c_proj.weight,
86
+ out_proj_bias=self.c_proj.bias,
87
+ use_separate_proj_weight=True,
88
+ training=self.training,
89
+ need_weights=False
90
+ )
91
+ return x.squeeze(0)
92
+
93
+
94
+ class ModifiedResNet(nn.Module):
95
+ """
96
+ A ResNet class that is similar to torchvision's but contains the following changes:
97
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
98
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
99
+ - The final pooling layer is a QKV attention instead of an average pool
100
+ """
101
+
102
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
103
+ super().__init__()
104
+ self.output_dim = output_dim
105
+ self.input_resolution = input_resolution
106
+
107
+ # the 3-layer stem
108
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
109
+ self.bn1 = nn.BatchNorm2d(width // 2)
110
+ self.relu1 = nn.ReLU(inplace=True)
111
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
112
+ self.bn2 = nn.BatchNorm2d(width // 2)
113
+ self.relu2 = nn.ReLU(inplace=True)
114
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
115
+ self.bn3 = nn.BatchNorm2d(width)
116
+ self.relu3 = nn.ReLU(inplace=True)
117
+ self.avgpool = nn.AvgPool2d(2)
118
+
119
+ # residual layers
120
+ self._inplanes = width # this is a *mutable* variable used during construction
121
+ self.layer1 = self._make_layer(width, layers[0])
122
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
123
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
124
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
125
+
126
+ embed_dim = width * 32 # the ResNet feature dimension
127
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
128
+
129
+ def _make_layer(self, planes, blocks, stride=1):
130
+ layers = [Bottleneck(self._inplanes, planes, stride)]
131
+
132
+ self._inplanes = planes * Bottleneck.expansion
133
+ for _ in range(1, blocks):
134
+ layers.append(Bottleneck(self._inplanes, planes))
135
+
136
+ return nn.Sequential(*layers)
137
+
138
+ def forward(self, x):
139
+ def stem(x):
140
+ x = self.relu1(self.bn1(self.conv1(x)))
141
+ x = self.relu2(self.bn2(self.conv2(x)))
142
+ x = self.relu3(self.bn3(self.conv3(x)))
143
+ x = self.avgpool(x)
144
+ return x
145
+
146
+ x = x.type(self.conv1.weight.dtype)
147
+ x = stem(x)
148
+ x = self.layer1(x)
149
+ x = self.layer2(x)
150
+ x = self.layer3(x)
151
+ x = self.layer4(x)
152
+ x = self.attnpool(x)
153
+
154
+ return x
155
+
156
+
157
+ class LayerNorm(nn.LayerNorm):
158
+ """Subclass torch's LayerNorm to handle fp16."""
159
+
160
+ def forward(self, x: torch.Tensor):
161
+ orig_type = x.dtype
162
+ ret = super().forward(x.type(torch.float32))
163
+ return ret.type(orig_type)
164
+
165
+
166
+ class QuickGELU(nn.Module):
167
+ def forward(self, x: torch.Tensor):
168
+ return x * torch.sigmoid(1.702 * x)
169
+
170
+
171
+ class ResidualAttentionBlock(nn.Module):
172
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
173
+ super().__init__()
174
+
175
+ self.attn = nn.MultiheadAttention(d_model, n_head)
176
+ self.ln_1 = LayerNorm(d_model)
177
+ self.mlp = nn.Sequential(OrderedDict([
178
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
179
+ ("gelu", QuickGELU()),
180
+ ("c_proj", nn.Linear(d_model * 4, d_model))
181
+ ]))
182
+ self.ln_2 = LayerNorm(d_model)
183
+ self.attn_mask = attn_mask
184
+
185
+ def attention(self, x: torch.Tensor):
186
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
187
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
188
+
189
+ def forward(self, x: torch.Tensor):
190
+ x = x + self.attention(self.ln_1(x))
191
+ x = x + self.mlp(self.ln_2(x))
192
+ return x
193
+
194
+
195
+ class Transformer(nn.Module):
196
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
197
+ super().__init__()
198
+ self.width = width
199
+ self.layers = layers
200
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
201
+
202
+ def forward(self, x: torch.Tensor):
203
+ out = {}
204
+ for idx, layer in enumerate(self.resblocks.children()):
205
+ x = layer(x)
206
+ out['layer'+str(idx)] = x[0] # shape:LND. choose cls token feature
207
+ return out, x
208
+
209
+ # return self.resblocks(x) # This is the original code
210
+
211
+
212
+ class VisionTransformer(nn.Module):
213
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
214
+ super().__init__()
215
+ self.input_resolution = input_resolution
216
+ self.output_dim = output_dim
217
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
218
+
219
+ scale = width ** -0.5
220
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
221
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
222
+ self.ln_pre = LayerNorm(width)
223
+
224
+ self.transformer = Transformer(width, layers, heads)
225
+
226
+ self.ln_post = LayerNorm(width)
227
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
228
+
229
+
230
+
231
+ def forward(self, x: torch.Tensor):
232
+ x = self.conv1(x) # shape = [*, width, grid, grid]
233
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
234
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
235
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
236
+ x = x + self.positional_embedding.to(x.dtype)
237
+ x = self.ln_pre(x)
238
+
239
+ x = x.permute(1, 0, 2) # NLD -> LND
240
+ out, x = self.transformer(x)
241
+ x = x.permute(1, 0, 2) # LND -> NLD
242
+
243
+ x = self.ln_post(x[:, 0, :])
244
+
245
+
246
+ out['before_projection'] = x
247
+
248
+ if self.proj is not None:
249
+ x = x @ self.proj
250
+ out['after_projection'] = x
251
+
252
+ # Return both intermediate features and final clip feature
253
+ # return out
254
+
255
+ # This only returns CLIP features
256
+ return x
257
+
258
+
259
+ class CLIP(nn.Module):
260
+ def __init__(self,
261
+ embed_dim: int,
262
+ # vision
263
+ image_resolution: int,
264
+ vision_layers: Union[Tuple[int, int, int, int], int],
265
+ vision_width: int,
266
+ vision_patch_size: int,
267
+ # text
268
+ context_length: int,
269
+ vocab_size: int,
270
+ transformer_width: int,
271
+ transformer_heads: int,
272
+ transformer_layers: int
273
+ ):
274
+ super().__init__()
275
+
276
+ self.context_length = context_length
277
+
278
+ if isinstance(vision_layers, (tuple, list)):
279
+ vision_heads = vision_width * 32 // 64
280
+ self.visual = ModifiedResNet(
281
+ layers=vision_layers,
282
+ output_dim=embed_dim,
283
+ heads=vision_heads,
284
+ input_resolution=image_resolution,
285
+ width=vision_width
286
+ )
287
+ else:
288
+ vision_heads = vision_width // 64
289
+ self.visual = VisionTransformer(
290
+ input_resolution=image_resolution,
291
+ patch_size=vision_patch_size,
292
+ width=vision_width,
293
+ layers=vision_layers,
294
+ heads=vision_heads,
295
+ output_dim=embed_dim
296
+ )
297
+
298
+ self.transformer = Transformer(
299
+ width=transformer_width,
300
+ layers=transformer_layers,
301
+ heads=transformer_heads,
302
+ attn_mask=self.build_attention_mask()
303
+ )
304
+
305
+ self.vocab_size = vocab_size
306
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
307
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
308
+ self.ln_final = LayerNorm(transformer_width)
309
+
310
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
311
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
312
+
313
+ self.initialize_parameters()
314
+
315
+ def initialize_parameters(self):
316
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
317
+ nn.init.normal_(self.positional_embedding, std=0.01)
318
+
319
+ if isinstance(self.visual, ModifiedResNet):
320
+ if self.visual.attnpool is not None:
321
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
322
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
323
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
324
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
325
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
326
+
327
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
328
+ for name, param in resnet_block.named_parameters():
329
+ if name.endswith("bn3.weight"):
330
+ nn.init.zeros_(param)
331
+
332
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
333
+ attn_std = self.transformer.width ** -0.5
334
+ fc_std = (2 * self.transformer.width) ** -0.5
335
+ for block in self.transformer.resblocks:
336
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
337
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
338
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
339
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
340
+
341
+ if self.text_projection is not None:
342
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
343
+
344
+ def build_attention_mask(self):
345
+ # lazily create causal attention mask, with full attention between the vision tokens
346
+ # pytorch uses additive attention mask; fill with -inf
347
+ mask = torch.empty(self.context_length, self.context_length)
348
+ mask.fill_(float("-inf"))
349
+ mask.triu_(1) # zero out the lower diagonal
350
+ return mask
351
+
352
+ @property
353
+ def dtype(self):
354
+ return self.visual.conv1.weight.dtype
355
+
356
+ def encode_image(self, image):
357
+ return self.visual(image.type(self.dtype))
358
+
359
+ def encode_text(self, text):
360
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
361
+
362
+ x = x + self.positional_embedding.type(self.dtype)
363
+ x = x.permute(1, 0, 2) # NLD -> LND
364
+ x = self.transformer(x)
365
+ x = x.permute(1, 0, 2) # LND -> NLD
366
+ x = self.ln_final(x).type(self.dtype)
367
+
368
+ # x.shape = [batch_size, n_ctx, transformer.width]
369
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
370
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
371
+
372
+ return x
373
+
374
+ def forward(self, image, text):
375
+ image_features = self.encode_image(image)
376
+ text_features = self.encode_text(text)
377
+
378
+ # normalized features
379
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
380
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
381
+
382
+ # cosine similarity as logits
383
+ logit_scale = self.logit_scale.exp()
384
+ logits_per_image = logit_scale * image_features @ text_features.t()
385
+ logits_per_text = logits_per_image.t()
386
+
387
+ # shape = [global_batch_size, global_batch_size]
388
+ return logits_per_image, logits_per_text
389
+
390
+
391
+ def convert_weights(model: nn.Module):
392
+ """Convert applicable model parameters to fp16"""
393
+
394
+ def _convert_weights_to_fp16(l):
395
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
396
+ l.weight.data = l.weight.data.half()
397
+ if l.bias is not None:
398
+ l.bias.data = l.bias.data.half()
399
+
400
+ if isinstance(l, nn.MultiheadAttention):
401
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
402
+ tensor = getattr(l, attr)
403
+ if tensor is not None:
404
+ tensor.data = tensor.data.half()
405
+
406
+ for name in ["text_projection", "proj"]:
407
+ if hasattr(l, name):
408
+ attr = getattr(l, name)
409
+ if attr is not None:
410
+ attr.data = attr.data.half()
411
+
412
+ model.apply(_convert_weights_to_fp16)
413
+
414
+
415
+ def build_model(state_dict: dict):
416
+ vit = "visual.proj" in state_dict
417
+
418
+ if vit:
419
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
420
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
421
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
422
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
423
+ image_resolution = vision_patch_size * grid_size
424
+ else:
425
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
426
+ vision_layers = tuple(counts)
427
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
428
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
429
+ vision_patch_size = None
430
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
431
+ image_resolution = output_width * 32
432
+
433
+ embed_dim = state_dict["text_projection"].shape[1]
434
+ context_length = state_dict["positional_embedding"].shape[0]
435
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
436
+ transformer_width = state_dict["ln_final.weight"].shape[0]
437
+ transformer_heads = transformer_width // 64
438
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
439
+
440
+ model = CLIP(
441
+ embed_dim,
442
+ image_resolution, vision_layers, vision_width, vision_patch_size,
443
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
444
+ )
445
+
446
+ for key in ["input_resolution", "context_length", "vocab_size"]:
447
+ if key in state_dict:
448
+ del state_dict[key]
449
+
450
+ convert_weights(model)
451
+ model.load_state_dict(state_dict)
452
+ return model.eval()
models/clip/simple_tokenizer.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ from functools import lru_cache
5
+
6
+ import ftfy
7
+ import regex as re
8
+
9
+
10
+ @lru_cache()
11
+ def default_bpe():
12
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
13
+
14
+
15
+ @lru_cache()
16
+ def bytes_to_unicode():
17
+ """
18
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
19
+ The reversible bpe codes work on unicode strings.
20
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
21
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
22
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
23
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
24
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
25
+ """
26
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
27
+ cs = bs[:]
28
+ n = 0
29
+ for b in range(2**8):
30
+ if b not in bs:
31
+ bs.append(b)
32
+ cs.append(2**8+n)
33
+ n += 1
34
+ cs = [chr(n) for n in cs]
35
+ return dict(zip(bs, cs))
36
+
37
+
38
+ def get_pairs(word):
39
+ """Return set of symbol pairs in a word.
40
+ Word is represented as tuple of symbols (symbols being variable-length strings).
41
+ """
42
+ pairs = set()
43
+ prev_char = word[0]
44
+ for char in word[1:]:
45
+ pairs.add((prev_char, char))
46
+ prev_char = char
47
+ return pairs
48
+
49
+
50
+ def basic_clean(text):
51
+ text = ftfy.fix_text(text)
52
+ text = html.unescape(html.unescape(text))
53
+ return text.strip()
54
+
55
+
56
+ def whitespace_clean(text):
57
+ text = re.sub(r'\s+', ' ', text)
58
+ text = text.strip()
59
+ return text
60
+
61
+
62
+ class SimpleTokenizer(object):
63
+ def __init__(self, bpe_path: str = default_bpe()):
64
+ self.byte_encoder = bytes_to_unicode()
65
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
66
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
67
+ merges = merges[1:49152-256-2+1]
68
+ merges = [tuple(merge.split()) for merge in merges]
69
+ vocab = list(bytes_to_unicode().values())
70
+ vocab = vocab + [v+'</w>' for v in vocab]
71
+ for merge in merges:
72
+ vocab.append(''.join(merge))
73
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
74
+ self.encoder = dict(zip(vocab, range(len(vocab))))
75
+ self.decoder = {v: k for k, v in self.encoder.items()}
76
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
77
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
78
+ self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
79
+
80
+ def bpe(self, token):
81
+ if token in self.cache:
82
+ return self.cache[token]
83
+ word = tuple(token[:-1]) + ( token[-1] + '</w>',)
84
+ pairs = get_pairs(word)
85
+
86
+ if not pairs:
87
+ return token+'</w>'
88
+
89
+ while True:
90
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
91
+ if bigram not in self.bpe_ranks:
92
+ break
93
+ first, second = bigram
94
+ new_word = []
95
+ i = 0
96
+ while i < len(word):
97
+ try:
98
+ j = word.index(first, i)
99
+ new_word.extend(word[i:j])
100
+ i = j
101
+ except:
102
+ new_word.extend(word[i:])
103
+ break
104
+
105
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
106
+ new_word.append(first+second)
107
+ i += 2
108
+ else:
109
+ new_word.append(word[i])
110
+ i += 1
111
+ new_word = tuple(new_word)
112
+ word = new_word
113
+ if len(word) == 1:
114
+ break
115
+ else:
116
+ pairs = get_pairs(word)
117
+ word = ' '.join(word)
118
+ self.cache[token] = word
119
+ return word
120
+
121
+ def encode(self, text):
122
+ bpe_tokens = []
123
+ text = whitespace_clean(basic_clean(text)).lower()
124
+ for token in re.findall(self.pat, text):
125
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
126
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
127
+ return bpe_tokens
128
+
129
+ def decode(self, tokens):
130
+ text = ''.join([self.decoder[token] for token in tokens])
131
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
132
+ return text
models/clip_models.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .clip import clip
2
+ from PIL import Image
3
+ import torch.nn as nn
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from models.transformer_attention import TransformerAttention
7
+ import torchvision.transforms as transforms
8
+ from .clip.model import VisionTransformer
9
+ from .mlp import MLP
10
+
11
+ CHANNELS = {
12
+ "RN50" : 1024,
13
+ "ViT-L/14" : 768,
14
+ "ViT-L/14-penultimate" : 1024
15
+ }
16
+
17
+
18
+ MEAN = {
19
+ "imagenet":[0.485, 0.456, 0.406],
20
+ "clip":[0.48145466, 0.4578275, 0.40821073]
21
+ }
22
+
23
+ STD = {
24
+ "imagenet":[0.229, 0.224, 0.225],
25
+ "clip":[0.26862954, 0.26130258, 0.27577711]
26
+ }
27
+
28
+ class CLIPModel(nn.Module):
29
+ """UFD"""
30
+ def __init__(self, name, num_classes=1):
31
+ super(CLIPModel, self).__init__()
32
+
33
+ self.model, self.preprocess = clip.load(name, device="cpu") # self.preprecess will not be used during training, which is handled in Dataset class
34
+ self.fc = nn.Linear( CHANNELS[name], num_classes )
35
+
36
+
37
+ def forward(self, x, return_feature=False):
38
+ features = self.model.encode_image(x)
39
+ if return_feature:
40
+ return features
41
+ return self.fc(features)
42
+
43
+
44
+ class CLIPModelPenultimateLayer(nn.Module):
45
+ def __init__(self, name, num_classes=1):
46
+ super(CLIPModelPenultimateLayer, self).__init__()
47
+
48
+ self.model, self.preprocess = clip.load(name, device="cpu") # self.preprecess will not be used during training, which is handled in Dataset class
49
+ self.register_hook()
50
+ self.fc = nn.Linear(CHANNELS[name+"-penultimate"], num_classes)
51
+
52
+ def register_hook(self):
53
+
54
+ def hook(module, input, output):
55
+ self.features = torch.clone(output)
56
+ for name, module in self.model.visual.named_children():
57
+ if name == "ln_post":
58
+ module.register_forward_hook(hook)
59
+ return
60
+
61
+ def forward(self, x):
62
+ self.model.encode_image(x)
63
+ return self.fc(self.features)
64
+
65
+
66
+
67
+ class CLIPModelShuffleAttentionPenultimateLayer(nn.Module):
68
+ def __init__(self, name, num_classes=1,shuffle_times=1, patch_size=32, original_times=1):
69
+ super(CLIPModelShuffleAttentionPenultimateLayer, self).__init__()
70
+ self.name = name
71
+ self.num_classes = num_classes
72
+ self.shuffle_times = shuffle_times
73
+ self.original_times = original_times
74
+ self.patch_size = patch_size
75
+ self.model, self.preprocess = clip.load(name, device="cpu") # self.preprecess will not be used during training, which is handled in Dataset class
76
+ self.register_hook()
77
+ self.attention_head = TransformerAttention(CHANNELS[name+"-penultimate"], shuffle_times + original_times, last_dim=num_classes)
78
+ for name, param in self.model.named_parameters():
79
+ param.requires_grad = False
80
+
81
+ def register_hook(self):
82
+
83
+ def hook(module, input, output):
84
+ self.features = torch.clone(output)
85
+ for name, module in self.model.visual.named_children():
86
+ if name == "ln_post":
87
+ module.register_forward_hook(hook)
88
+ return
89
+
90
+ def shuffle_patches(self, x, patch_size):
91
+ B, C, H, W = x.size()
92
+ # Unfold the input tensor to extract non-overlapping patches
93
+ patches = F.unfold(x, kernel_size=patch_size, stride=patch_size, dilation=1)
94
+ # Reshape the patches to (B, C, patch_H, patch_W, num_patches)
95
+ shuffled_patches = patches[:, :, torch.randperm(patches.size(-1))]
96
+ # Fold the shuffled patches back into images
97
+ shuffled_images = F.fold(shuffled_patches, output_size=(H, W), kernel_size=patch_size, stride=patch_size)
98
+ return shuffled_images
99
+
100
+
101
+ def forward(self, x, return_feature=False):
102
+ features = []
103
+ with torch.no_grad():
104
+ for i in range(self.shuffle_times):
105
+ self.model.encode_image(self.shuffle_patches(x, patch_size=self.patch_size[0]))
106
+ features.append(self.features)
107
+
108
+ self.model.encode_image(x)
109
+ for i in range(self.original_times):
110
+ features.append(self.features.clone())
111
+ features = self.attention_head(torch.stack(features, dim=-2))
112
+
113
+ return features
114
+
115
+
models/delete/vgg.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import Union, List, Dict, Any, cast
4
+ import torchvision
5
+ import torch.nn.functional as F
6
+
7
+
8
+
9
+
10
+
11
+ class VGG(torch.nn.Module):
12
+ def __init__(self, arch_type, pretrained, progress):
13
+ super().__init__()
14
+
15
+ self.layer1 = torch.nn.Sequential()
16
+ self.layer2 = torch.nn.Sequential()
17
+ self.layer3 = torch.nn.Sequential()
18
+ self.layer4 = torch.nn.Sequential()
19
+ self.layer5 = torch.nn.Sequential()
20
+
21
+ if arch_type == 'vgg11':
22
+ official_vgg = torchvision.models.vgg11(pretrained=pretrained, progress=progress)
23
+ blocks = [ [0,2], [2,5], [5,10], [10,15], [15,20] ]
24
+ last_idx = 20
25
+ elif arch_type == 'vgg19':
26
+ official_vgg = torchvision.models.vgg19(pretrained=pretrained, progress=progress)
27
+ blocks = [ [0,4], [4,9], [9,18], [18,27], [27,36] ]
28
+ last_idx = 36
29
+ else:
30
+ raise NotImplementedError
31
+
32
+
33
+ for x in range( *blocks[0] ):
34
+ self.layer1.add_module(str(x), official_vgg.features[x])
35
+ for x in range( *blocks[1] ):
36
+ self.layer2.add_module(str(x), official_vgg.features[x])
37
+ for x in range( *blocks[2] ):
38
+ self.layer3.add_module(str(x), official_vgg.features[x])
39
+ for x in range( *blocks[3] ):
40
+ self.layer4.add_module(str(x), official_vgg.features[x])
41
+ for x in range( *blocks[4] ):
42
+ self.layer5.add_module(str(x), official_vgg.features[x])
43
+
44
+ self.max_pool = official_vgg.features[last_idx]
45
+ self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
46
+
47
+ self.fc1 = official_vgg.classifier[0]
48
+ self.fc2 = official_vgg.classifier[3]
49
+ self.fc3 = official_vgg.classifier[6]
50
+ self.dropout = nn.Dropout()
51
+
52
+
53
+ def forward(self, x):
54
+ out = {}
55
+
56
+ x = self.layer1(x)
57
+ out['f0'] = x
58
+
59
+ x = self.layer2(x)
60
+ out['f1'] = x
61
+
62
+ x = self.layer3(x)
63
+ out['f2'] = x
64
+
65
+ x = self.layer4(x)
66
+ out['f3'] = x
67
+
68
+ x = self.layer5(x)
69
+ out['f4'] = x
70
+
71
+ x = self.max_pool(x)
72
+ x = self.avgpool(x)
73
+ x = x.view(-1,512*7*7)
74
+
75
+ x = self.fc1(x)
76
+ x = F.relu(x)
77
+ x = self.dropout(x)
78
+ x = self.fc2(x)
79
+ x = F.relu(x)
80
+ out['penultimate'] = x
81
+ x = self.dropout(x)
82
+ x = self.fc3(x)
83
+ out['logits'] = x
84
+
85
+ return out
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+ def vgg11(pretrained=False, progress=True):
97
+ r"""VGG 11-layer model (configuration "A") from
98
+ `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
99
+
100
+ Args:
101
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
102
+ progress (bool): If True, displays a progress bar of the download to stderr
103
+ """
104
+ return VGG('vgg11', pretrained, progress)
105
+
106
+
107
+
108
+ def vgg19(pretrained=False, progress=True):
109
+ r"""VGG 19-layer model (configuration "E")
110
+ `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
111
+
112
+ Args:
113
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
114
+ progress (bool): If True, displays a progress bar of the download to stderr
115
+ """
116
+ return VGG('vgg19', pretrained, progress)
117
+
118
+
119
+
120
+
models/imagenet_models.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .resnet import resnet18, resnet34, resnet50, resnet101, resnet152
2
+ from .vision_transformer import vit_b_16, vit_b_32, vit_l_16, vit_l_32
3
+
4
+ from torchvision import transforms
5
+ from PIL import Image
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+
10
+ model_dict = {
11
+ 'resnet18': resnet18,
12
+ 'resnet34': resnet34,
13
+ 'resnet50': resnet50,
14
+ 'resnet101': resnet101,
15
+ 'resnet152': resnet152,
16
+ 'vit_b_16': vit_b_16,
17
+ 'vit_b_32': vit_b_32,
18
+ 'vit_l_16': vit_l_16,
19
+ 'vit_l_32': vit_l_32
20
+ }
21
+
22
+
23
+ CHANNELS = {
24
+ "resnet50" : 2048,
25
+ "vit_b_16" : 768,
26
+ }
27
+
28
+
29
+
30
+ class ImagenetModel(nn.Module):
31
+ def __init__(self, name, num_classes=1):
32
+ super(ImagenetModel, self).__init__()
33
+
34
+ self.model = model_dict[name](pretrained=True)
35
+ self.fc = nn.Linear(CHANNELS[name], num_classes) #manually define a fc layer here
36
+
37
+
38
+ def forward(self, x):
39
+ feature = self.model(x)["penultimate"]
40
+ return self.fc(feature)
models/mlp.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ class MLP(nn.Module):
6
+ def __init__(self, input_size, h_sizes, output_size):
7
+ super(MLP, self).__init__()
8
+ self.input = nn.Linear(input_size, h_sizes[0])
9
+ self.hidden = nn.ModuleList([nn.Linear(h_sizes[i], h_sizes[i+1]) for i in range(len(h_sizes) - 1)])
10
+ self.output = nn.Linear(h_sizes[-1], output_size)
11
+
12
+ def forward(self, x):
13
+ x = F.relu(self.input(x))
14
+ for layer in self.hidden:
15
+ x = F.relu(layer(x))
16
+ x = self.output(x)
17
+ return x
18
+
models/moco_models.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ import torchvision.transforms as transforms
4
+ import os
5
+ from models import vits
6
+ from models.transformer_attention import TransformerAttention
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.parallel
10
+ import torch.optim
11
+ import torch.utils.data
12
+ import torch.utils.data.distributed
13
+ import torchvision.transforms as transforms
14
+ import torchvision.models as torchvision_models
15
+ import torch.nn.functional as F
16
+ import models.moco_v1.builder as builder
17
+ import torchvision.models as models
18
+
19
+
20
+ CHANNELS = {
21
+ "MOCO" : 128,
22
+ "ViT-L/14" : 768
23
+ }
24
+
25
+ MEAN = {
26
+ "imagenet":[0.485, 0.456, 0.406],
27
+ "clip":[0.48145466, 0.4578275, 0.40821073]
28
+ }
29
+
30
+ STD = {
31
+ "imagenet":[0.229, 0.224, 0.225],
32
+ "clip":[0.26862954, 0.26130258, 0.27577711]
33
+ }
34
+
35
+
36
+
37
+ class MOCOModel_v3(nn.Module):
38
+ def __init__(self, opt, num_classes=1):
39
+ super(MOCOModel_v3, self).__init__()
40
+ self.opt = opt
41
+ model_root = "path to your moco pretrained weight"
42
+ self.model = self.create_model(model_root) # self.preprecess will not be used during training, which is handled in Dataset class
43
+ normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
44
+ self.preprocess = transforms.Compose([
45
+ transforms.Resize([224, 224]),
46
+ transforms.ToTensor(),
47
+ normalize,
48
+ ])
49
+
50
+ def create_model(self, model_root):
51
+ opt = self.opt
52
+ opt.pretrained = model_root
53
+ dim_in = None
54
+ # create model
55
+ print("=> creating model '{}'".format(opt.arch))
56
+ if opt.arch.lower().find('vit') != -1:
57
+ model = vits.__dict__["vit_base"]()
58
+ linear_keyword = 'head'
59
+ else:
60
+ model = torchvision_models.__dict__[opt.arch]()
61
+ linear_keyword = 'fc'
62
+
63
+ # freeze all layers and remove the last fc
64
+ remove_name = None
65
+ for name, param in model.named_parameters():
66
+ if name not in ['%s.weight' % linear_keyword, '%s.bias' % linear_keyword]:
67
+ param.requires_grad = False
68
+ model.head = nn.Linear(model.head.weight.shape[-1], 1)
69
+ self.fc = model.head
70
+
71
+ # init the fc layer
72
+ getattr(model, linear_keyword).weight.data.normal_(mean=0.0, std=0.01)
73
+ getattr(model, linear_keyword).bias.data.zero_()
74
+
75
+ # load from pre-trained, before DistributedDataParallel constructor
76
+ if opt.pretrained:
77
+ if os.path.isfile(opt.pretrained):
78
+ print("=> loading checkpoint '{}'".format(opt.pretrained))
79
+ checkpoint = torch.load(opt.pretrained, map_location="cpu")
80
+
81
+ # rename moco pre-trained keys
82
+ state_dict = checkpoint['state_dict']
83
+ for k in list(state_dict.keys()):
84
+ # retain only base_encoder up to before the embedding layer
85
+ if k.startswith('module.base_encoder') and not k.startswith('module.base_encoder.%s' % linear_keyword):
86
+ # remove prefix
87
+ state_dict[k[len("module.base_encoder."):]] = state_dict[k]
88
+ # delete renamed or unused k
89
+ del state_dict[k]
90
+
91
+ opt.start_epoch = 0
92
+ msg = model.load_state_dict(state_dict, strict=False)
93
+ assert set(msg.missing_keys) == {"%s.weight" % linear_keyword, "%s.bias" % linear_keyword}
94
+
95
+ print("=> loaded pre-trained model '{}'".format(opt.pretrained))
96
+ else:
97
+ print("=> no checkpoint found at '{}'".format(opt.pretrained))
98
+
99
+
100
+
101
+ return model
102
+
103
+
104
+ def forward(self, x, return_feature=False):
105
+ features = self.model(x)
106
+ return features
107
+
108
+
109
+
110
+ class MOCOModel_v3_ShuffleAttention(nn.Module):
111
+ def __init__(self, opt, num_classes=1, shuffle_times=3):
112
+ self.shuffle_times = shuffle_times
113
+ super(MOCOModel_v3_ShuffleAttention, self).__init__()
114
+ self.opt = opt
115
+ self.attention_head = TransformerAttention(768, shuffle_times, 1)
116
+ model_root = "path to your moco pretrained weight"
117
+ self.model = self.create_model(model_root) # self.preprecess will not be used during training, which is handled in Dataset class
118
+ normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
119
+ self.preprocess = transforms.Compose([
120
+ transforms.Resize([224, 224]),
121
+ transforms.ToTensor(),
122
+ normalize,
123
+ ])
124
+
125
+ def create_model(self, model_root):
126
+ opt = self.opt
127
+ opt.pretrained = model_root
128
+ dim_in = None
129
+ # create model
130
+ print("=> creating model '{}'".format(opt.arch))
131
+ if opt.arch.lower().find('vit') != -1:
132
+ model = vits.__dict__["vit_base"]()
133
+ linear_keyword = 'head'
134
+ else:
135
+ model = torchvision_models.__dict__[opt.arch]()
136
+ linear_keyword = 'fc'
137
+
138
+ # init the fc layer
139
+ # getattr(model, linear_keyword).weight.data.one_()
140
+ # getattr(model, linear_keyword).bias.data.zero_()
141
+ for name, param in model.named_parameters():
142
+ # if name not in ['%s.weight' % linear_keyword, '%s.bias' % linear_keyword]:
143
+ param.requires_grad = False
144
+
145
+
146
+ # load from pre-trained, before DistributedDataParallel constructor
147
+ if opt.pretrained:
148
+ if os.path.isfile(opt.pretrained):
149
+ print("=> loading checkpoint '{}'".format(opt.pretrained))
150
+ checkpoint = torch.load(opt.pretrained, map_location="cpu")
151
+
152
+ # rename moco pre-trained keys
153
+ state_dict = checkpoint['state_dict']
154
+ for k in list(state_dict.keys()):
155
+ # retain only base_encoder up to before the embedding layer
156
+ if k.startswith('module.base_encoder') and not k.startswith('module.base_encoder.%s' % linear_keyword):
157
+ # remove prefix
158
+ state_dict[k[len("module.base_encoder."):]] = state_dict[k]
159
+ # delete renamed or unused k
160
+ del state_dict[k]
161
+
162
+ opt.start_epoch = 0
163
+ msg = model.load_state_dict(state_dict, strict=False)
164
+ assert set(msg.missing_keys) == {"%s.weight" % linear_keyword, "%s.bias" % linear_keyword}
165
+
166
+ print("=> loaded pre-trained model '{}'".format(opt.pretrained))
167
+ else:
168
+ print("=> no checkpoint found at '{}'".format(opt.pretrained))
169
+
170
+ # remove last layer
171
+ model.head = nn.Identity()
172
+
173
+
174
+ return model
175
+
176
+ def shuffle_patches(self, x, patch_size):
177
+ B, C, H, W = x.size()
178
+ # Unfold the input tensor to extract non-overlapping patches
179
+ patches = F.unfold(x, kernel_size=patch_size, stride=patch_size, dilation=1)
180
+ # Reshape the patches to (B, C, patch_H, patch_W, num_patches)
181
+ shuffled_patches = patches[:, :, torch.randperm(patches.size(-1))]
182
+ # Fold the shuffled patches back into images
183
+ shuffled_images = F.fold(shuffled_patches, output_size=(H, W), kernel_size=patch_size, stride=patch_size)
184
+ return shuffled_images
185
+
186
+
187
+ def forward(self, x, return_feature=False):
188
+ features = []
189
+ for i in range(self.shuffle_times):
190
+ features.append(self.model(self.shuffle_patches(x, patch_size=32)))
191
+ features = self.attention_head(torch.stack(features, dim=-2))
192
+ return features
193
+
194
+
195
+
196
+
197
+
198
+ class MOCOModel_v1(nn.Module):
199
+ def __init__(self, num_classes=1):
200
+ super(MOCOModel_v1, self).__init__()
201
+ model_root = "path to your moco pretrained weight"
202
+ self.model = self.create_model(model_root) # self.preprecess will not be used during training, which is handled in Dataset class
203
+ self.fc = nn.Linear( CHANNELS["MOCO"], num_classes)
204
+
205
+
206
+ def create_model(self, model_root):
207
+ print("=> creating model '{}'".format("resnet50"))
208
+ model = builder.MoCo(
209
+ models.__dict__["resnet50"],
210
+ 128,
211
+ 65536,
212
+ 0.999,
213
+ 0.07,
214
+ False,
215
+ )
216
+
217
+ model = model.encoder_q
218
+ pretrained_dict = torch.load(model_root, map_location="cpu")["state_dict"]
219
+ model_dict = model.state_dict()
220
+
221
+ # Create a new dictionary that maps the keys in the pretrained model to the keys in the built model
222
+ new_dict = {}
223
+ for k, v in pretrained_dict.items():
224
+ if 'module.encoder_q' in k:
225
+ k = k.replace('module.encoder_q.', '')
226
+ new_dict[k] = v
227
+
228
+ # Load the pretrained weights into the built model
229
+ model_dict.update(new_dict)
230
+ model.load_state_dict(model_dict)
231
+
232
+
233
+ return model
234
+
235
+
236
+ def forward(self, x, return_feature=False):
237
+ features = self.model(x)
238
+ if return_feature:
239
+ return features
240
+ return self.fc(features)
241
+
242
+
243
+
244
+
245
+
246
+ class MOCOModel_v1_ShuffleAttention(nn.Module):
247
+ def __init__(self, num_classes=1,shuffle_times=3):
248
+ super(MOCOModel_v1_ShuffleAttention, self).__init__()
249
+ model_root = "path to your moco pretrained weight"
250
+ self.model = self.create_model(model_root) # self.preprecess will not be used during training, which is handled in Dataset class
251
+ self.shuffle_times = shuffle_times
252
+ self.attention_head = TransformerAttention(CHANNELS["MOCO"], shuffle_times + 1, 1)
253
+ for name, param in self.model.named_parameters():
254
+ param.requires_grad = False
255
+
256
+ def create_model(self, model_root):
257
+ print("=> creating model '{}'".format("resnet50"))
258
+ model = builder.MoCo(
259
+ models.__dict__["resnet50"],
260
+ 128,
261
+ 65536,
262
+ 0.999,
263
+ 0.07,
264
+ False,
265
+ )
266
+
267
+ model = model.encoder_q
268
+ pretrained_dict = torch.load(model_root, map_location="cpu")["state_dict"]
269
+ model_dict = model.state_dict()
270
+
271
+ # Create a new dictionary that maps the keys in the pretrained model to the keys in the built model
272
+ new_dict = {}
273
+ for k, v in pretrained_dict.items():
274
+ if 'module.encoder_q' in k:
275
+ k = k.replace('module.encoder_q.', '')
276
+ new_dict[k] = v
277
+
278
+ # Load the pretrained weights into the built model
279
+ model_dict.update(new_dict)
280
+ model.load_state_dict(model_dict)
281
+
282
+
283
+ return model
284
+
285
+
286
+ def shuffle_patches(self, x, patch_size):
287
+ B, C, H, W = x.size()
288
+ # Unfold the input tensor to extract non-overlapping patches
289
+ patches = F.unfold(x, kernel_size=patch_size, stride=patch_size, dilation=1)
290
+ # Reshape the patches to (B, C, patch_H, patch_W, num_patches)
291
+ shuffled_patches = patches[:, :, torch.randperm(patches.size(-1))]
292
+ # Fold the shuffled patches back into images
293
+ shuffled_images = F.fold(shuffled_patches, output_size=(H, W), kernel_size=patch_size, stride=patch_size)
294
+ return shuffled_images
295
+
296
+
297
+ def forward(self, x, return_feature=False):
298
+ features = []
299
+ for i in range(self.shuffle_times):
300
+ features.append(self.model(self.shuffle_patches(x, patch_size=32)))
301
+ features.append(self.model(x))
302
+ features = self.attention_head(torch.stack(features, dim=-2))
303
+ return features
304
+
305
+
306
+
307
+ class MOCOModel_v1_PatchesAttention(nn.Module):
308
+ def __init__(self, num_classes=1, divide_nums=3):
309
+ super(MOCOModel_v1_PatchesAttention, self).__init__()
310
+ self.divide_nums = divide_nums
311
+ model_root = "path to your moco pretrained weight"
312
+ self.model = self.create_model(model_root) # self.preprecess will not be used during training, which is handled in Dataset class
313
+ self.normal = transforms.Normalize( mean=MEAN["imagenet"], std=STD["imagenet"] )
314
+ self.attention_head = TransformerAttention(CHANNELS["MOCO"], divide_nums**2 + 1, 1)
315
+ for name, param in self.model.named_parameters():
316
+ param.requires_grad = False
317
+
318
+ def create_model(self, model_root):
319
+ print("=> creating model '{}'".format("resnet50"))
320
+ model = builder.MoCo(
321
+ models.__dict__["resnet50"],
322
+ 128,
323
+ 65536,
324
+ 0.999,
325
+ 0.07,
326
+ False,
327
+ )
328
+
329
+ model = model.encoder_q
330
+ pretrained_dict = torch.load(model_root, map_location="cpu")["state_dict"]
331
+ model_dict = model.state_dict()
332
+
333
+ # Create a new dictionary that maps the keys in the pretrained model to the keys in the built model
334
+ new_dict = {}
335
+ for k, v in pretrained_dict.items():
336
+ if 'module.encoder_q' in k:
337
+ k = k.replace('module.encoder_q.', '')
338
+ new_dict[k] = v
339
+
340
+ # Load the pretrained weights into the built model
341
+ model_dict.update(new_dict)
342
+ model.load_state_dict(model_dict)
343
+
344
+
345
+ return model
346
+
347
+ def divide(self, x):
348
+ patch_size = 224 // self.divide_nums
349
+ patches = []
350
+ for i in range(self.divide_nums):
351
+ for j in range(self.divide_nums):
352
+ patches.append(transforms.Resize([224, 224], antialias=True)(x[:, :, i*patch_size:(i+1)*patch_size, j*patch_size:(j+1)*patch_size]))
353
+ return patches
354
+
355
+
356
+ def forward(self, x, return_feature=False):
357
+ features = []
358
+ patches = self.divide(x)
359
+ for patch in patches:
360
+ features.append(self.model(self.normal(patch)))
361
+ features.append(self.model(self.normal(x)))
362
+ features = self.attention_head(torch.stack(features, dim=-2))
363
+ return features
364
+
models/moco_v1/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
models/moco_v1/builder.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from copy import deepcopy
9
+
10
+
11
+ class MoCo(nn.Module):
12
+ """
13
+ Build a MoCo model with: a query encoder, a key encoder, and a queue
14
+ https://arxiv.org/abs/1911.05722
15
+ """
16
+
17
+ def __init__(self, base_encoder, dim=128, K=65536, m=0.999, T=0.07, mlp=False):
18
+ """
19
+ dim: feature dimension (default: 128)
20
+ K: queue size; number of negative keys (default: 65536)
21
+ m: moco momentum of updating key encoder (default: 0.999)
22
+ T: softmax temperature (default: 0.07)
23
+ """
24
+ super(MoCo, self).__init__()
25
+
26
+ self.K = K
27
+ self.m = m
28
+ self.T = T
29
+
30
+ # create the encoders
31
+ # num_classes is the output fc dimension
32
+ self.encoder_q = base_encoder(num_classes=dim)
33
+ self.encoder_k = base_encoder(num_classes=dim)
34
+
35
+ if mlp: # hack: brute-force replacement
36
+ dim_mlp = self.encoder_q.fc.weight.shape[1]
37
+ self.encoder_q.fc = nn.Sequential(
38
+ nn.Linear(dim_mlp, dim_mlp), nn.ReLU(), self.encoder_q.fc
39
+ )
40
+ self.encoder_k.fc = nn.Sequential(
41
+ nn.Linear(dim_mlp, dim_mlp), nn.ReLU(), self.encoder_k.fc
42
+ )
43
+
44
+ for param_q, param_k in zip(
45
+ self.encoder_q.parameters(), self.encoder_k.parameters()
46
+ ):
47
+ param_k.data.copy_(param_q.data) # initialize
48
+ param_k.requires_grad = False # not update by gradient
49
+
50
+ # create the queue
51
+ self.register_buffer("queue", torch.randn(dim, K))
52
+ self.queue = nn.functional.normalize(self.queue, dim=0)
53
+
54
+ self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long))
55
+
56
+ @torch.no_grad()
57
+ def _momentum_update_key_encoder(self):
58
+ """
59
+ Momentum update of the key encoder
60
+ """
61
+ for param_q, param_k in zip(
62
+ self.encoder_q.parameters(), self.encoder_k.parameters()
63
+ ):
64
+ param_k.data = param_k.data * self.m + param_q.data * (1.0 - self.m)
65
+
66
+ @torch.no_grad()
67
+ def _dequeue_and_enqueue(self, keys):
68
+ # gather keys before updating queue
69
+ keys = concat_all_gather(keys)
70
+
71
+ batch_size = keys.shape[0]
72
+
73
+ ptr = int(self.queue_ptr)
74
+ assert self.K % batch_size == 0 # for simplicity
75
+
76
+ # replace the keys at ptr (dequeue and enqueue)
77
+ self.queue[:, ptr : ptr + batch_size] = keys.T
78
+ ptr = (ptr + batch_size) % self.K # move pointer
79
+
80
+ self.queue_ptr[0] = ptr
81
+
82
+ @torch.no_grad()
83
+ def _batch_shuffle_ddp(self, x):
84
+ """
85
+ Batch shuffle, for making use of BatchNorm.
86
+ *** Only support DistributedDataParallel (DDP) model. ***
87
+ """
88
+ # gather from all gpus
89
+ batch_size_this = x.shape[0]
90
+ x_gather = concat_all_gather(x)
91
+ batch_size_all = x_gather.shape[0]
92
+
93
+ num_gpus = batch_size_all // batch_size_this
94
+
95
+ # random shuffle index
96
+ idx_shuffle = torch.randperm(batch_size_all).cuda()
97
+
98
+ # broadcast to all gpus
99
+ torch.distributed.broadcast(idx_shuffle, src=0)
100
+
101
+ # index for restoring
102
+ idx_unshuffle = torch.argsort(idx_shuffle)
103
+
104
+ # shuffled index for this gpu
105
+ gpu_idx = torch.distributed.get_rank()
106
+ idx_this = idx_shuffle.view(num_gpus, -1)[gpu_idx]
107
+
108
+ return x_gather[idx_this], idx_unshuffle
109
+
110
+ @torch.no_grad()
111
+ def _batch_unshuffle_ddp(self, x, idx_unshuffle):
112
+ """
113
+ Undo batch shuffle.
114
+ *** Only support DistributedDataParallel (DDP) model. ***
115
+ """
116
+ # gather from all gpus
117
+ batch_size_this = x.shape[0]
118
+ x_gather = concat_all_gather(x)
119
+ batch_size_all = x_gather.shape[0]
120
+
121
+ num_gpus = batch_size_all // batch_size_this
122
+
123
+ # restored index for this gpu
124
+ gpu_idx = torch.distributed.get_rank()
125
+ idx_this = idx_unshuffle.view(num_gpus, -1)[gpu_idx]
126
+
127
+ return x_gather[idx_this]
128
+
129
+ def forward(self, im_q, im_k):
130
+ """
131
+ Input:
132
+ im_q: a batch of query images
133
+ im_k: a batch of key images
134
+ Output:
135
+ logits, targets
136
+ """
137
+
138
+ # compute query features
139
+ q = self.encoder_q(im_q) # queries: NxC
140
+ q = nn.functional.normalize(q, dim=1)
141
+
142
+ # compute key features
143
+ with torch.no_grad(): # no gradient to keys
144
+ self._momentum_update_key_encoder() # update the key encoder
145
+
146
+ # shuffle for making use of BN
147
+ im_k, idx_unshuffle = self._batch_shuffle_ddp(im_k)
148
+
149
+ k = self.encoder_k(im_k) # keys: NxC
150
+ k = nn.functional.normalize(k, dim=1)
151
+
152
+ # undo shuffle
153
+ k = self._batch_unshuffle_ddp(k, idx_unshuffle)
154
+
155
+ # compute logits
156
+ # Einstein sum is more intuitive
157
+ # positive logits: Nx1
158
+ l_pos = torch.einsum("nc,nc->n", [q, k]).unsqueeze(-1)
159
+ # negative logits: NxK
160
+ l_neg = torch.einsum("nc,ck->nk", [q, self.queue.clone().detach()])
161
+
162
+ # logits: Nx(1+K)
163
+ logits = torch.cat([l_pos, l_neg], dim=1)
164
+
165
+ # apply temperature
166
+ logits /= self.T
167
+
168
+ # labels: positive key indicators
169
+ labels = torch.zeros(logits.shape[0], dtype=torch.long).cuda()
170
+
171
+ # dequeue and enqueue
172
+ self._dequeue_and_enqueue(k)
173
+
174
+ return logits, labels
175
+
176
+
177
+ class MoCoMAE(nn.Module):
178
+
179
+ def __init__(self, base_encoder, dim=1024, K=65536, m=0.999, T=0.07, norm=False):
180
+ super().__init__()
181
+
182
+ self.K = K
183
+ self.m = m
184
+ self.T = T
185
+ self.norm = norm
186
+
187
+ self.patch_embed = deepcopy(base_encoder.patch_embed)
188
+ self.pos_embed = deepcopy(base_encoder.pos_embed)
189
+ self.encoder_q = deepcopy(base_encoder)
190
+ self.encoder_k = deepcopy(base_encoder)
191
+
192
+ for param_k in self.encoder_k.parameters():
193
+ param_k.requires_grad = False # not update by gradient
194
+ for param_q in self.encoder_q.parameters():
195
+ param_q.requires_grad = False
196
+ for param_q in self.encoder_q.blocks.parameters():
197
+ param_q.requires_grad = True
198
+ self.encoder_q.cls_token.requires_grad = True
199
+
200
+
201
+ # create the queue
202
+ self.register_buffer("queue", torch.randn(dim, K))
203
+ self.queue = nn.functional.normalize(self.queue, dim=0)
204
+
205
+ self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long))
206
+
207
+ @torch.no_grad()
208
+ def _momentum_update_key_encoder(self):
209
+ """
210
+ Momentum update of the key encoder
211
+ """
212
+ for param_q, param_k in zip(
213
+ self.encoder_q.parameters(), self.encoder_k.parameters()
214
+ ):
215
+ param_k.data = param_k.data * self.m + param_q.data * (1.0 - self.m)
216
+
217
+ @torch.no_grad()
218
+ def _dequeue_and_enqueue(self, keys):
219
+ # gather keys before updating queue
220
+ keys = concat_all_gather(keys)
221
+
222
+ batch_size = keys.shape[0]
223
+
224
+ ptr = int(self.queue_ptr)
225
+ assert self.K % batch_size == 0 # for simplicity
226
+
227
+ # replace the keys at ptr (dequeue and enqueue)
228
+ self.queue[:, ptr : ptr + batch_size] = keys.T
229
+ ptr = (ptr + batch_size) % self.K # move pointer
230
+
231
+ self.queue_ptr[0] = ptr
232
+
233
+ @torch.no_grad()
234
+ def _batch_shuffle_ddp(self, x):
235
+ """
236
+ Batch shuffle, for making use of BatchNorm.
237
+ *** Only support DistributedDataParallel (DDP) model. ***
238
+ """
239
+ # gather from all gpus
240
+ batch_size_this = x.shape[0]
241
+ x_gather = concat_all_gather(x)
242
+ batch_size_all = x_gather.shape[0]
243
+
244
+ num_gpus = batch_size_all // batch_size_this
245
+
246
+ # random shuffle index
247
+ idx_shuffle = torch.randperm(batch_size_all).cuda()
248
+
249
+ # broadcast to all gpus
250
+ torch.distributed.broadcast(idx_shuffle, src=0)
251
+
252
+ # index for restoring
253
+ idx_unshuffle = torch.argsort(idx_shuffle)
254
+
255
+ # shuffled index for this gpu
256
+ gpu_idx = torch.distributed.get_rank()
257
+ idx_this = idx_shuffle.view(num_gpus, -1)[gpu_idx]
258
+
259
+ return x_gather[idx_this], idx_unshuffle
260
+
261
+ @torch.no_grad()
262
+ def _batch_unshuffle_ddp(self, x, idx_unshuffle):
263
+ """
264
+ Undo batch shuffle.
265
+ *** Only support DistributedDataParallel (DDP) model. ***
266
+ """
267
+ # gather from all gpus
268
+ batch_size_this = x.shape[0]
269
+ x_gather = concat_all_gather(x)
270
+ batch_size_all = x_gather.shape[0]
271
+
272
+ num_gpus = batch_size_all // batch_size_this
273
+
274
+ # restored index for this gpu
275
+ gpu_idx = torch.distributed.get_rank()
276
+ idx_this = idx_unshuffle.view(num_gpus, -1)[gpu_idx]
277
+
278
+ return x_gather[idx_this]
279
+
280
+ def augment(self, x, mask_ratio=0.75):
281
+ # embed patches
282
+ x = self.patch_embed(x)
283
+ # add pos embed w/o cls token
284
+ x = x + self.pos_embed[:, 1:, :]
285
+ # masking: length -> length * mask_ratio
286
+ x = random_masking(x, mask_ratio)
287
+ return x
288
+
289
+ def forward(self, im_q, im_k):
290
+ """
291
+ Input:
292
+ im_q: a batch of query images
293
+ im_k: a batch of key images
294
+ Output:
295
+ logits, targets
296
+ """
297
+
298
+ # compute query features
299
+ q = self.encoder_q(im_q) # queries: NxC
300
+ if self.norm:
301
+ q = nn.functional.normalize(q, dim=1)
302
+
303
+ # compute key features
304
+ with torch.no_grad(): # no gradient to keys
305
+ self._momentum_update_key_encoder() # update the key encoder
306
+
307
+ # shuffle for making use of BN
308
+ im_k, idx_unshuffle = self._batch_shuffle_ddp(im_k)
309
+
310
+ k = self.encoder_k(im_k) # keys: NxC
311
+ if self.norm:
312
+ k = nn.functional.normalize(k, dim=1)
313
+
314
+ # undo shuffle
315
+ k = self._batch_unshuffle_ddp(k, idx_unshuffle)
316
+
317
+ # compute logits
318
+ # Einstein sum is more intuitive
319
+ # positive logits: Nx1
320
+ l_pos = torch.einsum("nc,nc->n", [q, k]).unsqueeze(-1)
321
+ # negative logits: NxK
322
+ l_neg = torch.einsum("nc,ck->nk", [q, self.queue.clone().detach()])
323
+
324
+ # logits: Nx(1+K)
325
+ logits = torch.cat([l_pos, l_neg], dim=1)
326
+
327
+ # apply temperature
328
+ logits /= self.T
329
+
330
+ # labels: positive key indicators
331
+ labels = torch.zeros(logits.shape[0], dtype=torch.long).cuda()
332
+
333
+ # dequeue and enqueue
334
+ self._dequeue_and_enqueue(k)
335
+
336
+ return logits, labels
337
+
338
+
339
+ # utils
340
+ @torch.no_grad()
341
+ def concat_all_gather(tensor):
342
+ """
343
+ Performs all_gather operation on the provided tensors.
344
+ *** Warning ***: torch.distributed.all_gather has no gradient.
345
+ """
346
+ tensors_gather = [
347
+ torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())
348
+ ]
349
+ torch.distributed.all_gather(tensors_gather, tensor.contiguous(), async_op=False)
350
+
351
+ output = torch.cat(tensors_gather, dim=0)
352
+ return output
353
+
354
+
355
+ def random_masking(x, mask_ratio):
356
+ """
357
+ Perform per-sample random masking by per-sample shuffling.
358
+ Per-sample shuffling is done by argsort random noise.
359
+ x: [N, L, D], sequence
360
+ """
361
+ N, L, D = x.shape # batch, length, dim
362
+ len_keep = int(L * (1 - mask_ratio))
363
+
364
+ noise = torch.rand(N, L, device=x.device) # noise in [0, 1]
365
+
366
+ # sort noise for each sample
367
+ ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove
368
+ ids_restore = torch.argsort(ids_shuffle, dim=1)
369
+
370
+ # keep the first subset
371
+ ids_keep = ids_shuffle[:, :len_keep]
372
+ x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))
373
+
374
+ # generate the binary mask: 0 is keep, 1 is remove
375
+ mask = torch.ones([N, L], device=x.device)
376
+ mask[:, :len_keep] = 0
377
+ # unshuffle to get the binary mask
378
+ mask = torch.gather(mask, dim=1, index=ids_restore)
379
+
380
+ return x_masked
models/moco_v1/loader.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import random
7
+
8
+ from PIL import ImageFilter
9
+
10
+
11
+ class TwoCropsTransform:
12
+ """Take two random crops of one image as the query and key."""
13
+
14
+ def __init__(self, base_transform):
15
+ self.base_transform = base_transform
16
+
17
+ def __call__(self, x):
18
+ q = self.base_transform(x)
19
+ k = self.base_transform(x)
20
+ return [q, k]
21
+
22
+
23
+ class GaussianBlur:
24
+ """Gaussian blur augmentation in SimCLR https://arxiv.org/abs/2002.05709"""
25
+
26
+ def __init__(self, sigma=[0.1, 2.0]):
27
+ self.sigma = sigma
28
+
29
+ def __call__(self, x):
30
+ sigma = random.uniform(self.sigma[0], self.sigma[1])
31
+ x = x.filter(ImageFilter.GaussianBlur(radius=sigma))
32
+ return x
models/resnet.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor
3
+ import torch.nn as nn
4
+ from typing import Type, Any, Callable, Union, List, Optional
5
+
6
+ try:
7
+ from torch.hub import load_state_dict_from_url
8
+ except ImportError:
9
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
10
+
11
+
12
+ model_urls = {
13
+ 'resnet18': 'https://download.pytorch.org/models/resnet18-f37072fd.pth',
14
+ 'resnet34': 'https://download.pytorch.org/models/resnet34-b627a593.pth',
15
+ 'resnet50': 'https://download.pytorch.org/models/resnet50-0676ba61.pth',
16
+ 'resnet101': 'https://download.pytorch.org/models/resnet101-63fe2227.pth',
17
+ 'resnet152': 'https://download.pytorch.org/models/resnet152-394f9c45.pth',
18
+ 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
19
+ 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
20
+ 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
21
+ 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
22
+ }
23
+
24
+
25
+
26
+
27
+ def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
28
+ """3x3 convolution with padding"""
29
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
30
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
31
+
32
+
33
+ def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
34
+ """1x1 convolution"""
35
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
36
+
37
+
38
+ class BasicBlock(nn.Module):
39
+ expansion: int = 1
40
+
41
+ def __init__(
42
+ self,
43
+ inplanes: int,
44
+ planes: int,
45
+ stride: int = 1,
46
+ downsample: Optional[nn.Module] = None,
47
+ groups: int = 1,
48
+ base_width: int = 64,
49
+ dilation: int = 1,
50
+ norm_layer: Optional[Callable[..., nn.Module]] = None
51
+ ) -> None:
52
+ super(BasicBlock, self).__init__()
53
+ if norm_layer is None:
54
+ norm_layer = nn.BatchNorm2d
55
+ if groups != 1 or base_width != 64:
56
+ raise ValueError('BasicBlock only supports groups=1 and base_width=64')
57
+ if dilation > 1:
58
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
59
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
60
+ self.conv1 = conv3x3(inplanes, planes, stride)
61
+ self.bn1 = norm_layer(planes)
62
+ self.relu = nn.ReLU(inplace=True)
63
+ self.conv2 = conv3x3(planes, planes)
64
+ self.bn2 = norm_layer(planes)
65
+ self.downsample = downsample
66
+ self.stride = stride
67
+
68
+ def forward(self, x: Tensor) -> Tensor:
69
+ identity = x
70
+
71
+ out = self.conv1(x)
72
+ out = self.bn1(out)
73
+ out = self.relu(out)
74
+
75
+ out = self.conv2(out)
76
+ out = self.bn2(out)
77
+
78
+ if self.downsample is not None:
79
+ identity = self.downsample(x)
80
+
81
+ out += identity
82
+ out = self.relu(out)
83
+
84
+ return out
85
+
86
+
87
+ class Bottleneck(nn.Module):
88
+ # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
89
+ # while original implementation places the stride at the first 1x1 convolution(self.conv1)
90
+ # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
91
+ # This variant is also known as ResNet V1.5 and improves accuracy according to
92
+ # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
93
+
94
+ expansion: int = 4
95
+
96
+ def __init__(
97
+ self,
98
+ inplanes: int,
99
+ planes: int,
100
+ stride: int = 1,
101
+ downsample: Optional[nn.Module] = None,
102
+ groups: int = 1,
103
+ base_width: int = 64,
104
+ dilation: int = 1,
105
+ norm_layer: Optional[Callable[..., nn.Module]] = None
106
+ ) -> None:
107
+ super(Bottleneck, self).__init__()
108
+ if norm_layer is None:
109
+ norm_layer = nn.BatchNorm2d
110
+ width = int(planes * (base_width / 64.)) * groups
111
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
112
+ self.conv1 = conv1x1(inplanes, width)
113
+ self.bn1 = norm_layer(width)
114
+ self.conv2 = conv3x3(width, width, stride, groups, dilation)
115
+ self.bn2 = norm_layer(width)
116
+ self.conv3 = conv1x1(width, planes * self.expansion)
117
+ self.bn3 = norm_layer(planes * self.expansion)
118
+ self.relu = nn.ReLU(inplace=True)
119
+ self.downsample = downsample
120
+ self.stride = stride
121
+
122
+ def forward(self, x: Tensor) -> Tensor:
123
+ identity = x
124
+
125
+ out = self.conv1(x)
126
+ out = self.bn1(out)
127
+ out = self.relu(out)
128
+
129
+ out = self.conv2(out)
130
+ out = self.bn2(out)
131
+ out = self.relu(out)
132
+
133
+ out = self.conv3(out)
134
+ out = self.bn3(out)
135
+
136
+ if self.downsample is not None:
137
+ identity = self.downsample(x)
138
+
139
+ out += identity
140
+ out = self.relu(out)
141
+
142
+ return out
143
+
144
+
145
+ class ResNet(nn.Module):
146
+
147
+ def __init__(
148
+ self,
149
+ block: Type[Union[BasicBlock, Bottleneck]],
150
+ layers: List[int],
151
+ num_classes: int = 1000,
152
+ zero_init_residual: bool = False,
153
+ groups: int = 1,
154
+ width_per_group: int = 64,
155
+ replace_stride_with_dilation: Optional[List[bool]] = None,
156
+ norm_layer: Optional[Callable[..., nn.Module]] = None
157
+ ) -> None:
158
+ super(ResNet, self).__init__()
159
+ if norm_layer is None:
160
+ norm_layer = nn.BatchNorm2d
161
+ self._norm_layer = norm_layer
162
+
163
+ self.inplanes = 64
164
+ self.dilation = 1
165
+ if replace_stride_with_dilation is None:
166
+ # each element in the tuple indicates if we should replace
167
+ # the 2x2 stride with a dilated convolution instead
168
+ replace_stride_with_dilation = [False, False, False]
169
+ if len(replace_stride_with_dilation) != 3:
170
+ raise ValueError("replace_stride_with_dilation should be None "
171
+ "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
172
+ self.groups = groups
173
+ self.base_width = width_per_group
174
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
175
+ bias=False)
176
+ self.bn1 = norm_layer(self.inplanes)
177
+ self.relu = nn.ReLU(inplace=True)
178
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
179
+ self.layer1 = self._make_layer(block, 64, layers[0])
180
+ self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
181
+ dilate=replace_stride_with_dilation[0])
182
+ self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
183
+ dilate=replace_stride_with_dilation[1])
184
+ self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
185
+ dilate=replace_stride_with_dilation[2])
186
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
187
+ self.fc = nn.Linear(512 * block.expansion, num_classes)
188
+
189
+ for m in self.modules():
190
+ if isinstance(m, nn.Conv2d):
191
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
192
+ elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
193
+ nn.init.constant_(m.weight, 1)
194
+ nn.init.constant_(m.bias, 0)
195
+
196
+ # Zero-initialize the last BN in each residual branch,
197
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
198
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
199
+ if zero_init_residual:
200
+ for m in self.modules():
201
+ if isinstance(m, Bottleneck):
202
+ nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]
203
+ elif isinstance(m, BasicBlock):
204
+ nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type]
205
+
206
+ def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,
207
+ stride: int = 1, dilate: bool = False) -> nn.Sequential:
208
+ norm_layer = self._norm_layer
209
+ downsample = None
210
+ previous_dilation = self.dilation
211
+ if dilate:
212
+ self.dilation *= stride
213
+ stride = 1
214
+ if stride != 1 or self.inplanes != planes * block.expansion:
215
+ downsample = nn.Sequential(
216
+ conv1x1(self.inplanes, planes * block.expansion, stride),
217
+ norm_layer(planes * block.expansion),
218
+ )
219
+
220
+ layers = []
221
+ layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
222
+ self.base_width, previous_dilation, norm_layer))
223
+ self.inplanes = planes * block.expansion
224
+ for _ in range(1, blocks):
225
+ layers.append(block(self.inplanes, planes, groups=self.groups,
226
+ base_width=self.base_width, dilation=self.dilation,
227
+ norm_layer=norm_layer))
228
+
229
+ return nn.Sequential(*layers)
230
+
231
+ def _forward_impl(self, x):
232
+ # The comment resolution is based on input size is 224*224 imagenet
233
+ out = {}
234
+ x = self.conv1(x)
235
+ x = self.bn1(x)
236
+ x = self.relu(x)
237
+ x = self.maxpool(x)
238
+ out['f0'] = x # N*64*56*56
239
+
240
+ x = self.layer1(x)
241
+ out['f1'] = x # N*64*56*56
242
+
243
+ x = self.layer2(x)
244
+ out['f2'] = x # N*128*28*28
245
+
246
+ x = self.layer3(x)
247
+ out['f3'] = x # N*256*14*14
248
+
249
+ x = self.layer4(x)
250
+ out['f4'] = x # N*512*7*7
251
+
252
+ x = self.avgpool(x)
253
+ x = torch.flatten(x, 1)
254
+ out['penultimate'] = x # N*512
255
+
256
+ x = self.fc(x)
257
+ out['logits'] = x # N*1000
258
+
259
+ # return all features
260
+ return out
261
+
262
+ # return final classification result
263
+ # return x
264
+
265
+ def forward(self, x):
266
+ return self._forward_impl(x)
267
+
268
+
269
+ def _resnet(
270
+ arch: str,
271
+ block: Type[Union[BasicBlock, Bottleneck]],
272
+ layers: List[int],
273
+ pretrained: bool,
274
+ progress: bool,
275
+ **kwargs: Any
276
+ ) -> ResNet:
277
+ model = ResNet(block, layers, **kwargs)
278
+ if pretrained:
279
+ state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
280
+ model.load_state_dict(state_dict)
281
+ return model
282
+
283
+
284
+ def resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
285
+ r"""ResNet-18 model from
286
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
287
+
288
+ Args:
289
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
290
+ progress (bool): If True, displays a progress bar of the download to stderr
291
+ """
292
+ return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, **kwargs)
293
+
294
+
295
+ def resnet34(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
296
+ r"""ResNet-34 model from
297
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
298
+
299
+ Args:
300
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
301
+ progress (bool): If True, displays a progress bar of the download to stderr
302
+ """
303
+ return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, **kwargs)
304
+
305
+
306
+ def resnet50(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
307
+ r"""ResNet-50 model from
308
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
309
+
310
+ Args:
311
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
312
+ progress (bool): If True, displays a progress bar of the download to stderr
313
+ """
314
+ return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
315
+
316
+
317
+ def resnet101(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
318
+ r"""ResNet-101 model from
319
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
320
+
321
+ Args:
322
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
323
+ progress (bool): If True, displays a progress bar of the download to stderr
324
+ """
325
+ return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
326
+
327
+
328
+ def resnet152(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
329
+ r"""ResNet-152 model from
330
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
331
+
332
+ Args:
333
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
334
+ progress (bool): If True, displays a progress bar of the download to stderr
335
+ """
336
+ return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, **kwargs)
337
+
models/transformer_attention.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+
6
+
7
+
8
+ class TransformerAttention(nn.Module):
9
+ def __init__(self, input_dim, output_dim, last_dim=1):
10
+ super(TransformerAttention, self).__init__()
11
+ self.query = nn.Linear(input_dim, input_dim)
12
+ self.key = nn.Linear(input_dim, input_dim)
13
+ self.value = nn.Linear(input_dim, input_dim)
14
+ self.fc = nn.Linear(input_dim*output_dim, last_dim)
15
+ # self.fc = nn.Linear(input_dim, output_dim)
16
+ self.softmax = nn.Softmax(dim=1)
17
+
18
+ def forward(self, x):
19
+ # x = x.unsqueeze(dim=1)
20
+ q = self.query(x)
21
+ k = self.key(x)
22
+ v = self.value(x)
23
+ attention = torch.matmul(q, k.transpose(1, 2))
24
+ attention = attention / torch.sqrt(torch.tensor(k.size(-1)))
25
+ attention = self.softmax(attention)
26
+ output = torch.matmul(attention, v)
27
+ output = output.view([output.shape[0], -1])
28
+ output = self.fc(output)
29
+ return output
30
+
31
+
32
+
33
+
34
+
35
+
36
+ class TransformerMultiHeadAttention(nn.Module):
37
+ def __init__(self, input_dim, output_dim, head_num, predict_dim=1):
38
+ super(TransformerMultiHeadAttention, self).__init__()
39
+ self.head_num = head_num
40
+ self.query = nn.Linear(input_dim, input_dim * head_num)
41
+ self.key = nn.Linear(input_dim, input_dim * head_num)
42
+ self.value = nn.Linear(input_dim, input_dim * head_num)
43
+ self.fc = nn.Linear(input_dim * head_num * output_dim, predict_dim)
44
+ self.softmax = nn.Softmax(dim=1)
45
+
46
+ def split_heads(self, tensor):
47
+ # Split the last dimension into (head_num, new_last_dim)
48
+ tensor = tensor.view(tensor.size(0), tensor.size(1), self.head_num, tensor.size(-1) // self.head_num)
49
+ # Transpose the result to (batch, head_num, new_last_dim, -1)
50
+ return tensor.transpose(1, 2)
51
+
52
+
53
+ def scaled_dot_product_attention(self, q, k, v):
54
+ d_k = q.size(-1)
55
+ scores = torch.matmul(q, k.transpose(-2, -1)) / torch.sqrt(torch.tensor(d_k, dtype=torch.float32))
56
+ attention = self.softmax(scores)
57
+ return torch.matmul(attention, v)
58
+
59
+ def combine_heads(self, tensor):
60
+ # Transpose and reshape the tensor to (batch, -1, head_num * new_last_dim)
61
+ return tensor.transpose(1, 2).contiguous().view(tensor.size(0), -1)
62
+
63
+ def forward(self, x):
64
+ q = self.query(x)
65
+ k = self.key(x)
66
+ v = self.value(x)
67
+ q, k, v = [self.split_heads(tensor) for tensor in (q, k, v)]
68
+ attention = self.scaled_dot_product_attention(q, k, v)
69
+ output = self.combine_heads(attention)
70
+ output = self.fc(output)
71
+ return output
72
+
73
+
74
+
75
+ class TransformerAttentionwithClassifierToken(nn.Module):
76
+ def __init__(self, input_dim, middle_dim, output_dim):
77
+ super(TransformerAttentionwithClassifierToken, self).__init__()
78
+ self.input_dim = input_dim
79
+ self.classifier_token = nn.Linear(input_dim, 1)
80
+ self.query = nn.Linear(input_dim, input_dim)
81
+ self.key = nn.Linear(input_dim, input_dim)
82
+ self.value = nn.Linear(input_dim, input_dim)
83
+ self.fc = nn.Linear(input_dim, output_dim)
84
+ self.softmax = nn.Softmax(dim=1)
85
+
86
+ def forward(self, x):
87
+ classifier_token = torch.ones((x.shape[0], 1, self.input_dim)).to(x.device)*self.classifier_token.weight.data.squeeze(dim=-1)
88
+ x = torch.cat([classifier_token.to(x.device), x], dim=-2)
89
+ q = self.query(x)
90
+ k = self.key(x)
91
+ v = self.value(x)
92
+ attention = torch.matmul(q, k.transpose(1, 2))
93
+ attention = attention / torch.sqrt(torch.tensor(k.size(-1)))
94
+ attention = self.softmax(attention)
95
+ output = torch.matmul(attention, v)
96
+ # using only the classifier token
97
+ output = self.fc(output[:, 0, :])
98
+ return output
99
+
100
+
101
+ class TransformerCrossAttention(nn.Module):
102
+ def __init__(self, input_dim, middle_dim, output_dim):
103
+ super(TransformerAttention, self).__init__()
104
+ self.query = nn.Linear(input_dim, input_dim)
105
+ self.key = nn.Linear(input_dim, input_dim)
106
+ self.value = nn.Linear(input_dim, input_dim)
107
+ self.fc = nn.Linear(input_dim*middle_dim, output_dim)
108
+ # self.fc = nn.Linear(input_dim, output_dim)
109
+ self.softmax = nn.Softmax(dim=1)
110
+
111
+ def forward(self, x):
112
+ # x = x.unsqueeze(dim=1)
113
+ q = self.query(x)
114
+ k = self.key(x)
115
+ v = self.value(x)
116
+ attention = torch.matmul(q, k.transpose(1, 2))
117
+ attention = attention / torch.sqrt(torch.tensor(k.size(-1)))
118
+ attention = self.softmax(attention)
119
+ output = torch.matmul(attention, v)
120
+ output = output.view([output.shape[0], -1])
121
+ output = self.fc(output)
122
+ return output
123
+
124
+
125
+
126
+
127
+
128
+ class TransformerAttentionwithPisition(nn.Module):
129
+ def __init__(self, input_dim, output_dim, last_dim=1, token_num=2):
130
+ super(TransformerAttentionwithPisition, self).__init__()
131
+ self.query = nn.Linear(input_dim, input_dim)
132
+ self.key = nn.Linear(input_dim, input_dim)
133
+ self.value = nn.Linear(input_dim, input_dim)
134
+ self.fc = nn.Linear(input_dim * token_num, last_dim)
135
+ self.softmax = nn.Softmax(dim=1)
136
+ self.position_embeddings = nn.Parameter(torch.zeros([token_num, input_dim]))
137
+
138
+ def forward(self, x):
139
+ seq_len = x.size(1)
140
+ x_with_position = x + self.position_embeddings
141
+
142
+ q = self.query(x_with_position)
143
+ k = self.key(x_with_position)
144
+ v = self.value(x_with_position)
145
+
146
+ attention = torch.matmul(q, k.transpose(1, 2))
147
+ attention = attention / torch.sqrt(torch.tensor(k.size(-1), dtype=torch.float32))
148
+
149
+ attention = self.softmax(attention)
150
+ output = torch.matmul(attention, v)
151
+
152
+ output = output.view([output.shape[0], -1])
153
+ output = self.fc(output)
154
+ return output
155
+
156
+
157
+
158
+ class TransformerCrossAttentionwithPisition(nn.Module):
159
+ def __init__(self, input_dim, output_dim, last_dim=1, token_num=2):
160
+ super(TransformerCrossAttentionwithPisition, self).__init__()
161
+ self.query = nn.Linear(input_dim, input_dim)
162
+ self.key = nn.Linear(input_dim, input_dim)
163
+ self.value = nn.Linear(input_dim, input_dim)
164
+ self.fc = nn.Linear(input_dim * output_dim // 2, last_dim)
165
+ self.softmax = nn.Softmax(dim=1)
166
+ self.position_embeddings = nn.Parameter(torch.zeros([token_num, input_dim]))
167
+
168
+ def forward(self, x):
169
+ # first half to be q and second half to be k, v
170
+ seq_len = x.size(1)
171
+ x_with_position = x + self.position_embeddings
172
+
173
+ q = self.query(x_with_position[:, :x_with_position.shape[1]//2, :])
174
+ k = self.key(x_with_position[:, x_with_position.shape[1]//2:, :])
175
+ v = self.value(x_with_position[:, x_with_position.shape[1]//2:, :])
176
+
177
+ attention = torch.matmul(q, k.transpose(1, 2))
178
+ attention = attention / torch.sqrt(torch.tensor(k.size(-1), dtype=torch.float32))
179
+
180
+ attention = self.softmax(attention)
181
+ output = torch.matmul(attention, v)
182
+
183
+ output = output.view([output.shape[0], -1])
184
+ output = self.fc(output)
185
+ return output
186
+
187
+
188
+ class TransformerAttentionwithCatPe(nn.Module):
189
+ def __init__(self, input_dim, output_dim, last_dim=1, token_num=2):
190
+ super(TransformerAttentionwithCatPe, self).__init__()
191
+ input_dim = input_dim * 2
192
+ self.query = nn.Linear(input_dim, input_dim)
193
+ self.key = nn.Linear(input_dim, input_dim)
194
+ self.value = nn.Linear(input_dim, input_dim)
195
+ self.fc = nn.Linear(input_dim * output_dim, last_dim)
196
+ self.softmax = nn.Softmax(dim=1)
197
+ self.position_embeddings = nn.Parameter(torch.zeros([token_num, input_dim//2]))
198
+
199
+ def forward(self, x):
200
+ seq_len = x.size(1)
201
+ pe = self.position_embeddings.expand(x.shape[0], -1, -1)
202
+ x_with_position = torch.cat([x, pe], dim=-1)
203
+
204
+ q = self.query(x_with_position)
205
+ k = self.key(x_with_position)
206
+ v = self.value(x_with_position)
207
+
208
+ attention = torch.matmul(q, k.transpose(1, 2))
209
+ attention = attention / torch.sqrt(torch.tensor(k.size(-1), dtype=torch.float32))
210
+
211
+ attention = self.softmax(attention)
212
+ output = torch.matmul(attention, v)
213
+
214
+ output = output.view([output.shape[0], -1])
215
+ output = self.fc(output)
216
+ return output
217
+
models/vision_transformer.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections import OrderedDict
3
+ from functools import partial
4
+ from typing import Any, Callable, List, NamedTuple, Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ # from .._internally_replaced_utils import load_state_dict_from_url
10
+ from .vision_transformer_misc import ConvNormActivation
11
+ from .vision_transformer_utils import _log_api_usage_once
12
+
13
+ try:
14
+ from torch.hub import load_state_dict_from_url
15
+ except ImportError:
16
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
17
+
18
+ # __all__ = [
19
+ # "VisionTransformer",
20
+ # "vit_b_16",
21
+ # "vit_b_32",
22
+ # "vit_l_16",
23
+ # "vit_l_32",
24
+ # ]
25
+
26
+ model_urls = {
27
+ "vit_b_16": "https://download.pytorch.org/models/vit_b_16-c867db91.pth",
28
+ "vit_b_32": "https://download.pytorch.org/models/vit_b_32-d86f8d99.pth",
29
+ "vit_l_16": "https://download.pytorch.org/models/vit_l_16-852ce7e3.pth",
30
+ "vit_l_32": "https://download.pytorch.org/models/vit_l_32-c7638314.pth",
31
+ }
32
+
33
+
34
+ class ConvStemConfig(NamedTuple):
35
+ out_channels: int
36
+ kernel_size: int
37
+ stride: int
38
+ norm_layer: Callable[..., nn.Module] = nn.BatchNorm2d
39
+ activation_layer: Callable[..., nn.Module] = nn.ReLU
40
+
41
+
42
+ class MLPBlock(nn.Sequential):
43
+ """Transformer MLP block."""
44
+
45
+ def __init__(self, in_dim: int, mlp_dim: int, dropout: float):
46
+ super().__init__()
47
+ self.linear_1 = nn.Linear(in_dim, mlp_dim)
48
+ self.act = nn.GELU()
49
+ self.dropout_1 = nn.Dropout(dropout)
50
+ self.linear_2 = nn.Linear(mlp_dim, in_dim)
51
+ self.dropout_2 = nn.Dropout(dropout)
52
+
53
+ nn.init.xavier_uniform_(self.linear_1.weight)
54
+ nn.init.xavier_uniform_(self.linear_2.weight)
55
+ nn.init.normal_(self.linear_1.bias, std=1e-6)
56
+ nn.init.normal_(self.linear_2.bias, std=1e-6)
57
+
58
+
59
+ class EncoderBlock(nn.Module):
60
+ """Transformer encoder block."""
61
+
62
+ def __init__(
63
+ self,
64
+ num_heads: int,
65
+ hidden_dim: int,
66
+ mlp_dim: int,
67
+ dropout: float,
68
+ attention_dropout: float,
69
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
70
+ ):
71
+ super().__init__()
72
+ self.num_heads = num_heads
73
+
74
+ # Attention block
75
+ self.ln_1 = norm_layer(hidden_dim)
76
+ self.self_attention = nn.MultiheadAttention(hidden_dim, num_heads, dropout=attention_dropout, batch_first=True)
77
+ self.dropout = nn.Dropout(dropout)
78
+
79
+ # MLP block
80
+ self.ln_2 = norm_layer(hidden_dim)
81
+ self.mlp = MLPBlock(hidden_dim, mlp_dim, dropout)
82
+
83
+ def forward(self, input: torch.Tensor):
84
+ torch._assert(input.dim() == 3, f"Expected (seq_length, batch_size, hidden_dim) got {input.shape}")
85
+ x = self.ln_1(input)
86
+ x, _ = self.self_attention(query=x, key=x, value=x, need_weights=False)
87
+ x = self.dropout(x)
88
+ x = x + input
89
+
90
+ y = self.ln_2(x)
91
+ y = self.mlp(y)
92
+ return x + y
93
+
94
+
95
+ class Encoder(nn.Module):
96
+ """Transformer Model Encoder for sequence to sequence translation."""
97
+
98
+ def __init__(
99
+ self,
100
+ seq_length: int,
101
+ num_layers: int,
102
+ num_heads: int,
103
+ hidden_dim: int,
104
+ mlp_dim: int,
105
+ dropout: float,
106
+ attention_dropout: float,
107
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
108
+ ):
109
+ super().__init__()
110
+ # Note that batch_size is on the first dim because
111
+ # we have batch_first=True in nn.MultiAttention() by default
112
+ self.pos_embedding = nn.Parameter(torch.empty(1, seq_length, hidden_dim).normal_(std=0.02)) # from BERT
113
+ self.dropout = nn.Dropout(dropout)
114
+ layers: OrderedDict[str, nn.Module] = OrderedDict()
115
+ for i in range(num_layers):
116
+ layers[f"encoder_layer_{i}"] = EncoderBlock(
117
+ num_heads,
118
+ hidden_dim,
119
+ mlp_dim,
120
+ dropout,
121
+ attention_dropout,
122
+ norm_layer,
123
+ )
124
+ self.layers = nn.Sequential(layers)
125
+ self.ln = norm_layer(hidden_dim)
126
+
127
+ def forward(self, input: torch.Tensor):
128
+ torch._assert(input.dim() == 3, f"Expected (batch_size, seq_length, hidden_dim) got {input.shape}")
129
+ input = input + self.pos_embedding
130
+ return self.ln(self.layers(self.dropout(input)))
131
+
132
+
133
+ class VisionTransformer(nn.Module):
134
+ """Vision Transformer as per https://arxiv.org/abs/2010.11929."""
135
+
136
+ def __init__(
137
+ self,
138
+ image_size: int,
139
+ patch_size: int,
140
+ num_layers: int,
141
+ num_heads: int,
142
+ hidden_dim: int,
143
+ mlp_dim: int,
144
+ dropout: float = 0.0,
145
+ attention_dropout: float = 0.0,
146
+ num_classes: int = 1000,
147
+ representation_size: Optional[int] = None,
148
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
149
+ conv_stem_configs: Optional[List[ConvStemConfig]] = None,
150
+ ):
151
+ super().__init__()
152
+ _log_api_usage_once(self)
153
+ torch._assert(image_size % patch_size == 0, "Input shape indivisible by patch size!")
154
+ self.image_size = image_size
155
+ self.patch_size = patch_size
156
+ self.hidden_dim = hidden_dim
157
+ self.mlp_dim = mlp_dim
158
+ self.attention_dropout = attention_dropout
159
+ self.dropout = dropout
160
+ self.num_classes = num_classes
161
+ self.representation_size = representation_size
162
+ self.norm_layer = norm_layer
163
+
164
+ if conv_stem_configs is not None:
165
+ # As per https://arxiv.org/abs/2106.14881
166
+ seq_proj = nn.Sequential()
167
+ prev_channels = 3
168
+ for i, conv_stem_layer_config in enumerate(conv_stem_configs):
169
+ seq_proj.add_module(
170
+ f"conv_bn_relu_{i}",
171
+ ConvNormActivation(
172
+ in_channels=prev_channels,
173
+ out_channels=conv_stem_layer_config.out_channels,
174
+ kernel_size=conv_stem_layer_config.kernel_size,
175
+ stride=conv_stem_layer_config.stride,
176
+ norm_layer=conv_stem_layer_config.norm_layer,
177
+ activation_layer=conv_stem_layer_config.activation_layer,
178
+ ),
179
+ )
180
+ prev_channels = conv_stem_layer_config.out_channels
181
+ seq_proj.add_module(
182
+ "conv_last", nn.Conv2d(in_channels=prev_channels, out_channels=hidden_dim, kernel_size=1)
183
+ )
184
+ self.conv_proj: nn.Module = seq_proj
185
+ else:
186
+ self.conv_proj = nn.Conv2d(
187
+ in_channels=3, out_channels=hidden_dim, kernel_size=patch_size, stride=patch_size
188
+ )
189
+
190
+ seq_length = (image_size // patch_size) ** 2
191
+
192
+ # Add a class token
193
+ self.class_token = nn.Parameter(torch.zeros(1, 1, hidden_dim))
194
+ seq_length += 1
195
+
196
+ self.encoder = Encoder(
197
+ seq_length,
198
+ num_layers,
199
+ num_heads,
200
+ hidden_dim,
201
+ mlp_dim,
202
+ dropout,
203
+ attention_dropout,
204
+ norm_layer,
205
+ )
206
+ self.seq_length = seq_length
207
+
208
+ heads_layers: OrderedDict[str, nn.Module] = OrderedDict()
209
+ if representation_size is None:
210
+ heads_layers["head"] = nn.Linear(hidden_dim, num_classes)
211
+ else:
212
+ heads_layers["pre_logits"] = nn.Linear(hidden_dim, representation_size)
213
+ heads_layers["act"] = nn.Tanh()
214
+ heads_layers["head"] = nn.Linear(representation_size, num_classes)
215
+
216
+ self.heads = nn.Sequential(heads_layers)
217
+
218
+ if isinstance(self.conv_proj, nn.Conv2d):
219
+ # Init the patchify stem
220
+ fan_in = self.conv_proj.in_channels * self.conv_proj.kernel_size[0] * self.conv_proj.kernel_size[1]
221
+ nn.init.trunc_normal_(self.conv_proj.weight, std=math.sqrt(1 / fan_in))
222
+ if self.conv_proj.bias is not None:
223
+ nn.init.zeros_(self.conv_proj.bias)
224
+ elif self.conv_proj.conv_last is not None and isinstance(self.conv_proj.conv_last, nn.Conv2d):
225
+ # Init the last 1x1 conv of the conv stem
226
+ nn.init.normal_(
227
+ self.conv_proj.conv_last.weight, mean=0.0, std=math.sqrt(2.0 / self.conv_proj.conv_last.out_channels)
228
+ )
229
+ if self.conv_proj.conv_last.bias is not None:
230
+ nn.init.zeros_(self.conv_proj.conv_last.bias)
231
+
232
+ if hasattr(self.heads, "pre_logits") and isinstance(self.heads.pre_logits, nn.Linear):
233
+ fan_in = self.heads.pre_logits.in_features
234
+ nn.init.trunc_normal_(self.heads.pre_logits.weight, std=math.sqrt(1 / fan_in))
235
+ nn.init.zeros_(self.heads.pre_logits.bias)
236
+
237
+ if isinstance(self.heads.head, nn.Linear):
238
+ nn.init.zeros_(self.heads.head.weight)
239
+ nn.init.zeros_(self.heads.head.bias)
240
+
241
+ def _process_input(self, x: torch.Tensor) -> torch.Tensor:
242
+ n, c, h, w = x.shape
243
+ p = self.patch_size
244
+ torch._assert(h == self.image_size, "Wrong image height!")
245
+ torch._assert(w == self.image_size, "Wrong image width!")
246
+ n_h = h // p
247
+ n_w = w // p
248
+
249
+ # (n, c, h, w) -> (n, hidden_dim, n_h, n_w)
250
+ x = self.conv_proj(x)
251
+ # (n, hidden_dim, n_h, n_w) -> (n, hidden_dim, (n_h * n_w))
252
+ x = x.reshape(n, self.hidden_dim, n_h * n_w)
253
+
254
+ # (n, hidden_dim, (n_h * n_w)) -> (n, (n_h * n_w), hidden_dim)
255
+ # The self attention layer expects inputs in the format (N, S, E)
256
+ # where S is the source sequence length, N is the batch size, E is the
257
+ # embedding dimension
258
+ x = x.permute(0, 2, 1)
259
+
260
+ return x
261
+
262
+ def forward(self, x: torch.Tensor):
263
+ out = {}
264
+
265
+ # Reshape and permute the input tensor
266
+ x = self._process_input(x)
267
+ n = x.shape[0]
268
+
269
+ # Expand the class token to the full batch
270
+ batch_class_token = self.class_token.expand(n, -1, -1)
271
+ x = torch.cat([batch_class_token, x], dim=1)
272
+
273
+
274
+ x = self.encoder(x)
275
+ img_feature = x[:,1:]
276
+ H = W = int(self.image_size / self.patch_size)
277
+ out['f4'] = img_feature.view(n, H, W, self.hidden_dim).permute(0,3,1,2)
278
+
279
+ # Classifier "token" as used by standard language architectures
280
+ x = x[:, 0]
281
+ out['penultimate'] = x
282
+
283
+ x = self.heads(x) # I checked that for all pretrained ViT, this is just a fc
284
+ out['logits'] = x
285
+
286
+ return out
287
+
288
+
289
+ def _vision_transformer(
290
+ arch: str,
291
+ patch_size: int,
292
+ num_layers: int,
293
+ num_heads: int,
294
+ hidden_dim: int,
295
+ mlp_dim: int,
296
+ pretrained: bool,
297
+ progress: bool,
298
+ **kwargs: Any,
299
+ ) -> VisionTransformer:
300
+ image_size = kwargs.pop("image_size", 224)
301
+
302
+ model = VisionTransformer(
303
+ image_size=image_size,
304
+ patch_size=patch_size,
305
+ num_layers=num_layers,
306
+ num_heads=num_heads,
307
+ hidden_dim=hidden_dim,
308
+ mlp_dim=mlp_dim,
309
+ **kwargs,
310
+ )
311
+
312
+ if pretrained:
313
+ if arch not in model_urls:
314
+ raise ValueError(f"No checkpoint is available for model type '{arch}'!")
315
+ state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
316
+ model.load_state_dict(state_dict)
317
+
318
+ return model
319
+
320
+
321
+ def vit_b_16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
322
+ """
323
+ Constructs a vit_b_16 architecture from
324
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
325
+
326
+ Args:
327
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
328
+ progress (bool): If True, displays a progress bar of the download to stderr
329
+ """
330
+ return _vision_transformer(
331
+ arch="vit_b_16",
332
+ patch_size=16,
333
+ num_layers=12,
334
+ num_heads=12,
335
+ hidden_dim=768,
336
+ mlp_dim=3072,
337
+ pretrained=pretrained,
338
+ progress=progress,
339
+ **kwargs,
340
+ )
341
+
342
+
343
+ def vit_b_32(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
344
+ """
345
+ Constructs a vit_b_32 architecture from
346
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
347
+
348
+ Args:
349
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
350
+ progress (bool): If True, displays a progress bar of the download to stderr
351
+ """
352
+ return _vision_transformer(
353
+ arch="vit_b_32",
354
+ patch_size=32,
355
+ num_layers=12,
356
+ num_heads=12,
357
+ hidden_dim=768,
358
+ mlp_dim=3072,
359
+ pretrained=pretrained,
360
+ progress=progress,
361
+ **kwargs,
362
+ )
363
+
364
+
365
+ def vit_l_16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
366
+ """
367
+ Constructs a vit_l_16 architecture from
368
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
369
+
370
+ Args:
371
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
372
+ progress (bool): If True, displays a progress bar of the download to stderr
373
+ """
374
+ return _vision_transformer(
375
+ arch="vit_l_16",
376
+ patch_size=16,
377
+ num_layers=24,
378
+ num_heads=16,
379
+ hidden_dim=1024,
380
+ mlp_dim=4096,
381
+ pretrained=pretrained,
382
+ progress=progress,
383
+ **kwargs,
384
+ )
385
+
386
+
387
+ def vit_l_32(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
388
+ """
389
+ Constructs a vit_l_32 architecture from
390
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
391
+
392
+ Args:
393
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
394
+ progress (bool): If True, displays a progress bar of the download to stderr
395
+ """
396
+ return _vision_transformer(
397
+ arch="vit_l_32",
398
+ patch_size=32,
399
+ num_layers=24,
400
+ num_heads=16,
401
+ hidden_dim=1024,
402
+ mlp_dim=4096,
403
+ pretrained=pretrained,
404
+ progress=progress,
405
+ **kwargs,
406
+ )
407
+
408
+
409
+ def interpolate_embeddings(
410
+ image_size: int,
411
+ patch_size: int,
412
+ model_state: "OrderedDict[str, torch.Tensor]",
413
+ interpolation_mode: str = "bicubic",
414
+ reset_heads: bool = False,
415
+ ) -> "OrderedDict[str, torch.Tensor]":
416
+ """This function helps interpolating positional embeddings during checkpoint loading,
417
+ especially when you want to apply a pre-trained model on images with different resolution.
418
+
419
+ Args:
420
+ image_size (int): Image size of the new model.
421
+ patch_size (int): Patch size of the new model.
422
+ model_state (OrderedDict[str, torch.Tensor]): State dict of the pre-trained model.
423
+ interpolation_mode (str): The algorithm used for upsampling. Default: bicubic.
424
+ reset_heads (bool): If true, not copying the state of heads. Default: False.
425
+
426
+ Returns:
427
+ OrderedDict[str, torch.Tensor]: A state dict which can be loaded into the new model.
428
+ """
429
+ # Shape of pos_embedding is (1, seq_length, hidden_dim)
430
+ pos_embedding = model_state["encoder.pos_embedding"]
431
+ n, seq_length, hidden_dim = pos_embedding.shape
432
+ if n != 1:
433
+ raise ValueError(f"Unexpected position embedding shape: {pos_embedding.shape}")
434
+
435
+ new_seq_length = (image_size // patch_size) ** 2 + 1
436
+
437
+ # Need to interpolate the weights for the position embedding.
438
+ # We do this by reshaping the positions embeddings to a 2d grid, performing
439
+ # an interpolation in the (h, w) space and then reshaping back to a 1d grid.
440
+ if new_seq_length != seq_length:
441
+ # The class token embedding shouldn't be interpolated so we split it up.
442
+ seq_length -= 1
443
+ new_seq_length -= 1
444
+ pos_embedding_token = pos_embedding[:, :1, :]
445
+ pos_embedding_img = pos_embedding[:, 1:, :]
446
+
447
+ # (1, seq_length, hidden_dim) -> (1, hidden_dim, seq_length)
448
+ pos_embedding_img = pos_embedding_img.permute(0, 2, 1)
449
+ seq_length_1d = int(math.sqrt(seq_length))
450
+ torch._assert(seq_length_1d * seq_length_1d == seq_length, "seq_length is not a perfect square!")
451
+
452
+ # (1, hidden_dim, seq_length) -> (1, hidden_dim, seq_l_1d, seq_l_1d)
453
+ pos_embedding_img = pos_embedding_img.reshape(1, hidden_dim, seq_length_1d, seq_length_1d)
454
+ new_seq_length_1d = image_size // patch_size
455
+
456
+ # Perform interpolation.
457
+ # (1, hidden_dim, seq_l_1d, seq_l_1d) -> (1, hidden_dim, new_seq_l_1d, new_seq_l_1d)
458
+ new_pos_embedding_img = nn.functional.interpolate(
459
+ pos_embedding_img,
460
+ size=new_seq_length_1d,
461
+ mode=interpolation_mode,
462
+ align_corners=True,
463
+ )
464
+
465
+ # (1, hidden_dim, new_seq_l_1d, new_seq_l_1d) -> (1, hidden_dim, new_seq_length)
466
+ new_pos_embedding_img = new_pos_embedding_img.reshape(1, hidden_dim, new_seq_length)
467
+
468
+ # (1, hidden_dim, new_seq_length) -> (1, new_seq_length, hidden_dim)
469
+ new_pos_embedding_img = new_pos_embedding_img.permute(0, 2, 1)
470
+ new_pos_embedding = torch.cat([pos_embedding_token, new_pos_embedding_img], dim=1)
471
+
472
+ model_state["encoder.pos_embedding"] = new_pos_embedding
473
+
474
+ if reset_heads:
475
+ model_state_copy: "OrderedDict[str, torch.Tensor]" = OrderedDict()
476
+ for k, v in model_state.items():
477
+ if not k.startswith("heads"):
478
+ model_state_copy[k] = v
479
+ model_state = model_state_copy
480
+
481
+ return model_state
models/vision_transformer_misc.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional
2
+
3
+ import torch
4
+ from torch import Tensor
5
+
6
+ from .vision_transformer_utils import _log_api_usage_once
7
+
8
+
9
+ interpolate = torch.nn.functional.interpolate
10
+
11
+
12
+ # This is not in nn
13
+ class FrozenBatchNorm2d(torch.nn.Module):
14
+ """
15
+ BatchNorm2d where the batch statistics and the affine parameters are fixed
16
+
17
+ Args:
18
+ num_features (int): Number of features ``C`` from an expected input of size ``(N, C, H, W)``
19
+ eps (float): a value added to the denominator for numerical stability. Default: 1e-5
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ num_features: int,
25
+ eps: float = 1e-5,
26
+ ):
27
+ super().__init__()
28
+ _log_api_usage_once(self)
29
+ self.eps = eps
30
+ self.register_buffer("weight", torch.ones(num_features))
31
+ self.register_buffer("bias", torch.zeros(num_features))
32
+ self.register_buffer("running_mean", torch.zeros(num_features))
33
+ self.register_buffer("running_var", torch.ones(num_features))
34
+
35
+ def _load_from_state_dict(
36
+ self,
37
+ state_dict: dict,
38
+ prefix: str,
39
+ local_metadata: dict,
40
+ strict: bool,
41
+ missing_keys: List[str],
42
+ unexpected_keys: List[str],
43
+ error_msgs: List[str],
44
+ ):
45
+ num_batches_tracked_key = prefix + "num_batches_tracked"
46
+ if num_batches_tracked_key in state_dict:
47
+ del state_dict[num_batches_tracked_key]
48
+
49
+ super()._load_from_state_dict(
50
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
51
+ )
52
+
53
+ def forward(self, x: Tensor) -> Tensor:
54
+ # move reshapes to the beginning
55
+ # to make it fuser-friendly
56
+ w = self.weight.reshape(1, -1, 1, 1)
57
+ b = self.bias.reshape(1, -1, 1, 1)
58
+ rv = self.running_var.reshape(1, -1, 1, 1)
59
+ rm = self.running_mean.reshape(1, -1, 1, 1)
60
+ scale = w * (rv + self.eps).rsqrt()
61
+ bias = b - rm * scale
62
+ return x * scale + bias
63
+
64
+ def __repr__(self) -> str:
65
+ return f"{self.__class__.__name__}({self.weight.shape[0]}, eps={self.eps})"
66
+
67
+
68
+ class ConvNormActivation(torch.nn.Sequential):
69
+ """
70
+ Configurable block used for Convolution-Normalzation-Activation blocks.
71
+
72
+ Args:
73
+ in_channels (int): Number of channels in the input image
74
+ out_channels (int): Number of channels produced by the Convolution-Normalzation-Activation block
75
+ kernel_size: (int, optional): Size of the convolving kernel. Default: 3
76
+ stride (int, optional): Stride of the convolution. Default: 1
77
+ padding (int, tuple or str, optional): Padding added to all four sides of the input. Default: None, in wich case it will calculated as ``padding = (kernel_size - 1) // 2 * dilation``
78
+ groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
79
+ norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the convolutiuon layer. If ``None`` this layer wont be used. Default: ``torch.nn.BatchNorm2d``
80
+ activation_layer (Callable[..., torch.nn.Module], optinal): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the conv layer. If ``None`` this layer wont be used. Default: ``torch.nn.ReLU``
81
+ dilation (int): Spacing between kernel elements. Default: 1
82
+ inplace (bool): Parameter for the activation layer, which can optionally do the operation in-place. Default ``True``
83
+ bias (bool, optional): Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is None``.
84
+
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ in_channels: int,
90
+ out_channels: int,
91
+ kernel_size: int = 3,
92
+ stride: int = 1,
93
+ padding: Optional[int] = None,
94
+ groups: int = 1,
95
+ norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm2d,
96
+ activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU,
97
+ dilation: int = 1,
98
+ inplace: Optional[bool] = True,
99
+ bias: Optional[bool] = None,
100
+ ) -> None:
101
+ if padding is None:
102
+ padding = (kernel_size - 1) // 2 * dilation
103
+ if bias is None:
104
+ bias = norm_layer is None
105
+ layers = [
106
+ torch.nn.Conv2d(
107
+ in_channels,
108
+ out_channels,
109
+ kernel_size,
110
+ stride,
111
+ padding,
112
+ dilation=dilation,
113
+ groups=groups,
114
+ bias=bias,
115
+ )
116
+ ]
117
+ if norm_layer is not None:
118
+ layers.append(norm_layer(out_channels))
119
+ if activation_layer is not None:
120
+ params = {} if inplace is None else {"inplace": inplace}
121
+ layers.append(activation_layer(**params))
122
+ super().__init__(*layers)
123
+ _log_api_usage_once(self)
124
+ self.out_channels = out_channels
125
+
126
+
127
+ class SqueezeExcitation(torch.nn.Module):
128
+ """
129
+ This block implements the Squeeze-and-Excitation block from https://arxiv.org/abs/1709.01507 (see Fig. 1).
130
+ Parameters ``activation``, and ``scale_activation`` correspond to ``delta`` and ``sigma`` in in eq. 3.
131
+
132
+ Args:
133
+ input_channels (int): Number of channels in the input image
134
+ squeeze_channels (int): Number of squeeze channels
135
+ activation (Callable[..., torch.nn.Module], optional): ``delta`` activation. Default: ``torch.nn.ReLU``
136
+ scale_activation (Callable[..., torch.nn.Module]): ``sigma`` activation. Default: ``torch.nn.Sigmoid``
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ input_channels: int,
142
+ squeeze_channels: int,
143
+ activation: Callable[..., torch.nn.Module] = torch.nn.ReLU,
144
+ scale_activation: Callable[..., torch.nn.Module] = torch.nn.Sigmoid,
145
+ ) -> None:
146
+ super().__init__()
147
+ _log_api_usage_once(self)
148
+ self.avgpool = torch.nn.AdaptiveAvgPool2d(1)
149
+ self.fc1 = torch.nn.Conv2d(input_channels, squeeze_channels, 1)
150
+ self.fc2 = torch.nn.Conv2d(squeeze_channels, input_channels, 1)
151
+ self.activation = activation()
152
+ self.scale_activation = scale_activation()
153
+
154
+ def _scale(self, input: Tensor) -> Tensor:
155
+ scale = self.avgpool(input)
156
+ scale = self.fc1(scale)
157
+ scale = self.activation(scale)
158
+ scale = self.fc2(scale)
159
+ return self.scale_activation(scale)
160
+
161
+ def forward(self, input: Tensor) -> Tensor:
162
+ scale = self._scale(input)
163
+ return scale * input
models/vision_transformer_utils.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import pathlib
3
+ import warnings
4
+ from types import FunctionType
5
+ from typing import Any, BinaryIO, List, Optional, Tuple, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image, ImageColor, ImageDraw, ImageFont
10
+
11
+ __all__ = [
12
+ "make_grid",
13
+ "save_image",
14
+ "draw_bounding_boxes",
15
+ "draw_segmentation_masks",
16
+ "draw_keypoints",
17
+ "flow_to_image",
18
+ ]
19
+
20
+
21
+ @torch.no_grad()
22
+ def make_grid(
23
+ tensor: Union[torch.Tensor, List[torch.Tensor]],
24
+ nrow: int = 8,
25
+ padding: int = 2,
26
+ normalize: bool = False,
27
+ value_range: Optional[Tuple[int, int]] = None,
28
+ scale_each: bool = False,
29
+ pad_value: float = 0.0,
30
+ **kwargs,
31
+ ) -> torch.Tensor:
32
+ """
33
+ Make a grid of images.
34
+
35
+ Args:
36
+ tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
37
+ or a list of images all of the same size.
38
+ nrow (int, optional): Number of images displayed in each row of the grid.
39
+ The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
40
+ padding (int, optional): amount of padding. Default: ``2``.
41
+ normalize (bool, optional): If True, shift the image to the range (0, 1),
42
+ by the min and max values specified by ``value_range``. Default: ``False``.
43
+ value_range (tuple, optional): tuple (min, max) where min and max are numbers,
44
+ then these numbers are used to normalize the image. By default, min and max
45
+ are computed from the tensor.
46
+ range (tuple. optional):
47
+ .. warning::
48
+ This parameter was deprecated in ``0.12`` and will be removed in ``0.14``. Please use ``value_range``
49
+ instead.
50
+ scale_each (bool, optional): If ``True``, scale each image in the batch of
51
+ images separately rather than the (min, max) over all images. Default: ``False``.
52
+ pad_value (float, optional): Value for the padded pixels. Default: ``0``.
53
+
54
+ Returns:
55
+ grid (Tensor): the tensor containing grid of images.
56
+ """
57
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
58
+ _log_api_usage_once(make_grid)
59
+ if not (torch.is_tensor(tensor) or (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
60
+ raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}")
61
+
62
+ if "range" in kwargs.keys():
63
+ warnings.warn(
64
+ "The parameter 'range' is deprecated since 0.12 and will be removed in 0.14. "
65
+ "Please use 'value_range' instead."
66
+ )
67
+ value_range = kwargs["range"]
68
+
69
+ # if list of tensors, convert to a 4D mini-batch Tensor
70
+ if isinstance(tensor, list):
71
+ tensor = torch.stack(tensor, dim=0)
72
+
73
+ if tensor.dim() == 2: # single image H x W
74
+ tensor = tensor.unsqueeze(0)
75
+ if tensor.dim() == 3: # single image
76
+ if tensor.size(0) == 1: # if single-channel, convert to 3-channel
77
+ tensor = torch.cat((tensor, tensor, tensor), 0)
78
+ tensor = tensor.unsqueeze(0)
79
+
80
+ if tensor.dim() == 4 and tensor.size(1) == 1: # single-channel images
81
+ tensor = torch.cat((tensor, tensor, tensor), 1)
82
+
83
+ if normalize is True:
84
+ tensor = tensor.clone() # avoid modifying tensor in-place
85
+ if value_range is not None:
86
+ assert isinstance(
87
+ value_range, tuple
88
+ ), "value_range has to be a tuple (min, max) if specified. min and max are numbers"
89
+
90
+ def norm_ip(img, low, high):
91
+ img.clamp_(min=low, max=high)
92
+ img.sub_(low).div_(max(high - low, 1e-5))
93
+
94
+ def norm_range(t, value_range):
95
+ if value_range is not None:
96
+ norm_ip(t, value_range[0], value_range[1])
97
+ else:
98
+ norm_ip(t, float(t.min()), float(t.max()))
99
+
100
+ if scale_each is True:
101
+ for t in tensor: # loop over mini-batch dimension
102
+ norm_range(t, value_range)
103
+ else:
104
+ norm_range(tensor, value_range)
105
+
106
+ assert isinstance(tensor, torch.Tensor)
107
+ if tensor.size(0) == 1:
108
+ return tensor.squeeze(0)
109
+
110
+ # make the mini-batch of images into a grid
111
+ nmaps = tensor.size(0)
112
+ xmaps = min(nrow, nmaps)
113
+ ymaps = int(math.ceil(float(nmaps) / xmaps))
114
+ height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
115
+ num_channels = tensor.size(1)
116
+ grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)
117
+ k = 0
118
+ for y in range(ymaps):
119
+ for x in range(xmaps):
120
+ if k >= nmaps:
121
+ break
122
+ # Tensor.copy_() is a valid method but seems to be missing from the stubs
123
+ # https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_
124
+ grid.narrow(1, y * height + padding, height - padding).narrow( # type: ignore[attr-defined]
125
+ 2, x * width + padding, width - padding
126
+ ).copy_(tensor[k])
127
+ k = k + 1
128
+ return grid
129
+
130
+
131
+ @torch.no_grad()
132
+ def save_image(
133
+ tensor: Union[torch.Tensor, List[torch.Tensor]],
134
+ fp: Union[str, pathlib.Path, BinaryIO],
135
+ format: Optional[str] = None,
136
+ **kwargs,
137
+ ) -> None:
138
+ """
139
+ Save a given Tensor into an image file.
140
+
141
+ Args:
142
+ tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
143
+ saves the tensor as a grid of images by calling ``make_grid``.
144
+ fp (string or file object): A filename or a file object
145
+ format(Optional): If omitted, the format to use is determined from the filename extension.
146
+ If a file object was used instead of a filename, this parameter should always be used.
147
+ **kwargs: Other arguments are documented in ``make_grid``.
148
+ """
149
+
150
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
151
+ _log_api_usage_once(save_image)
152
+ grid = make_grid(tensor, **kwargs)
153
+ # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
154
+ ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
155
+ im = Image.fromarray(ndarr)
156
+ im.save(fp, format=format)
157
+
158
+
159
+ @torch.no_grad()
160
+ def draw_bounding_boxes(
161
+ image: torch.Tensor,
162
+ boxes: torch.Tensor,
163
+ labels: Optional[List[str]] = None,
164
+ colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str, Tuple[int, int, int]]] = None,
165
+ fill: Optional[bool] = False,
166
+ width: int = 1,
167
+ font: Optional[str] = None,
168
+ font_size: int = 10,
169
+ ) -> torch.Tensor:
170
+
171
+ """
172
+ Draws bounding boxes on given image.
173
+ The values of the input image should be uint8 between 0 and 255.
174
+ If fill is True, Resulting Tensor should be saved as PNG image.
175
+
176
+ Args:
177
+ image (Tensor): Tensor of shape (C x H x W) and dtype uint8.
178
+ boxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. Note that
179
+ the boxes are absolute coordinates with respect to the image. In other words: `0 <= xmin < xmax < W` and
180
+ `0 <= ymin < ymax < H`.
181
+ labels (List[str]): List containing the labels of bounding boxes.
182
+ colors (color or list of colors, optional): List containing the colors
183
+ of the boxes or single color for all boxes. The color can be represented as
184
+ PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
185
+ By default, random colors are generated for boxes.
186
+ fill (bool): If `True` fills the bounding box with specified color.
187
+ width (int): Width of bounding box.
188
+ font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
189
+ also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
190
+ `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
191
+ font_size (int): The requested font size in points.
192
+
193
+ Returns:
194
+ img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted.
195
+ """
196
+
197
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
198
+ _log_api_usage_once(draw_bounding_boxes)
199
+ if not isinstance(image, torch.Tensor):
200
+ raise TypeError(f"Tensor expected, got {type(image)}")
201
+ elif image.dtype != torch.uint8:
202
+ raise ValueError(f"Tensor uint8 expected, got {image.dtype}")
203
+ elif image.dim() != 3:
204
+ raise ValueError("Pass individual images, not batches")
205
+ elif image.size(0) not in {1, 3}:
206
+ raise ValueError("Only grayscale and RGB images are supported")
207
+
208
+ num_boxes = boxes.shape[0]
209
+
210
+ if labels is None:
211
+ labels: Union[List[str], List[None]] = [None] * num_boxes # type: ignore[no-redef]
212
+ elif len(labels) != num_boxes:
213
+ raise ValueError(
214
+ f"Number of boxes ({num_boxes}) and labels ({len(labels)}) mismatch. Please specify labels for each box."
215
+ )
216
+
217
+ if colors is None:
218
+ colors = _generate_color_palette(num_boxes)
219
+ elif isinstance(colors, list):
220
+ if len(colors) < num_boxes:
221
+ raise ValueError(f"Number of colors ({len(colors)}) is less than number of boxes ({num_boxes}). ")
222
+ else: # colors specifies a single color for all boxes
223
+ colors = [colors] * num_boxes
224
+
225
+ colors = [(ImageColor.getrgb(color) if isinstance(color, str) else color) for color in colors]
226
+
227
+ # Handle Grayscale images
228
+ if image.size(0) == 1:
229
+ image = torch.tile(image, (3, 1, 1))
230
+
231
+ ndarr = image.permute(1, 2, 0).cpu().numpy()
232
+ img_to_draw = Image.fromarray(ndarr)
233
+ img_boxes = boxes.to(torch.int64).tolist()
234
+
235
+ if fill:
236
+ draw = ImageDraw.Draw(img_to_draw, "RGBA")
237
+ else:
238
+ draw = ImageDraw.Draw(img_to_draw)
239
+
240
+ txt_font = ImageFont.load_default() if font is None else ImageFont.truetype(font=font, size=font_size)
241
+
242
+ for bbox, color, label in zip(img_boxes, colors, labels): # type: ignore[arg-type]
243
+ if fill:
244
+ fill_color = color + (100,)
245
+ draw.rectangle(bbox, width=width, outline=color, fill=fill_color)
246
+ else:
247
+ draw.rectangle(bbox, width=width, outline=color)
248
+
249
+ if label is not None:
250
+ margin = width + 1
251
+ draw.text((bbox[0] + margin, bbox[1] + margin), label, fill=color, font=txt_font)
252
+
253
+ return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
254
+
255
+
256
+ @torch.no_grad()
257
+ def draw_segmentation_masks(
258
+ image: torch.Tensor,
259
+ masks: torch.Tensor,
260
+ alpha: float = 0.8,
261
+ colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str, Tuple[int, int, int]]] = None,
262
+ ) -> torch.Tensor:
263
+
264
+ """
265
+ Draws segmentation masks on given RGB image.
266
+ The values of the input image should be uint8 between 0 and 255.
267
+
268
+ Args:
269
+ image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
270
+ masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.
271
+ alpha (float): Float number between 0 and 1 denoting the transparency of the masks.
272
+ 0 means full transparency, 1 means no transparency.
273
+ colors (color or list of colors, optional): List containing the colors
274
+ of the masks or single color for all masks. The color can be represented as
275
+ PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
276
+ By default, random colors are generated for each mask.
277
+
278
+ Returns:
279
+ img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.
280
+ """
281
+
282
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
283
+ _log_api_usage_once(draw_segmentation_masks)
284
+ if not isinstance(image, torch.Tensor):
285
+ raise TypeError(f"The image must be a tensor, got {type(image)}")
286
+ elif image.dtype != torch.uint8:
287
+ raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
288
+ elif image.dim() != 3:
289
+ raise ValueError("Pass individual images, not batches")
290
+ elif image.size()[0] != 3:
291
+ raise ValueError("Pass an RGB image. Other Image formats are not supported")
292
+ if masks.ndim == 2:
293
+ masks = masks[None, :, :]
294
+ if masks.ndim != 3:
295
+ raise ValueError("masks must be of shape (H, W) or (batch_size, H, W)")
296
+ if masks.dtype != torch.bool:
297
+ raise ValueError(f"The masks must be of dtype bool. Got {masks.dtype}")
298
+ if masks.shape[-2:] != image.shape[-2:]:
299
+ raise ValueError("The image and the masks must have the same height and width")
300
+
301
+ num_masks = masks.size()[0]
302
+ if colors is not None and num_masks > len(colors):
303
+ raise ValueError(f"There are more masks ({num_masks}) than colors ({len(colors)})")
304
+
305
+ if colors is None:
306
+ colors = _generate_color_palette(num_masks)
307
+
308
+ if not isinstance(colors, list):
309
+ colors = [colors]
310
+ if not isinstance(colors[0], (tuple, str)):
311
+ raise ValueError("colors must be a tuple or a string, or a list thereof")
312
+ if isinstance(colors[0], tuple) and len(colors[0]) != 3:
313
+ raise ValueError("It seems that you passed a tuple of colors instead of a list of colors")
314
+
315
+ out_dtype = torch.uint8
316
+
317
+ colors_ = []
318
+ for color in colors:
319
+ if isinstance(color, str):
320
+ color = ImageColor.getrgb(color)
321
+ colors_.append(torch.tensor(color, dtype=out_dtype))
322
+
323
+ img_to_draw = image.detach().clone()
324
+ # TODO: There might be a way to vectorize this
325
+ for mask, color in zip(masks, colors_):
326
+ img_to_draw[:, mask] = color[:, None]
327
+
328
+ out = image * (1 - alpha) + img_to_draw * alpha
329
+ return out.to(out_dtype)
330
+
331
+
332
+ @torch.no_grad()
333
+ def draw_keypoints(
334
+ image: torch.Tensor,
335
+ keypoints: torch.Tensor,
336
+ connectivity: Optional[List[Tuple[int, int]]] = None,
337
+ colors: Optional[Union[str, Tuple[int, int, int]]] = None,
338
+ radius: int = 2,
339
+ width: int = 3,
340
+ ) -> torch.Tensor:
341
+
342
+ """
343
+ Draws Keypoints on given RGB image.
344
+ The values of the input image should be uint8 between 0 and 255.
345
+
346
+ Args:
347
+ image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
348
+ keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoints location for each of the N instances,
349
+ in the format [x, y].
350
+ connectivity (List[Tuple[int, int]]]): A List of tuple where,
351
+ each tuple contains pair of keypoints to be connected.
352
+ colors (str, Tuple): The color can be represented as
353
+ PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
354
+ radius (int): Integer denoting radius of keypoint.
355
+ width (int): Integer denoting width of line connecting keypoints.
356
+
357
+ Returns:
358
+ img (Tensor[C, H, W]): Image Tensor of dtype uint8 with keypoints drawn.
359
+ """
360
+
361
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
362
+ _log_api_usage_once(draw_keypoints)
363
+ if not isinstance(image, torch.Tensor):
364
+ raise TypeError(f"The image must be a tensor, got {type(image)}")
365
+ elif image.dtype != torch.uint8:
366
+ raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
367
+ elif image.dim() != 3:
368
+ raise ValueError("Pass individual images, not batches")
369
+ elif image.size()[0] != 3:
370
+ raise ValueError("Pass an RGB image. Other Image formats are not supported")
371
+
372
+ if keypoints.ndim != 3:
373
+ raise ValueError("keypoints must be of shape (num_instances, K, 2)")
374
+
375
+ ndarr = image.permute(1, 2, 0).cpu().numpy()
376
+ img_to_draw = Image.fromarray(ndarr)
377
+ draw = ImageDraw.Draw(img_to_draw)
378
+ img_kpts = keypoints.to(torch.int64).tolist()
379
+
380
+ for kpt_id, kpt_inst in enumerate(img_kpts):
381
+ for inst_id, kpt in enumerate(kpt_inst):
382
+ x1 = kpt[0] - radius
383
+ x2 = kpt[0] + radius
384
+ y1 = kpt[1] - radius
385
+ y2 = kpt[1] + radius
386
+ draw.ellipse([x1, y1, x2, y2], fill=colors, outline=None, width=0)
387
+
388
+ if connectivity:
389
+ for connection in connectivity:
390
+ start_pt_x = kpt_inst[connection[0]][0]
391
+ start_pt_y = kpt_inst[connection[0]][1]
392
+
393
+ end_pt_x = kpt_inst[connection[1]][0]
394
+ end_pt_y = kpt_inst[connection[1]][1]
395
+
396
+ draw.line(
397
+ ((start_pt_x, start_pt_y), (end_pt_x, end_pt_y)),
398
+ width=width,
399
+ )
400
+
401
+ return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
402
+
403
+
404
+ # Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization
405
+ @torch.no_grad()
406
+ def flow_to_image(flow: torch.Tensor) -> torch.Tensor:
407
+
408
+ """
409
+ Converts a flow to an RGB image.
410
+
411
+ Args:
412
+ flow (Tensor): Flow of shape (N, 2, H, W) or (2, H, W) and dtype torch.float.
413
+
414
+ Returns:
415
+ img (Tensor): Image Tensor of dtype uint8 where each color corresponds
416
+ to a given flow direction. Shape is (N, 3, H, W) or (3, H, W) depending on the input.
417
+ """
418
+
419
+ if flow.dtype != torch.float:
420
+ raise ValueError(f"Flow should be of dtype torch.float, got {flow.dtype}.")
421
+
422
+ orig_shape = flow.shape
423
+ if flow.ndim == 3:
424
+ flow = flow[None] # Add batch dim
425
+
426
+ if flow.ndim != 4 or flow.shape[1] != 2:
427
+ raise ValueError(f"Input flow should have shape (2, H, W) or (N, 2, H, W), got {orig_shape}.")
428
+
429
+ max_norm = torch.sum(flow ** 2, dim=1).sqrt().max()
430
+ epsilon = torch.finfo((flow).dtype).eps
431
+ normalized_flow = flow / (max_norm + epsilon)
432
+ img = _normalized_flow_to_image(normalized_flow)
433
+
434
+ if len(orig_shape) == 3:
435
+ img = img[0] # Remove batch dim
436
+ return img
437
+
438
+
439
+ @torch.no_grad()
440
+ def _normalized_flow_to_image(normalized_flow: torch.Tensor) -> torch.Tensor:
441
+
442
+ """
443
+ Converts a batch of normalized flow to an RGB image.
444
+
445
+ Args:
446
+ normalized_flow (torch.Tensor): Normalized flow tensor of shape (N, 2, H, W)
447
+ Returns:
448
+ img (Tensor(N, 3, H, W)): Flow visualization image of dtype uint8.
449
+ """
450
+
451
+ N, _, H, W = normalized_flow.shape
452
+ device = normalized_flow.device
453
+ flow_image = torch.zeros((N, 3, H, W), dtype=torch.uint8, device=device)
454
+ colorwheel = _make_colorwheel().to(device) # shape [55x3]
455
+ num_cols = colorwheel.shape[0]
456
+ norm = torch.sum(normalized_flow ** 2, dim=1).sqrt()
457
+ a = torch.atan2(-normalized_flow[:, 1, :, :], -normalized_flow[:, 0, :, :]) / torch.pi
458
+ fk = (a + 1) / 2 * (num_cols - 1)
459
+ k0 = torch.floor(fk).to(torch.long)
460
+ k1 = k0 + 1
461
+ k1[k1 == num_cols] = 0
462
+ f = fk - k0
463
+
464
+ for c in range(colorwheel.shape[1]):
465
+ tmp = colorwheel[:, c]
466
+ col0 = tmp[k0] / 255.0
467
+ col1 = tmp[k1] / 255.0
468
+ col = (1 - f) * col0 + f * col1
469
+ col = 1 - norm * (1 - col)
470
+ flow_image[:, c, :, :] = torch.floor(255 * col)
471
+ return flow_image
472
+
473
+
474
+ def _make_colorwheel() -> torch.Tensor:
475
+ """
476
+ Generates a color wheel for optical flow visualization as presented in:
477
+ Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007)
478
+ URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf.
479
+
480
+ Returns:
481
+ colorwheel (Tensor[55, 3]): Colorwheel Tensor.
482
+ """
483
+
484
+ RY = 15
485
+ YG = 6
486
+ GC = 4
487
+ CB = 11
488
+ BM = 13
489
+ MR = 6
490
+
491
+ ncols = RY + YG + GC + CB + BM + MR
492
+ colorwheel = torch.zeros((ncols, 3))
493
+ col = 0
494
+
495
+ # RY
496
+ colorwheel[0:RY, 0] = 255
497
+ colorwheel[0:RY, 1] = torch.floor(255 * torch.arange(0, RY) / RY)
498
+ col = col + RY
499
+ # YG
500
+ colorwheel[col : col + YG, 0] = 255 - torch.floor(255 * torch.arange(0, YG) / YG)
501
+ colorwheel[col : col + YG, 1] = 255
502
+ col = col + YG
503
+ # GC
504
+ colorwheel[col : col + GC, 1] = 255
505
+ colorwheel[col : col + GC, 2] = torch.floor(255 * torch.arange(0, GC) / GC)
506
+ col = col + GC
507
+ # CB
508
+ colorwheel[col : col + CB, 1] = 255 - torch.floor(255 * torch.arange(CB) / CB)
509
+ colorwheel[col : col + CB, 2] = 255
510
+ col = col + CB
511
+ # BM
512
+ colorwheel[col : col + BM, 2] = 255
513
+ colorwheel[col : col + BM, 0] = torch.floor(255 * torch.arange(0, BM) / BM)
514
+ col = col + BM
515
+ # MR
516
+ colorwheel[col : col + MR, 2] = 255 - torch.floor(255 * torch.arange(MR) / MR)
517
+ colorwheel[col : col + MR, 0] = 255
518
+ return colorwheel
519
+
520
+
521
+ def _generate_color_palette(num_objects: int):
522
+ palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
523
+ return [tuple((i * palette) % 255) for i in range(num_objects)]
524
+
525
+
526
+ def _log_api_usage_once(obj: Any) -> None:
527
+
528
+ """
529
+ Logs API usage(module and name) within an organization.
530
+ In a large ecosystem, it's often useful to track the PyTorch and
531
+ TorchVision APIs usage. This API provides the similar functionality to the
532
+ logging module in the Python stdlib. It can be used for debugging purpose
533
+ to log which methods are used and by default it is inactive, unless the user
534
+ manually subscribes a logger via the `SetAPIUsageLogger method <https://github.com/pytorch/pytorch/blob/eb3b9fe719b21fae13c7a7cf3253f970290a573e/c10/util/Logging.cpp#L114>`_.
535
+ Please note it is triggered only once for the same API call within a process.
536
+ It does not collect any data from open-source users since it is no-op by default.
537
+ For more information, please refer to
538
+ * PyTorch note: https://pytorch.org/docs/stable/notes/large_scale_deployments.html#api-usage-logging;
539
+ * Logging policy: https://github.com/pytorch/vision/issues/5052;
540
+
541
+ Args:
542
+ obj (class instance or method): an object to extract info from.
543
+ """
544
+ if not obj.__module__.startswith("torchvision"):
545
+ return
546
+ name = obj.__class__.__name__
547
+ if isinstance(obj, FunctionType):
548
+ name = obj.__name__
549
+ torch._C._log_api_usage_once(f"{obj.__module__}.{name}")
models/vits.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ import torch
9
+ import torch.nn as nn
10
+ from functools import partial, reduce
11
+ from operator import mul
12
+
13
+ from timm.models.vision_transformer import VisionTransformer, _cfg
14
+ from timm.models.layers.helpers import to_2tuple
15
+ from timm.models.layers import PatchEmbed
16
+
17
+ __all__ = [
18
+ 'vit_small',
19
+ 'vit_base',
20
+ 'vit_conv_small',
21
+ 'vit_conv_base',
22
+ ]
23
+
24
+
25
+ class VisionTransformerMoCo(VisionTransformer):
26
+ def __init__(self, stop_grad_conv1=False, **kwargs):
27
+ super().__init__(**kwargs)
28
+ # Use fixed 2D sin-cos position embedding
29
+ self.build_2d_sincos_position_embedding()
30
+
31
+ # weight initialization
32
+ for name, m in self.named_modules():
33
+ if isinstance(m, nn.Linear):
34
+ if 'qkv' in name:
35
+ # treat the weights of Q, K, V separately
36
+ val = math.sqrt(6. / float(m.weight.shape[0] // 3 + m.weight.shape[1]))
37
+ nn.init.uniform_(m.weight, -val, val)
38
+ else:
39
+ nn.init.xavier_uniform_(m.weight)
40
+ nn.init.zeros_(m.bias)
41
+ nn.init.normal_(self.cls_token, std=1e-6)
42
+
43
+ if isinstance(self.patch_embed, PatchEmbed):
44
+ # xavier_uniform initialization
45
+ val = math.sqrt(6. / float(3 * reduce(mul, self.patch_embed.patch_size, 1) + self.embed_dim))
46
+ nn.init.uniform_(self.patch_embed.proj.weight, -val, val)
47
+ nn.init.zeros_(self.patch_embed.proj.bias)
48
+
49
+ if stop_grad_conv1:
50
+ self.patch_embed.proj.weight.requires_grad = False
51
+ self.patch_embed.proj.bias.requires_grad = False
52
+
53
+ def build_2d_sincos_position_embedding(self, temperature=10000.):
54
+ h, w = self.patch_embed.grid_size
55
+ grid_w = torch.arange(w, dtype=torch.float32)
56
+ grid_h = torch.arange(h, dtype=torch.float32)
57
+ grid_w, grid_h = torch.meshgrid(grid_w, grid_h)
58
+ assert self.embed_dim % 4 == 0, 'Embed dimension must be divisible by 4 for 2D sin-cos position embedding'
59
+ pos_dim = self.embed_dim // 4
60
+ omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim
61
+ omega = 1. / (temperature**omega)
62
+ out_w = torch.einsum('m,d->md', [grid_w.flatten(), omega])
63
+ out_h = torch.einsum('m,d->md', [grid_h.flatten(), omega])
64
+ pos_emb = torch.cat([torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)], dim=1)[None, :, :]
65
+
66
+ assert self.num_tokens == 1, 'Assuming one and only one token, [cls]'
67
+ pe_token = torch.zeros([1, 1, self.embed_dim], dtype=torch.float32)
68
+ self.pos_embed = nn.Parameter(torch.cat([pe_token, pos_emb], dim=1))
69
+ self.pos_embed.requires_grad = False
70
+
71
+
72
+ class ConvStem(nn.Module):
73
+ """
74
+ ConvStem, from Early Convolutions Help Transformers See Better, Tete et al. https://arxiv.org/abs/2106.14881
75
+ """
76
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
77
+ super().__init__()
78
+
79
+ assert patch_size == 16, 'ConvStem only supports patch size of 16'
80
+ assert embed_dim % 8 == 0, 'Embed dimension must be divisible by 8 for ConvStem'
81
+
82
+ img_size = to_2tuple(img_size)
83
+ patch_size = to_2tuple(patch_size)
84
+ self.img_size = img_size
85
+ self.patch_size = patch_size
86
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
87
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
88
+ self.flatten = flatten
89
+
90
+ # build stem, similar to the design in https://arxiv.org/abs/2106.14881
91
+ stem = []
92
+ input_dim, output_dim = 3, embed_dim // 8
93
+ for l in range(4):
94
+ stem.append(nn.Conv2d(input_dim, output_dim, kernel_size=3, stride=2, padding=1, bias=False))
95
+ stem.append(nn.BatchNorm2d(output_dim))
96
+ stem.append(nn.ReLU(inplace=True))
97
+ input_dim = output_dim
98
+ output_dim *= 2
99
+ stem.append(nn.Conv2d(input_dim, embed_dim, kernel_size=1))
100
+ self.proj = nn.Sequential(*stem)
101
+
102
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
103
+
104
+ def forward(self, x):
105
+ B, C, H, W = x.shape
106
+ assert H == self.img_size[0] and W == self.img_size[1], \
107
+ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
108
+ x = self.proj(x)
109
+ if self.flatten:
110
+ x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
111
+ x = self.norm(x)
112
+ return x
113
+
114
+
115
+ def vit_small(**kwargs):
116
+ model = VisionTransformerMoCo(
117
+ patch_size=16, embed_dim=384, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,
118
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
119
+ model.default_cfg = _cfg()
120
+ return model
121
+
122
+ def vit_base(**kwargs):
123
+ model = VisionTransformerMoCo(
124
+ patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,
125
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
126
+ model.default_cfg = _cfg()
127
+ return model
128
+
129
+ def vit_conv_small(**kwargs):
130
+ # minus one ViT block
131
+ model = VisionTransformerMoCo(
132
+ patch_size=16, embed_dim=384, depth=11, num_heads=12, mlp_ratio=4, qkv_bias=True,
133
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), embed_layer=ConvStem, **kwargs)
134
+ model.default_cfg = _cfg()
135
+ return model
136
+
137
+ def vit_conv_base(**kwargs):
138
+ # minus one ViT block
139
+ model = VisionTransformerMoCo(
140
+ patch_size=16, embed_dim=768, depth=11, num_heads=12, mlp_ratio=4, qkv_bias=True,
141
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), embed_layer=ConvStem, **kwargs)
142
+ model.default_cfg = _cfg()
143
+ return model
networks/__init__.py ADDED
File without changes
networks/base_model.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import init
5
+ from torch.optim import lr_scheduler
6
+
7
+
8
+ class BaseModel(nn.Module):
9
+ def __init__(self, opt):
10
+ super(BaseModel, self).__init__()
11
+ self.opt = opt
12
+ self.total_steps = 0
13
+ self.save_dir = os.path.join(opt.checkpoints_dir, opt.name)
14
+ self.device = torch.device('cuda:{}'.format(opt.gpu_ids[0])) if opt.gpu_ids else torch.device('cpu')
15
+
16
+ def save_networks(self, save_filename):
17
+ save_path = os.path.join(self.save_dir, save_filename)
18
+
19
+ # serialize model and optimizer to dict
20
+ # state_dict = {
21
+ # 'model': self.model.state_dict(),
22
+ # 'optimizer' : self.optimizer.state_dict(),
23
+ # 'total_steps' : self.total_steps,
24
+ # }
25
+ if self.opt.fix_backbone:
26
+ if self.opt.head_type == "attention" or self.opt.head_type == "crossattention":
27
+ state_dict = self.model.attention_head.state_dict()
28
+ elif self.opt.head_type == "mlp":
29
+ # state_dict = {
30
+ # 'mlp': self.model.mlp.state_dict(),
31
+ # 'fc' : self.model.fc.state_dict(),
32
+ # }
33
+ state_dict = self.model.mlp.state_dict()
34
+ elif self.opt.head_type == "transformer":
35
+ state_dict = {
36
+ 'transformer': self.model.transformer_block.state_dict(),
37
+ 'fc' : self.model.fc.state_dict(),
38
+ }
39
+ else:
40
+ state_dict = {
41
+ "weight": self.model.fc.state_dict()["weight"],
42
+ "bias": self.model.fc.state_dict()["bias"],}
43
+ else:
44
+ state_dict = self.model.state_dict()
45
+
46
+ torch.save(state_dict, save_path)
47
+
48
+
49
+ def eval(self):
50
+ self.model.eval()
51
+
52
+ def test(self):
53
+ with torch.no_grad():
54
+ self.forward()
55
+
56
+
57
+ def init_weights(net, init_type='normal', gain=0.02):
58
+ def init_func(m):
59
+ classname = m.__class__.__name__
60
+ if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
61
+ if init_type == 'normal':
62
+ init.normal_(m.weight.data, 0.0, gain)
63
+ elif init_type == 'xavier':
64
+ init.xavier_normal_(m.weight.data, gain=gain)
65
+ elif init_type == 'kaiming':
66
+ init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
67
+ elif init_type == 'orthogonal':
68
+ init.orthogonal_(m.weight.data, gain=gain)
69
+ else:
70
+ raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
71
+ if hasattr(m, 'bias') and m.bias is not None:
72
+ init.constant_(m.bias.data, 0.0)
73
+ elif classname.find('BatchNorm2d') != -1:
74
+ init.normal_(m.weight.data, 1.0, gain)
75
+ init.constant_(m.bias.data, 0.0)
76
+
77
+ print('initialize network with %s' % init_type)
78
+ net.apply(init_func)
networks/lpf.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2019, Adobe Inc. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
4
+ # 4.0 International Public License. To view a copy of this license, visit
5
+ # https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.
6
+
7
+ import torch
8
+ import torch.nn.parallel
9
+ import numpy as np
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from IPython import embed
13
+
14
+ class Downsample(nn.Module):
15
+ def __init__(self, pad_type='reflect', filt_size=3, stride=2, channels=None, pad_off=0):
16
+ super(Downsample, self).__init__()
17
+ self.filt_size = filt_size
18
+ self.pad_off = pad_off
19
+ self.pad_sizes = [int(1.*(filt_size-1)/2), int(np.ceil(1.*(filt_size-1)/2)), int(1.*(filt_size-1)/2), int(np.ceil(1.*(filt_size-1)/2))]
20
+ self.pad_sizes = [pad_size+pad_off for pad_size in self.pad_sizes]
21
+ self.stride = stride
22
+ self.off = int((self.stride-1)/2.)
23
+ self.channels = channels
24
+
25
+ # print('Filter size [%i]'%filt_size)
26
+ if(self.filt_size==1):
27
+ a = np.array([1.,])
28
+ elif(self.filt_size==2):
29
+ a = np.array([1., 1.])
30
+ elif(self.filt_size==3):
31
+ a = np.array([1., 2., 1.])
32
+ elif(self.filt_size==4):
33
+ a = np.array([1., 3., 3., 1.])
34
+ elif(self.filt_size==5):
35
+ a = np.array([1., 4., 6., 4., 1.])
36
+ elif(self.filt_size==6):
37
+ a = np.array([1., 5., 10., 10., 5., 1.])
38
+ elif(self.filt_size==7):
39
+ a = np.array([1., 6., 15., 20., 15., 6., 1.])
40
+
41
+ filt = torch.Tensor(a[:,None]*a[None,:])
42
+ filt = filt/torch.sum(filt)
43
+ self.register_buffer('filt', filt[None,None,:,:].repeat((self.channels,1,1,1)))
44
+
45
+ self.pad = get_pad_layer(pad_type)(self.pad_sizes)
46
+
47
+ def forward(self, inp):
48
+ if(self.filt_size==1):
49
+ if(self.pad_off==0):
50
+ return inp[:,:,::self.stride,::self.stride]
51
+ else:
52
+ return self.pad(inp)[:,:,::self.stride,::self.stride]
53
+ else:
54
+ return F.conv2d(self.pad(inp), self.filt, stride=self.stride, groups=inp.shape[1])
55
+
56
+ def get_pad_layer(pad_type):
57
+ if(pad_type in ['refl','reflect']):
58
+ PadLayer = nn.ReflectionPad2d
59
+ elif(pad_type in ['repl','replicate']):
60
+ PadLayer = nn.ReplicationPad2d
61
+ elif(pad_type=='zero'):
62
+ PadLayer = nn.ZeroPad2d
63
+ else:
64
+ print('Pad type [%s] not recognized'%pad_type)
65
+ return PadLayer
66
+
67
+
68
+ class Downsample1D(nn.Module):
69
+ def __init__(self, pad_type='reflect', filt_size=3, stride=2, channels=None, pad_off=0):
70
+ super(Downsample1D, self).__init__()
71
+ self.filt_size = filt_size
72
+ self.pad_off = pad_off
73
+ self.pad_sizes = [int(1. * (filt_size - 1) / 2), int(np.ceil(1. * (filt_size - 1) / 2))]
74
+ self.pad_sizes = [pad_size + pad_off for pad_size in self.pad_sizes]
75
+ self.stride = stride
76
+ self.off = int((self.stride - 1) / 2.)
77
+ self.channels = channels
78
+
79
+ # print('Filter size [%i]' % filt_size)
80
+ if(self.filt_size == 1):
81
+ a = np.array([1., ])
82
+ elif(self.filt_size == 2):
83
+ a = np.array([1., 1.])
84
+ elif(self.filt_size == 3):
85
+ a = np.array([1., 2., 1.])
86
+ elif(self.filt_size == 4):
87
+ a = np.array([1., 3., 3., 1.])
88
+ elif(self.filt_size == 5):
89
+ a = np.array([1., 4., 6., 4., 1.])
90
+ elif(self.filt_size == 6):
91
+ a = np.array([1., 5., 10., 10., 5., 1.])
92
+ elif(self.filt_size == 7):
93
+ a = np.array([1., 6., 15., 20., 15., 6., 1.])
94
+
95
+ filt = torch.Tensor(a)
96
+ filt = filt / torch.sum(filt)
97
+ self.register_buffer('filt', filt[None, None, :].repeat((self.channels, 1, 1)))
98
+
99
+ self.pad = get_pad_layer_1d(pad_type)(self.pad_sizes)
100
+
101
+ def forward(self, inp):
102
+ if(self.filt_size == 1):
103
+ if(self.pad_off == 0):
104
+ return inp[:, :, ::self.stride]
105
+ else:
106
+ return self.pad(inp)[:, :, ::self.stride]
107
+ else:
108
+ return F.conv1d(self.pad(inp), self.filt, stride=self.stride, groups=inp.shape[1])
109
+
110
+
111
+ def get_pad_layer_1d(pad_type):
112
+ if(pad_type in ['refl', 'reflect']):
113
+ PadLayer = nn.ReflectionPad1d
114
+ elif(pad_type in ['repl', 'replicate']):
115
+ PadLayer = nn.ReplicationPad1d
116
+ elif(pad_type == 'zero'):
117
+ PadLayer = nn.ZeroPad1d
118
+ else:
119
+ print('Pad type [%s] not recognized' % pad_type)
120
+ return PadLayer
networks/resnet_lpf.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code is built from the PyTorch examples repository: https://github.com/pytorch/vision/tree/master/torchvision/models.
2
+ # Copyright (c) 2017 Torch Contributors.
3
+ # The Pytorch examples are available under the BSD 3-Clause License.
4
+ #
5
+ # ==========================================================================================
6
+ #
7
+ # Adobe’s modifications are Copyright 2019 Adobe. All rights reserved.
8
+ # Adobe’s modifications are licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
9
+ # 4.0 International Public License (CC-NC-SA-4.0). To view a copy of the license, visit
10
+ # https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.
11
+ #
12
+ # ==========================================================================================
13
+ #
14
+ # BSD-3 License
15
+ #
16
+ # Redistribution and use in source and binary forms, with or without
17
+ # modification, are permitted provided that the following conditions are met:
18
+ #
19
+ # * Redistributions of source code must retain the above copyright notice, this
20
+ # list of conditions and the following disclaimer.
21
+ #
22
+ # * Redistributions in binary form must reproduce the above copyright notice,
23
+ # this list of conditions and the following disclaimer in the documentation
24
+ # and/or other materials provided with the distribution.
25
+ #
26
+ # * Neither the name of the copyright holder nor the names of its
27
+ # contributors may be used to endorse or promote products derived from
28
+ # this software without specific prior written permission.
29
+ #
30
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
31
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
33
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
34
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
37
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
38
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39
+
40
+ import torch.nn as nn
41
+ import torch.utils.model_zoo as model_zoo
42
+ from .lpf import *
43
+
44
+ __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
45
+ 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d']
46
+
47
+
48
+ # model_urls = {
49
+ # 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
50
+ # 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
51
+ # 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
52
+ # 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
53
+ # 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
54
+ # }
55
+
56
+
57
+ def conv3x3(in_planes, out_planes, stride=1, groups=1):
58
+ """3x3 convolution with padding"""
59
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
60
+ padding=1, groups=groups, bias=False)
61
+
62
+ def conv1x1(in_planes, out_planes, stride=1):
63
+ """1x1 convolution"""
64
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
65
+
66
+ class BasicBlock(nn.Module):
67
+ expansion = 1
68
+
69
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, norm_layer=None, filter_size=1):
70
+ super(BasicBlock, self).__init__()
71
+ if norm_layer is None:
72
+ norm_layer = nn.BatchNorm2d
73
+ if groups != 1:
74
+ raise ValueError('BasicBlock only supports groups=1')
75
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
76
+ self.conv1 = conv3x3(inplanes, planes)
77
+ self.bn1 = norm_layer(planes)
78
+ self.relu = nn.ReLU(inplace=True)
79
+ if(stride==1):
80
+ self.conv2 = conv3x3(planes,planes)
81
+ else:
82
+ self.conv2 = nn.Sequential(Downsample(filt_size=filter_size, stride=stride, channels=planes),
83
+ conv3x3(planes, planes),)
84
+ self.bn2 = norm_layer(planes)
85
+ self.downsample = downsample
86
+ self.stride = stride
87
+
88
+ def forward(self, x):
89
+ identity = x
90
+
91
+ out = self.conv1(x)
92
+ out = self.bn1(out)
93
+ out = self.relu(out)
94
+
95
+ out = self.conv2(out)
96
+ out = self.bn2(out)
97
+
98
+ if self.downsample is not None:
99
+ identity = self.downsample(x)
100
+
101
+ out += identity
102
+ out = self.relu(out)
103
+
104
+ return out
105
+
106
+
107
+ class Bottleneck(nn.Module):
108
+ expansion = 4
109
+
110
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, norm_layer=None, filter_size=1):
111
+ super(Bottleneck, self).__init__()
112
+ if norm_layer is None:
113
+ norm_layer = nn.BatchNorm2d
114
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
115
+ self.conv1 = conv1x1(inplanes, planes)
116
+ self.bn1 = norm_layer(planes)
117
+ self.conv2 = conv3x3(planes, planes, groups) # stride moved
118
+ self.bn2 = norm_layer(planes)
119
+ if(stride==1):
120
+ self.conv3 = conv1x1(planes, planes * self.expansion)
121
+ else:
122
+ self.conv3 = nn.Sequential(Downsample(filt_size=filter_size, stride=stride, channels=planes),
123
+ conv1x1(planes, planes * self.expansion))
124
+ self.bn3 = norm_layer(planes * self.expansion)
125
+ self.relu = nn.ReLU(inplace=True)
126
+ self.downsample = downsample
127
+ self.stride = stride
128
+
129
+ def forward(self, x):
130
+ identity = x
131
+
132
+ out = self.conv1(x)
133
+ out = self.bn1(out)
134
+ out = self.relu(out)
135
+
136
+ out = self.conv2(out)
137
+ out = self.bn2(out)
138
+ out = self.relu(out)
139
+
140
+ out = self.conv3(out)
141
+ out = self.bn3(out)
142
+
143
+ if self.downsample is not None:
144
+ identity = self.downsample(x)
145
+
146
+ out += identity
147
+ out = self.relu(out)
148
+
149
+ return out
150
+
151
+
152
+ class ResNet(nn.Module):
153
+
154
+ def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
155
+ groups=1, width_per_group=64, norm_layer=None, filter_size=1, pool_only=True):
156
+ super(ResNet, self).__init__()
157
+ if norm_layer is None:
158
+ norm_layer = nn.BatchNorm2d
159
+ planes = [int(width_per_group * groups * 2 ** i) for i in range(4)]
160
+ self.inplanes = planes[0]
161
+
162
+ if(pool_only):
163
+ self.conv1 = nn.Conv2d(3, planes[0], kernel_size=7, stride=2, padding=3, bias=False)
164
+ else:
165
+ self.conv1 = nn.Conv2d(3, planes[0], kernel_size=7, stride=1, padding=3, bias=False)
166
+ self.bn1 = norm_layer(planes[0])
167
+ self.relu = nn.ReLU(inplace=True)
168
+
169
+ if(pool_only):
170
+ self.maxpool = nn.Sequential(*[nn.MaxPool2d(kernel_size=2, stride=1),
171
+ Downsample(filt_size=filter_size, stride=2, channels=planes[0])])
172
+ else:
173
+ self.maxpool = nn.Sequential(*[Downsample(filt_size=filter_size, stride=2, channels=planes[0]),
174
+ nn.MaxPool2d(kernel_size=2, stride=1),
175
+ Downsample(filt_size=filter_size, stride=2, channels=planes[0])])
176
+
177
+ self.layer1 = self._make_layer(block, planes[0], layers[0], groups=groups, norm_layer=norm_layer)
178
+ self.layer2 = self._make_layer(block, planes[1], layers[1], stride=2, groups=groups, norm_layer=norm_layer, filter_size=filter_size)
179
+ self.layer3 = self._make_layer(block, planes[2], layers[2], stride=2, groups=groups, norm_layer=norm_layer, filter_size=filter_size)
180
+ self.layer4 = self._make_layer(block, planes[3], layers[3], stride=2, groups=groups, norm_layer=norm_layer, filter_size=filter_size)
181
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
182
+ self.fc = nn.Linear(planes[3] * block.expansion, num_classes)
183
+
184
+ for m in self.modules():
185
+ if isinstance(m, nn.Conv2d):
186
+ if(m.in_channels!=m.out_channels or m.out_channels!=m.groups or m.bias is not None):
187
+ # don't want to reinitialize downsample layers, code assuming normal conv layers will not have these characteristics
188
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
189
+ else:
190
+ print('Not initializing')
191
+ elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
192
+ nn.init.constant_(m.weight, 1)
193
+ nn.init.constant_(m.bias, 0)
194
+
195
+ # Zero-initialize the last BN in each residual branch,
196
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
197
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
198
+ if zero_init_residual:
199
+ for m in self.modules():
200
+ if isinstance(m, Bottleneck):
201
+ nn.init.constant_(m.bn3.weight, 0)
202
+ elif isinstance(m, BasicBlock):
203
+ nn.init.constant_(m.bn2.weight, 0)
204
+
205
+ def _make_layer(self, block, planes, blocks, stride=1, groups=1, norm_layer=None, filter_size=1):
206
+ if norm_layer is None:
207
+ norm_layer = nn.BatchNorm2d
208
+ downsample = None
209
+ if stride != 1 or self.inplanes != planes * block.expansion:
210
+ # downsample = nn.Sequential(
211
+ # conv1x1(self.inplanes, planes * block.expansion, stride, filter_size=filter_size),
212
+ # norm_layer(planes * block.expansion),
213
+ # )
214
+
215
+ downsample = [Downsample(filt_size=filter_size, stride=stride, channels=self.inplanes),] if(stride !=1) else []
216
+ downsample += [conv1x1(self.inplanes, planes * block.expansion, 1),
217
+ norm_layer(planes * block.expansion)]
218
+ # print(downsample)
219
+ downsample = nn.Sequential(*downsample)
220
+
221
+ layers = []
222
+ layers.append(block(self.inplanes, planes, stride, downsample, groups, norm_layer, filter_size=filter_size))
223
+ self.inplanes = planes * block.expansion
224
+ for _ in range(1, blocks):
225
+ layers.append(block(self.inplanes, planes, groups=groups, norm_layer=norm_layer, filter_size=filter_size))
226
+
227
+ return nn.Sequential(*layers)
228
+
229
+ def forward(self, x):
230
+ x = self.conv1(x)
231
+ x = self.bn1(x)
232
+ x = self.relu(x)
233
+ x = self.maxpool(x)
234
+
235
+ x = self.layer1(x)
236
+ x = self.layer2(x)
237
+ x = self.layer3(x)
238
+ x = self.layer4(x)
239
+
240
+ x = self.avgpool(x)
241
+ x = x.view(x.size(0), -1)
242
+ x = self.fc(x)
243
+
244
+ return x
245
+
246
+
247
+ def resnet18(pretrained=False, filter_size=1, pool_only=True, **kwargs):
248
+ """Constructs a ResNet-18 model.
249
+ Args:
250
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
251
+ """
252
+ model = ResNet(BasicBlock, [2, 2, 2, 2], filter_size=filter_size, pool_only=pool_only, **kwargs)
253
+ if pretrained:
254
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
255
+ return model
256
+
257
+
258
+ def resnet34(pretrained=False, filter_size=1, pool_only=True, **kwargs):
259
+ """Constructs a ResNet-34 model.
260
+ Args:
261
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
262
+ """
263
+ model = ResNet(BasicBlock, [3, 4, 6, 3], filter_size=filter_size, pool_only=pool_only, **kwargs)
264
+ if pretrained:
265
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
266
+ return model
267
+
268
+
269
+ def resnet50(pretrained=False, filter_size=1, pool_only=True, **kwargs):
270
+ """Constructs a ResNet-50 model.
271
+ Args:
272
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
273
+ """
274
+ model = ResNet(Bottleneck, [3, 4, 6, 3], filter_size=filter_size, pool_only=pool_only, **kwargs)
275
+ if pretrained:
276
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
277
+ return model
278
+
279
+
280
+ def resnet101(pretrained=False, filter_size=1, pool_only=True, **kwargs):
281
+ """Constructs a ResNet-101 model.
282
+ Args:
283
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
284
+ """
285
+ model = ResNet(Bottleneck, [3, 4, 23, 3], filter_size=filter_size, pool_only=pool_only, **kwargs)
286
+ if pretrained:
287
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
288
+ return model
289
+
290
+
291
+ def resnet152(pretrained=False, filter_size=1, pool_only=True, **kwargs):
292
+ """Constructs a ResNet-152 model.
293
+ Args:
294
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
295
+ """
296
+ model = ResNet(Bottleneck, [3, 8, 36, 3], filter_size=filter_size, pool_only=pool_only, **kwargs)
297
+ if pretrained:
298
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
299
+ return model
300
+
301
+
302
+ def resnext50_32x4d(pretrained=False, filter_size=1, pool_only=True, **kwargs):
303
+ model = ResNet(Bottleneck, [3, 4, 6, 3], groups=4, width_per_group=32, filter_size=filter_size, pool_only=pool_only, **kwargs)
304
+ # if pretrained:
305
+ # model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
306
+ return model
307
+
308
+
309
+ def resnext101_32x8d(pretrained=False, filter_size=1, pool_only=True, **kwargs):
310
+ model = ResNet(Bottleneck, [3, 4, 23, 3], groups=8, width_per_group=32, filter_size=filter_size, pool_only=pool_only, **kwargs)
311
+ # if pretrained:
312
+ # model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
313
+ return model
networks/trainer.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import torch
3
+ import torch.nn as nn
4
+ from networks.base_model import BaseModel, init_weights
5
+ import sys
6
+ from models import get_model
7
+
8
+ class Trainer(BaseModel):
9
+ def name(self):
10
+ return 'Trainer'
11
+
12
+ def __init__(self, opt):
13
+ super(Trainer, self).__init__(opt)
14
+ self.opt = opt
15
+ self.model = get_model(opt)
16
+ print(f"using {self.model.__class__.__name__}")
17
+
18
+ if opt.head_type == "fc":
19
+ torch.nn.init.normal_(self.model.fc.weight.data, 0.0, opt.init_gain)
20
+ elif opt.head_type == "attention":
21
+ for name, params in self.model.attention_head.named_parameters():
22
+ torch.nn.init.normal_(params, 0.0, opt.init_gain)
23
+
24
+ if opt.resume_path is not None:
25
+ state_dict = torch.load(opt.resume_path)
26
+ if self.opt.fix_backbone:
27
+ if self.opt.head_type == "attention" or opt.head_type == "crossattention":
28
+ self.model.attention_head.load_state_dict(state_dict)
29
+ else:
30
+ self.model.fc.load_state_dict(state_dict)
31
+ else:
32
+ self.model.load_state_dict(state_dict)
33
+
34
+ if opt.fix_backbone:
35
+ params = []
36
+ if opt.head_type == "fc":
37
+ for name, p in self.model.named_parameters():
38
+ if name=="fc.weight" or name=="fc.bias":
39
+ params.append(p)
40
+ else:
41
+ p.requires_grad = False
42
+ elif opt.head_type == "mlp":
43
+ for p in self.model.mlp.parameters():
44
+ params.append(p)
45
+ elif opt.head_type == "attention" or opt.head_type == "crossattention":
46
+ for p in self.model.attention_head.parameters():
47
+ params.append(p)
48
+
49
+ elif opt.head_type == "transformer":
50
+ params = [{'params': self.model.transformer_block.parameters()},
51
+ {'params': self.model.fc.parameters()}]
52
+ # params = self.model.transformer.parameters()
53
+ # params["fc"] = self.model.fc.parameters()
54
+
55
+
56
+ else:
57
+ print("Your backbone is not fixed. Are you sure you want to proceed? If this is a mistake, enable the --fix_backbone command during training and rerun")
58
+ import time
59
+ time.sleep(3)
60
+ params = self.model.parameters()
61
+
62
+ if opt.optim == 'adam':
63
+ self.optimizer = torch.optim.AdamW(params, lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=opt.weight_decay)
64
+ elif opt.optim == 'sgd':
65
+ self.optimizer = torch.optim.SGD(params, lr=opt.lr, momentum=0.0, weight_decay=opt.weight_decay)
66
+ else:
67
+ raise ValueError("optim should be [adam, sgd]")
68
+
69
+ self.loss_fn = nn.BCEWithLogitsLoss()
70
+
71
+ # self.model = nn.parallel.DistributedDataParallel(self.model)
72
+ self.model.to(opt.gpu_ids[0])
73
+
74
+
75
+
76
+ def adjust_learning_rate(self, min_lr=1e-6):
77
+ for param_group in self.optimizer.param_groups:
78
+ param_group['lr'] /= 10.
79
+ if param_group['lr'] < min_lr:
80
+ return False
81
+ return True
82
+
83
+
84
+ def set_input(self, input):
85
+ self.input = input[0].to(self.device)
86
+ self.label = input[1].to(self.device).float()
87
+
88
+
89
+ def forward(self):
90
+ self.output = self.model(self.input)
91
+ # self.output = self.output.view(-1).unsqueeze(1)
92
+ self.output = self.output
93
+
94
+
95
+
96
+
97
+ def get_loss(self):
98
+ return self.loss_fn(self.output.squeeze(1), self.label)
99
+
100
+ def optimize_parameters(self):
101
+ self.forward()
102
+ self.loss = self.loss_fn(self.output.squeeze(1), self.label)
103
+ self.optimizer.zero_grad()
104
+ self.loss.backward()
105
+ self.optimizer.step()
106
+
107
+
options/__init__.py ADDED
File without changes
options/base_options.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import torch
4
+
5
+
6
+ class BaseOptions():
7
+ def __init__(self):
8
+ self.initialized = False
9
+
10
+ def initialize(self, parser):
11
+
12
+ parser.add_argument('--head_type', default='attention')
13
+ parser.add_argument('--no_augment', action='store_true', default=False)
14
+ parser.add_argument('--patch_base', action='store_true', default=False)
15
+ parser.add_argument('--shuffle', action='store_true', default=False)
16
+ parser.add_argument('--shuffle_times', type=int, default=1)
17
+ parser.add_argument('--original_times', type=int, default=1)
18
+ parser.add_argument('--patch_size', nargs='+', type=int, default=[14])
19
+ parser.add_argument('--resume_path', type=str, default=None)
20
+ parser.add_argument('--load_whole_model', action='store_true', default=False)
21
+ parser.add_argument('--scale', type=float, default=1.0)
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+ parser.add_argument('--mode', default='binary')
32
+ parser.add_argument('--arch', type=str, default='res50', help='see my_models/__init__.py')
33
+ parser.add_argument('--fix_backbone', action='store_true')
34
+
35
+ # data augmentation
36
+ parser.add_argument('--rz_interp', default='bilinear')
37
+ parser.add_argument('--blur_prob', type=float, default=0.5)
38
+ parser.add_argument('--blur_sig', default='0.0,3.0')
39
+ parser.add_argument('--jpg_prob', type=float, default=0.5)
40
+ parser.add_argument('--jpg_method', default='cv2,pil')
41
+ parser.add_argument('--jpg_qual', default='30,100')
42
+
43
+
44
+ parser.add_argument('--real_list_path', default=None, help='only used if data_mode==ours: path for the list of real images, which should contain train.pickle and val.pickle')
45
+ parser.add_argument('--fake_list_path', default=None, help='only used if data_mode==ours: path for the list of fake images, which should contain train.pickle and val.pickle')
46
+ parser.add_argument('--wang2020_data_path', default=None, help='only used if data_mode==wang2020 it should contain train and test folders')
47
+ parser.add_argument('--data_mode', default='ours', help='wang2020 or ours')
48
+ parser.add_argument('--data_label', default='train', help='label to decide whether train or validation dataset')
49
+ parser.add_argument('--weight_decay', type=float, default=0.0, help='loss weight for l2 reg')
50
+
51
+ parser.add_argument('--class_bal', action='store_true') # what is this ?
52
+ parser.add_argument('--batch_size', type=int, default=256, help='input batch size')
53
+ parser.add_argument('--loadSize', type=int, default=256, help='scale images to this size')
54
+ parser.add_argument('--cropSize', type=int, default=224, help='then crop to this size')
55
+ parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')
56
+ parser.add_argument('--name', type=str, default='experiment_name', help='name of the experiment. It decides where to store samples and models')
57
+ parser.add_argument('--num_threads', default=4, type=int, help='# threads for loading data')
58
+ parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')
59
+ parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly')
60
+ parser.add_argument('--resize_or_crop', type=str, default='scale_and_crop', help='scaling and cropping of images at load time [resize_and_crop|crop|scale_width|scale_width_and_crop|none]')
61
+ parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data augmentation')
62
+ parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal|xavier|kaiming|orthogonal]')
63
+ parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')
64
+ parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{loadSize}')
65
+ self.initialized = True
66
+ return parser
67
+
68
+ def gather_options(self):
69
+ # initialize parser with basic options
70
+ if not self.initialized:
71
+ parser = argparse.ArgumentParser(
72
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
73
+ parser = self.initialize(parser)
74
+
75
+ # get the basic options
76
+ opt, _ = parser.parse_known_args()
77
+ self.parser = parser
78
+
79
+ return parser.parse_args()
80
+
81
+ def print_options(self, opt):
82
+ message = ''
83
+ message += '----------------- Options ---------------\n'
84
+ for k, v in sorted(vars(opt).items()):
85
+ comment = ''
86
+ default = self.parser.get_default(k)
87
+ if v != default:
88
+ comment = '\t[default: %s]' % str(default)
89
+ message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment)
90
+ message += '----------------- End -------------------'
91
+ print(message)
92
+
93
+ # save to the disk
94
+ expr_dir = os.path.join(opt.checkpoints_dir, opt.name)
95
+ if not os.path.exists(expr_dir):
96
+ os.makedirs(expr_dir)
97
+ file_name = os.path.join(expr_dir, 'opt.txt')
98
+ with open(file_name, 'wt') as opt_file:
99
+ opt_file.write(message)
100
+ opt_file.write('\n')
101
+
102
+ def parse(self, print_options=True):
103
+
104
+ opt = self.gather_options()
105
+ opt.isTrain = self.isTrain # train or test
106
+
107
+ # process opt.suffix
108
+ if opt.suffix:
109
+ suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''
110
+ opt.name = opt.name + suffix
111
+
112
+ if print_options:
113
+ self.print_options(opt)
114
+
115
+ # set gpu ids
116
+ str_ids = opt.gpu_ids.split(',')
117
+ opt.gpu_ids = []
118
+ for str_id in str_ids:
119
+ id = int(str_id)
120
+ if id >= 0:
121
+ opt.gpu_ids.append(id)
122
+ if len(opt.gpu_ids) > 0:
123
+ torch.cuda.set_device(opt.gpu_ids[0])
124
+
125
+ # additional
126
+ #opt.classes = opt.classes.split(',')
127
+ opt.rz_interp = opt.rz_interp.split(',')
128
+ opt.blur_sig = [float(s) for s in opt.blur_sig.split(',')]
129
+ opt.jpg_method = opt.jpg_method.split(',')
130
+ opt.jpg_qual = [int(s) for s in opt.jpg_qual.split(',')]
131
+ if len(opt.jpg_qual) == 2:
132
+ opt.jpg_qual = list(range(opt.jpg_qual[0], opt.jpg_qual[1] + 1))
133
+ elif len(opt.jpg_qual) > 2:
134
+ raise ValueError("Shouldn't have more than 2 values for --jpg_qual.")
135
+
136
+ self.opt = opt
137
+ return self.opt
options/test_options.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base_options import BaseOptions
2
+
3
+
4
+ class TestOptions(BaseOptions):
5
+ def initialize(self, parser):
6
+ parser = BaseOptions.initialize(self, parser)
7
+ parser.add_argument('--model_path')
8
+ parser.add_argument('--no_resize', action='store_true')
9
+ parser.add_argument('--no_crop', action='store_true')
10
+ parser.add_argument('--eval', action='store_true', help='use eval mode during test time.')
11
+
12
+ self.isTrain = False
13
+ return parser
options/train_options.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base_options import BaseOptions
2
+
3
+
4
+ class TrainOptions(BaseOptions):
5
+ def initialize(self, parser):
6
+ parser = BaseOptions.initialize(self, parser)
7
+ parser.add_argument('--earlystop_epoch', type=int, default=5)
8
+ parser.add_argument('--data_aug', action='store_true', help='if specified, perform additional data augmentation (photometric, blurring, jpegging)')
9
+ parser.add_argument('--optim', type=str, default='adam', help='optim to use [sgd, adam]')
10
+ parser.add_argument('--new_optim', action='store_true', help='new optimizer instead of loading the optim state')
11
+ parser.add_argument('--loss_freq', type=int, default=400, help='frequency of showing loss on tensorboard')
12
+ parser.add_argument('--save_epoch_freq', type=int, default=1, help='frequency of saving checkpoints at the end of epochs')
13
+ parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')
14
+ parser.add_argument('--last_epoch', type=int, default=-1, help='starting epoch count for scheduler intialization')
15
+ parser.add_argument('--train_split', type=str, default='train', help='train, val, test, etc')
16
+ parser.add_argument('--val_split', type=str, default='val', help='train, val, test, etc')
17
+ parser.add_argument('--niter', type=int, default=100, help='total epoches')
18
+ parser.add_argument('--beta1', type=float, default=0.9, help='momentum term of adam')
19
+ parser.add_argument('--lr', type=float, default=0.0001, help='initial learning rate for adam')
20
+
21
+ self.isTrain = True
22
+ return parser
requirements.txt ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ annotated-types==0.7.0
3
+ anyio==4.5.2
4
+ blessed==1.20.0
5
+ brotlipy==0.7.0
6
+ captum==0.7.0
7
+ click==8.1.8
8
+ contourpy==1.1.1
9
+ cycler==0.12.1
10
+ et-xmlfile==1.1.0
11
+ exceptiongroup==1.3.0
12
+ fastapi==0.115.12
13
+ ffmpy==0.5.0
14
+ fonttools==4.43.1
15
+ fsspec==2025.3.0
16
+ ftfy==6.1.1
17
+ gpustat==1.1.1
18
+ gradio==4.44.1
19
+ gradio_client==1.3.0
20
+ h11==0.16.0
21
+ hf-xet==1.1.3
22
+ httpcore==1.0.9
23
+ httpx==0.28.1
24
+ huggingface-hub==0.32.4
25
+ imageio==2.31.5
26
+ importlib-resources==6.1.0
27
+ joblib==1.3.2
28
+ kiwisolver==1.4.5
29
+ lazy_loader==0.3
30
+ markdown-it-py==3.0.0
31
+ matplotlib==3.7.3
32
+ mdurl==0.1.2
33
+ mkl-fft==1.3.1
34
+ mkl-service==2.4.0
35
+ nvidia-ml-py==12.535.108
36
+ opencv-python==4.8.1.78
37
+ openpyxl==3.0.10
38
+ orjson==3.10.15
39
+ packaging==23.2
40
+ pandas
41
+ Pillow
42
+ protobuf==4.24.4
43
+ psutil==5.9.5
44
+ pydantic==2.10.6
45
+ pydantic_core==2.27.2
46
+ pydub==0.25.1
47
+ Pygments==2.19.1
48
+ pyparsing==3.1.1
49
+ python-multipart==0.0.20
50
+ pytorchtools==0.0.2
51
+ pytz
52
+ PyWavelets==1.4.1
53
+ PyYAML
54
+ regex==2023.10.3
55
+ requests
56
+ rich==14.0.0
57
+ ruff==0.11.13
58
+ scikit-image==0.21.0
59
+ scikit-learn==1.3.1
60
+ scipy==1.10.1
61
+ semantic-version==2.10.0
62
+ shellingham==1.5.4
63
+ six
64
+ sniffio==1.3.1
65
+ starlette==0.44.0
66
+ sympy
67
+ tensorboardX==2.6.2.2
68
+ threadpoolctl==3.2.0
69
+ tifffile==2023.7.10
70
+ timm
71
+ tomlkit==0.12.0
72
+ torch==2.1.0
73
+ torchaudio==2.1.0
74
+ torchvision==0.16.0
75
+ tqdm==4.66.1
76
+ triton==2.1.0
77
+ typer==0.16.0
78
+ typing_extensions==4.13.2
79
+ urllib3==2.2.3
80
+ utils==1.0.1
81
+ uvicorn==0.33.0
82
+ wcwidth==0.2.8
83
+ websockets==12.0
84
+ zipp==3.17.0
upload_space.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import upload_folder
2
+
3
+ upload_folder(
4
+ repo_id="XavierJiezou/face-forgery-detection", # 你的 Space 名称
5
+ folder_path="./", # 当前目录
6
+ repo_type="space",
7
+ path_in_repo=".", # 上传到 Space 的根目录
8
+ token=True # 自动从 CLI 登录中读取 token
9
+ )