ybbwcwaps commited on
Commit
3cc4a06
1 Parent(s): 11ce3fc
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.pyc
2
+ *.tfevents
3
+ *.pth
4
+ *.h5
5
+ *.msgpack
6
+ *.bin
7
+ *.safetensors
8
+ *.pt
9
+ *.pickle
10
+ _test_epoch4_0.7943
11
+ test.ipynb
app.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from run import get_model, detect_video
3
+ from FakeVD.code_test import predict
4
+ import os
5
+ os.environ['GRADIO_TEMP_DIR'] = "../cache/"
6
+
7
+ model = get_model()
8
+ FakeVD_model = predict.get_model()
9
+
10
+ def greet(video):
11
+ print(video, type(video))
12
+ generated_pred = detect_video(video_path=video, model=model)
13
+ context_pred = predict.main(FakeVD_model, video)
14
+
15
+ generated_output = f"Fake: {generated_pred*100:.2f}%" if generated_pred > 0.5 else f"Real: {(1-generated_pred)*100:.2f}%"
16
+ context_output = f"Fake: {context_pred*100:.2f}%" if context_pred > 0.5 else f"Real: {(1-context_pred)*100:.2f}%"
17
+ print(generated_output, '\n', context_output)
18
+ return generated_output, context_output
19
+
20
+ with gr.Blocks() as demo:
21
+ gr.Markdown("# Fake Video Detector")
22
+ with gr.Tabs():
23
+ with gr.TabItem("Video Detect"):
24
+ with gr.Column():
25
+ video_input = gr.Video(height=330)
26
+ video_button = gr.Button("detect")
27
+ detect_output = gr.Textbox(label="AI detect result")
28
+ context_output = gr.Textbox(label="Context detect result")
29
+
30
+ video_button.click(greet, inputs=video_input, outputs=[detect_output, context_output])
31
+
32
+ demo.launch()
dataset_paths.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATASET_PATHS = [
2
+ dict(
3
+ real_path='/mnt/data2/group2024-lhj/t2v/data/train/true',
4
+ fake_path='/mnt/data2/group2024-lhj/t2v/data/train/fake',
5
+ data_mode='train',
6
+ key='VideoCraft2'
7
+ ),
8
+ dict(
9
+ real_path='/mnt/data2/group2024-lhj/t2v/data/test/true',
10
+ fake_path='/mnt/data2/group2024-lhj/t2v/data/test/fake',
11
+ data_mode='test',
12
+ key='VideoCraft2'
13
+ ),
14
+ ]
datasetss/__init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torch.utils
4
+ import torch.utils.data
5
+ from torch.utils.data.sampler import WeightedRandomSampler
6
+ import torch.distributed as dist
7
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
8
+
9
+ from .datasets import RealFakeDataset
10
+
11
+
12
+
13
+ def get_bal_sampler(dataset):
14
+ targets = []
15
+ for d in dataset.datasets:
16
+ targets.extend(d.targets)
17
+
18
+ ratio = np.bincount(targets)
19
+ w = 1. / torch.tensor(ratio, dtype=torch.float)
20
+ sample_weights = w[targets]
21
+ sampler = WeightedRandomSampler(weights=sample_weights,
22
+ num_samples=len(sample_weights))
23
+ return sampler
24
+
25
+
26
+ def create_train_val_dataloader(opt, clip_model, transform, k_split: float):
27
+ shuffle = not opt.serial_batches if (opt.isTrain and not opt.class_bal) else False
28
+
29
+ dataset = RealFakeDataset(opt, clip_model, transform)
30
+
31
+ # 划分训练集和验证集
32
+ dataset_size = len(dataset)
33
+ train_size = int(dataset_size * k_split)
34
+ val_size = dataset_size - train_size
35
+
36
+ train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])
37
+
38
+ train_loader = torch.utils.data.DataLoader(train_dataset,
39
+ batch_size=opt.batch_size,
40
+ shuffle=False,
41
+ num_workers=16
42
+ )
43
+ val_loader = torch.utils.data.DataLoader(val_dataset,
44
+ batch_size=opt.batch_size,
45
+ shuffle=False,
46
+ num_workers=16
47
+ )
48
+
49
+ return train_loader, val_loader
50
+
51
+
52
+ def create_test_dataloader(opt, clip_model, transform):
53
+ shuffle = not opt.serial_batches if (opt.isTrain and not opt.class_bal) else False
54
+
55
+ dataset = RealFakeDataset(opt, clip_model, transform)
56
+
57
+ sampler = get_bal_sampler(dataset) if opt.class_bal else None
58
+
59
+
60
+ data_loader = torch.utils.data.DataLoader(dataset,
61
+ batch_size=opt.batch_size,
62
+ shuffle=shuffle,
63
+ sampler=sampler,
64
+ num_workers=16
65
+ )
66
+ return data_loader
datasetss/datasets.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import torch
4
+ import torchvision.datasets as datasets
5
+ import torchvision.transforms as transforms
6
+ import torchvision.transforms.functional as TF
7
+ from torchvision.io import read_video
8
+ from torch.utils.data import Dataset
9
+ from random import random, choice, shuffle
10
+ from io import BytesIO
11
+ from PIL import Image
12
+ from PIL import ImageFile
13
+ from scipy.ndimage.filters import gaussian_filter
14
+ import pickle
15
+ import os
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
+
29
+
30
+ def recursively_read(rootdir, must_contain, exts=["mp4", "avi"]):
31
+ out = []
32
+ for r, d, f in os.walk(rootdir):
33
+ for file in f:
34
+ if (file.split('.')[1] in exts) and (must_contain in os.path.join(r, file)):
35
+ out.append(os.path.join(r, file))
36
+ return out
37
+
38
+ def get_list(path, must_contain=''):
39
+ image_list = recursively_read(path, must_contain)
40
+ return image_list
41
+
42
+
43
+ def uniform_capture_video_frames(path, num_frames=16):
44
+ capture = cv2.VideoCapture(path)
45
+ total_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
46
+ frame_interval = total_frames // num_frames
47
+
48
+ frames = []
49
+ frame_count = 0
50
+
51
+ while len(frames) < num_frames:
52
+ ret, frame = capture.read()
53
+ if not ret:
54
+ break
55
+ if frame_count % frame_interval == 0:
56
+ # 将OpenCV的BGR图像转换为RGB图像
57
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
58
+ # 将numpy数组转换为PIL图像
59
+ pil_image = Image.fromarray(frame_rgb)
60
+ frames.append(pil_image)
61
+ frame_count += 1
62
+
63
+ capture.release()
64
+ return frames
65
+
66
+
67
+ class RealFakeDataset(Dataset):
68
+ def __init__(self, opt, clip_model=None, transform=None, num_frames=16):
69
+ self.opt = opt
70
+ assert opt.data_label in ["train", "val"]
71
+ self.data_label = opt.data_label
72
+ self.num_frames = num_frames
73
+ real_list = get_list( os.path.join(opt.real_list_path) )
74
+ fake_list = get_list( os.path.join(opt.fake_list_path) )
75
+
76
+
77
+ # setting the labels for the dataset
78
+ self.labels_dict = {}
79
+ for i in real_list:
80
+ self.labels_dict[i] = 0
81
+ for i in fake_list:
82
+ self.labels_dict[i] = 1
83
+
84
+ self.total_list = real_list + fake_list
85
+ shuffle(self.total_list)
86
+
87
+ self.transform = transform
88
+
89
+
90
+ def __len__(self):
91
+ return len(self.total_list)
92
+
93
+
94
+ def __getitem__(self, idx):
95
+ img_path = self.total_list[idx]
96
+ label = self.labels_dict[img_path]
97
+ # img = Image.open(img_path).convert("RGB")
98
+ # video_frames = uniform_capture_video_frames(img_path, num_frames=32)
99
+ # self.clip_model.to(torch.device('cuda:{}'.format(self.opt.gpu_ids[0])) if self.opt.gpu_ids else torch.device('cpu'))
100
+
101
+ frames, _, _ = read_video(str(img_path), pts_unit='sec')
102
+ frames = frames[:self.num_frames]
103
+ frames = frames.permute(0, 3, 1, 2) # (T,H,W,C) -> (T,C,H,W)
104
+
105
+ if self.transform is not None:
106
+ video_frames = torch.cat([self.transform(TF.to_pil_image(frame)).unsqueeze(0) for frame in frames])
107
+
108
+ return video_frames, label
models/__init__.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .clip_models import CLIPModel
2
+ from .imagenet_models import ImagenetModel
3
+ from .transformer import FeatureTransformer
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
+ 'FeatureTransformer'
33
+ ]
34
+
35
+
36
+
37
+
38
+
39
+ def get_model(name, **kwargs):
40
+ assert name in VALID_NAMES
41
+ if name.startswith("Imagenet:"):
42
+ return ImagenetModel(name[9:])
43
+ elif name.startswith("CLIP:"):
44
+ return CLIPModel(name[5:])
45
+ elif name.startswith("FeatureTransformer"):
46
+ return FeatureTransformer(**kwargs)
47
+ else:
48
+ 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,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .clip import clip
2
+ from PIL import Image
3
+ import torch.nn as nn
4
+
5
+
6
+ CHANNELS = {
7
+ "RN50" : 1024,
8
+ "ViT-L/14" : 768
9
+ }
10
+
11
+ class CLIPModel(nn.Module):
12
+ def __init__(self, name, num_classes=1):
13
+ super(CLIPModel, self).__init__()
14
+
15
+ self.model, self.preprocess = clip.load(name, device="cpu") # self.preprocess will not be used during training, which is handled in Dataset class
16
+ self.fc = nn.Linear( CHANNELS[name], num_classes )
17
+
18
+
19
+ def forward(self, x, return_feature=False):
20
+ features = self.model.encode_image(x)
21
+ if return_feature:
22
+ return features
23
+ return self.fc(features)
24
+
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/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.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ try:
10
+ from torch.hub import load_state_dict_from_url
11
+ except ImportError:
12
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
13
+
14
+
15
+ model_urls = {
16
+ "vit_b_16": "https://download.pytorch.org/models/vit_b_16-c867db91.pth",
17
+ "vit_b_32": "https://download.pytorch.org/models/vit_b_32-d86f8d99.pth",
18
+ "vit_l_16": "https://download.pytorch.org/models/vit_l_16-852ce7e3.pth",
19
+ "vit_l_32": "https://download.pytorch.org/models/vit_l_32-c7638314.pth",
20
+ }
21
+
22
+
23
+ class MLPBlock(nn.Sequential):
24
+ """Transformer MLP block."""
25
+
26
+ def __init__(self, in_dim: int, mlp_dim: int, dropout: float):
27
+ super().__init__()
28
+ self.linear_1 = nn.Linear(in_dim, mlp_dim)
29
+ self.act = nn.GELU()
30
+ self.dropout_1 = nn.Dropout(dropout)
31
+ self.linear_2 = nn.Linear(mlp_dim, in_dim)
32
+ self.dropout_2 = nn.Dropout(dropout)
33
+
34
+ nn.init.xavier_uniform_(self.linear_1.weight)
35
+ nn.init.xavier_uniform_(self.linear_2.weight)
36
+ nn.init.normal_(self.linear_1.bias, std=1e-6)
37
+ nn.init.normal_(self.linear_2.bias, std=1e-6)
38
+
39
+
40
+ class EncoderBlock(nn.Module):
41
+ """Transformer encoder block."""
42
+
43
+ def __init__(
44
+ self,
45
+ num_heads: int,
46
+ hidden_dim: int,
47
+ mlp_dim: int,
48
+ dropout: float,
49
+ attention_dropout: float,
50
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
51
+ ):
52
+ super().__init__()
53
+ self.num_heads = num_heads
54
+
55
+ # Attention block
56
+ self.ln_1 = norm_layer(hidden_dim)
57
+ self.self_attention = nn.MultiheadAttention(hidden_dim, num_heads, dropout=attention_dropout, batch_first=True)
58
+ self.dropout = nn.Dropout(dropout)
59
+
60
+ # MLP block
61
+ self.ln_2 = norm_layer(hidden_dim)
62
+ self.mlp = MLPBlock(hidden_dim, mlp_dim, dropout)
63
+
64
+ def forward(self, input: torch.Tensor):
65
+ torch._assert(input.dim() == 3, f"Expected (seq_length, batch_size, hidden_dim) got {input.shape}")
66
+ x = self.ln_1(input)
67
+ x, _ = self.self_attention(query=x, key=x, value=x, need_weights=False)
68
+ x = self.dropout(x)
69
+ x = x + input
70
+
71
+ y = self.ln_2(x)
72
+ y = self.mlp(y)
73
+ return x + y
74
+
75
+
76
+ class Encoder(nn.Module):
77
+ """Transformer Model Encoder for sequence to sequence translation."""
78
+
79
+ def __init__(
80
+ self,
81
+ seq_length: int,
82
+ num_layers: int,
83
+ num_heads: int,
84
+ hidden_dim: int,
85
+ mlp_dim: int,
86
+ dropout: float,
87
+ attention_dropout: float,
88
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
89
+ ):
90
+ super().__init__()
91
+ # Note that batch_size is on the first dim because
92
+ # we have batch_first=True in nn.MultiAttention() by default
93
+ self.pos_embedding = nn.Parameter(torch.empty(1, seq_length, hidden_dim).normal_(std=0.02)) # from BERT
94
+ self.dropout = nn.Dropout(dropout)
95
+ layers: OrderedDict[str, nn.Module] = OrderedDict()
96
+ for i in range(num_layers):
97
+ layers[f"encoder_layer_{i}"] = EncoderBlock(
98
+ num_heads,
99
+ hidden_dim,
100
+ mlp_dim,
101
+ dropout,
102
+ attention_dropout,
103
+ norm_layer,
104
+ )
105
+ self.layers = nn.Sequential(layers)
106
+ self.ln = norm_layer(hidden_dim)
107
+
108
+ def forward(self, input: torch.Tensor):
109
+ torch._assert(input.dim() == 3, f"Expected (batch_size, seq_length, hidden_dim) got {input.shape}")
110
+ input = input + self.pos_embedding
111
+ return self.ln(self.layers(self.dropout(input)))
112
+
113
+
114
+ class FeatureTransformer(nn.Module):
115
+ """
116
+ Feaure Transformer
117
+ """
118
+ def __init__(
119
+ self,
120
+ seq_length: int = 16,
121
+ num_layers: int = 2,
122
+ num_heads: int = 4,
123
+ hidden_dim: int = 768,
124
+ mlp_dim: int = 768,
125
+ dropout: float = 0.0,
126
+ attention_dropout: float = 0.0,
127
+ num_classes: int = 1,
128
+ representation_size: Optional[int] = None,
129
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
130
+ ) -> None:
131
+ super().__init__()
132
+ # _log_api_usage_once(self)
133
+ self.hidden_dim = hidden_dim
134
+ self.mlp_dim = mlp_dim
135
+ self.attention_dropout = attention_dropout
136
+ self.dropout = dropout
137
+ self.num_classes = num_classes
138
+ self.representation_size = representation_size
139
+ self.norm_layer = norm_layer
140
+
141
+ # Add a class token
142
+ self.class_token = nn.Parameter(torch.zeros(1, 1, hidden_dim))
143
+ seq_length += 1
144
+
145
+ self.encoder = Encoder(
146
+ seq_length,
147
+ num_layers,
148
+ num_heads,
149
+ hidden_dim,
150
+ mlp_dim,
151
+ dropout,
152
+ attention_dropout,
153
+ norm_layer,
154
+ )
155
+ self.seq_length = seq_length
156
+
157
+ heads_layers: OrderedDict[str, nn.Module] = OrderedDict()
158
+ if representation_size is None:
159
+ heads_layers["head"] = nn.Linear(hidden_dim, num_classes)
160
+ else:
161
+ heads_layers["pre_logits"] = nn.Linear(hidden_dim, representation_size)
162
+ heads_layers["act"] = nn.Tanh()
163
+ heads_layers["head"] = nn.Linear(representation_size, num_classes)
164
+
165
+ self.heads = nn.Sequential(heads_layers)
166
+
167
+ if hasattr(self.heads, "pre_logits") and isinstance(self.heads.pre_logits, nn.Linear):
168
+ fan_in = self.heads.pre_logits.in_features
169
+ nn.init.trunc_normal_(self.heads.pre_logits.weight, std=math.sqrt(1 / fan_in))
170
+ nn.init.zeros_(self.heads.pre_logits.bias)
171
+
172
+ if isinstance(self.heads.head, nn.Linear):
173
+ nn.init.zeros_(self.heads.head.weight)
174
+ nn.init.zeros_(self.heads.head.bias)
175
+
176
+ def forward(self, x: torch.Tensor):
177
+ # Expand the class token to the full batch
178
+ batch_class_token = self.class_token.expand(x.shape[0], -1, -1)
179
+ x = torch.cat([batch_class_token, x], dim=1)
180
+
181
+ x = self.encoder(x)
182
+
183
+ # Classifier "token" as used by standard language architectures
184
+ x = x[:, 0]
185
+ x = self.heads(x)
186
+
187
+ return x
models/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/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}")
networks/__init__.py ADDED
File without changes
networks/base_model.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if opt.gpu_ids:
16
+ self.device= torch.device('cuda:{}'.format(opt.gpu_ids[0]))
17
+ else:
18
+ print("gpu is not available! ")
19
+ # exit()
20
+ self.device = torch.device('cpu')
21
+ # self.device = torch.device('cuda')
22
+
23
+ def save_networks(self, save_filename):
24
+ save_path = os.path.join(self.save_dir, save_filename)
25
+
26
+ # serialize model and optimizer to dict
27
+ state_dict = {
28
+ 'model': self.model.state_dict(),
29
+ 'optimizer' : self.optimizer.state_dict(),
30
+ 'total_steps' : self.total_steps,
31
+ }
32
+
33
+ torch.save(state_dict, save_path)
34
+
35
+
36
+ def eval(self):
37
+ self.model.eval()
38
+
39
+ def test(self):
40
+ with torch.no_grad():
41
+ self.forward()
networks/trainer.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import torch
3
+ import torch.nn as nn
4
+ from networks.base_model import BaseModel
5
+ import sys
6
+ from models import get_model
7
+
8
+
9
+ class Trainer(BaseModel):
10
+ def name(self):
11
+ return 'Trainer'
12
+
13
+ def __init__(self, opt):
14
+ super(Trainer, self).__init__(opt)
15
+ self.opt = opt
16
+ self.model = get_model("FeatureTransformer")
17
+ self.clip_model = get_model("CLIP:ViT-L/14")
18
+ # torch.nn.init.normal_(self.model.fc.weight.data, 0.0, opt.init_gain)
19
+
20
+ # if opt.fix_backbone:
21
+ params = []
22
+ for name, p in self.clip_model.named_parameters():
23
+ if name=="fc.weight" or name=="fc.bias":
24
+ params.append(p)
25
+ else:
26
+ p.requires_grad = False
27
+ del params
28
+ # else:
29
+ # 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")
30
+ # import time
31
+ # time.sleep(3)
32
+ # params = self.clip_model.parameters()
33
+
34
+
35
+
36
+ if opt.optim == 'adam':
37
+ self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=opt.weight_decay)
38
+ elif opt.optim == 'sgd':
39
+ self.optimizer = torch.optim.SGD(self.model.parameters(), lr=opt.lr, momentum=0.0, weight_decay=opt.weight_decay)
40
+ else:
41
+ raise ValueError("optim should be [adam, sgd]")
42
+
43
+ self.loss_fn = nn.BCEWithLogitsLoss()
44
+
45
+ self.model.to(self.device)
46
+
47
+
48
+ def adjust_learning_rate(self, min_lr=1e-6):
49
+ for param_group in self.optimizer.param_groups:
50
+ param_group['lr'] /= 10.
51
+ if param_group['lr'] < min_lr:
52
+ return False
53
+ return True
54
+
55
+
56
+ def set_input(self, input):
57
+ # self.input = torch.cat([self.clip_model.forward(x=video_frames, return_feature=True).unsqueeze(0) for video_frames in input[0]])
58
+ self.clip_model.to(self.device)
59
+ self.input = self.clip_model.forward(x=input[0].to(self.device).view(-1, 3, 224, 224), return_feature=True).view(-1, input[0].shape[1], 768)
60
+ self.clip_model.to('cpu')
61
+ self.input = self.input.to(self.device)
62
+ self.label = input[1].to(self.device).float()
63
+
64
+
65
+ def forward(self):
66
+ self.output = self.model(self.input)
67
+ self.output = self.output.view(-1).unsqueeze(1)
68
+
69
+
70
+ def get_loss(self):
71
+ return self.loss_fn(self.output.squeeze(1), self.label)
72
+
73
+ def optimize_parameters(self):
74
+ self.forward()
75
+ self.loss = self.loss_fn(self.output.squeeze(1), self.label)
76
+ self.optimizer.zero_grad()
77
+ self.loss.backward()
78
+ self.optimizer.step()
networks/validator.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from typing import Mapping
3
+ import torch
4
+ import torch.nn as nn
5
+ from networks.base_model import BaseModel
6
+ import sys
7
+ from models import get_model
8
+
9
+
10
+ class Validator(BaseModel):
11
+ def name(self):
12
+ return 'Validator'
13
+
14
+ def __init__(self, opt):
15
+ super(Validator, self).__init__(opt)
16
+ self.opt = opt
17
+ self.model = get_model("FeatureTransformer")
18
+ self.clip_model = get_model("CLIP:ViT-L/14")
19
+
20
+ # for name, p in self.clip_model.named_parameters():
21
+ # if name=="fc.weight" or name=="fc.bias":
22
+ # params.append(p)
23
+ # else:
24
+ # p.requires_grad = False
25
+ # del params
26
+
27
+ self.model.to(self.device)
28
+
29
+
30
+ def set_input(self, input):
31
+ # self.input = torch.cat([self.clip_model.forward(x=video_frames, return_feature=True).unsqueeze(0) for video_frames in input[0]])
32
+ self.clip_model.to(self.device)
33
+ self.input = self.clip_model.forward(x=input[0].to(self.device).view(-1, 3, 224, 224), return_feature=True).view(-1, 16, 768)
34
+ self.clip_model.to('cpu')
35
+ self.input = self.input.to(self.device)
36
+ self.label = input[1].to(self.device).float()
37
+
38
+
39
+ def forward(self):
40
+ self.output = self.model(self.input)
41
+ self.output = self.output.view(-1).unsqueeze(1)
42
+
43
+ def load_state_dict(self, ckpt_path):
44
+ state_dict = torch.load(ckpt_path, map_location='cpu')
45
+ self.model.load_state_dict(state_dict['model'])
46
+ self.model.eval()
options/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .train_options import TrainOptions
2
+ from .test_options import TestOptions
options/base_options.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ # import util
4
+ import torch
5
+
6
+
7
+ class BaseOptions():
8
+ def __init__(self):
9
+ self.initialized = False
10
+
11
+ def initialize(self, parser):
12
+ parser.add_argument('--mode', default='binary')
13
+
14
+ # data augmentation
15
+ parser.add_argument('--rz_interp', default='bilinear')
16
+ parser.add_argument('--blur_prob', type=float, default=0.5)
17
+ parser.add_argument('--blur_sig', default='0.0,3.0')
18
+ parser.add_argument('--jpg_prob', type=float, default=0.5)
19
+ parser.add_argument('--jpg_method', default='cv2,pil')
20
+ parser.add_argument('--jpg_qual', default='30,100')
21
+
22
+
23
+ parser.add_argument('--data_label', default='train', help='label to decide whether train or validation dataset')
24
+ parser.add_argument('--weight_decay', type=float, default=0.0, help='loss weight for l2 reg')
25
+
26
+ parser.add_argument('--class_bal', action='store_true') # what is this ?
27
+ parser.add_argument('--batch_size', type=int, default=16, help='input batch size')
28
+
29
+ parser.add_argument('--loadSize', type=int, default=256, help='scale images to this size')
30
+ parser.add_argument('--cropSize', type=int, default=224, help='then crop to this size')
31
+ parser.add_argument('--gpu_ids', type=str, default='-1', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')
32
+
33
+ parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')
34
+ parser.add_argument('--name', type=str, default='experiment', help='name of the experiment. It decides where to store samples and models')
35
+
36
+ parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly')
37
+ 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]')
38
+ parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data augmentation')
39
+ parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal|xavier|kaiming|orthogonal]')
40
+ parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')
41
+ parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{loadSize}')
42
+ self.initialized = True
43
+ return parser
44
+
45
+ def gather_options(self):
46
+ # initialize parser with basic options
47
+ if not self.initialized:
48
+ parser = argparse.ArgumentParser(
49
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
50
+ parser = self.initialize(parser)
51
+
52
+ # get the basic options
53
+ opt, _ = parser.parse_known_args()
54
+ self.parser = parser
55
+
56
+ return parser.parse_args()
57
+
58
+ def print_options(self, opt):
59
+ message = ''
60
+ message += '----------------- Options ---------------\n'
61
+ for k, v in sorted(vars(opt).items()):
62
+ comment = ''
63
+ default = self.parser.get_default(k)
64
+ if v != default:
65
+ comment = '\t[default: %s]' % str(default)
66
+ message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment)
67
+ message += '----------------- End -------------------'
68
+ print(message)
69
+
70
+ # save to the disk
71
+ expr_dir = os.path.join(opt.checkpoints_dir, opt.name)
72
+ # util.mkdirs(expr_dir)
73
+ os.makedirs(expr_dir, exist_ok=True)
74
+ file_name = os.path.join(expr_dir, 'opt.txt')
75
+ with open(file_name, 'wt') as opt_file:
76
+ opt_file.write(message)
77
+ opt_file.write('\n')
78
+
79
+ def parse(self, print_options=True):
80
+
81
+ opt = self.gather_options()
82
+ opt.isTrain = self.isTrain # train or test
83
+
84
+ # process opt.suffix
85
+ if opt.suffix:
86
+ suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''
87
+ opt.name = opt.name + suffix
88
+
89
+ if print_options:
90
+ self.print_options(opt)
91
+
92
+ # set gpu ids
93
+ str_ids = opt.gpu_ids.split(',')
94
+ opt.gpu_ids = []
95
+ for str_id in str_ids:
96
+ id = int(str_id)
97
+ if id >= 0:
98
+ opt.gpu_ids.append(id)
99
+ if len(opt.gpu_ids) > 0:
100
+ torch.cuda.set_device(opt.gpu_ids[0])
101
+
102
+ # additional
103
+ #opt.classes = opt.classes.split(',')
104
+ opt.rz_interp = opt.rz_interp.split(',')
105
+ opt.blur_sig = [float(s) for s in opt.blur_sig.split(',')]
106
+ opt.jpg_method = opt.jpg_method.split(',')
107
+ opt.jpg_qual = [int(s) for s in opt.jpg_qual.split(',')]
108
+ if len(opt.jpg_qual) == 2:
109
+ opt.jpg_qual = list(range(opt.jpg_qual[0], opt.jpg_qual[1] + 1))
110
+ elif len(opt.jpg_qual) > 2:
111
+ raise ValueError("Shouldn't have more than 2 values for --jpg_qual.")
112
+
113
+ self.opt = opt
114
+ return self.opt
options/test_options.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ parser.add_argument('--real_list_path', default='/mnt/data2/group2024-lhj/t2v/data/test/true', help='path for the list of real video,')
13
+ parser.add_argument('--fake_list_path', default='/mnt/data2/group2024-lhj/t2v/data/test/fake', help='path for the list of fake video,')
14
+
15
+ parser.add_argument('--ckpt', type=str, default='./checkpoints/best_network.pth')
16
+ parser.add_argument('--output', type=str, default='./checkpoints/test')
17
+
18
+ self.isTrain = False
19
+ return parser
options/train_options.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ parser.add_argument('--real_list_path', default='/mnt/data2/group2024-lhj/t2v/data/train/true', help='path for the list of real video')
22
+ parser.add_argument('--fake_list_path', default='/mnt/data2/group2024-lhj/t2v/data/train/fake', help='path for the list of fake video')
23
+
24
+ self.isTrain = True
25
+ return parser
requirements.txt ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ftfy==6.2.0
2
+ gradio==4.32.2
3
+ numpy==1.23.5
4
+ opencv_python==4.8.0.76
5
+ Pillow==10.3.0
6
+ regex==2023.10.3
7
+ scikit_learn==1.3.2
8
+ scipy==1.13.1
9
+ setuptools==65.5.0
10
+ tensorboardX==2.6.2.2
11
+ termcolor==2.4.0
12
+ torch==2.1.0
13
+ torchinfo==1.8.0
14
+ torchvision==0.16.0
15
+ tqdm==4.66.1
16
+ PyAV==12.0.5
17
+
18
+ transformers==4.18.0
19
+ ipykernel==6.13.0
20
+ ipython==8.3.0
21
+ jieba==0.42.1
22
+ huggingface-hub==0.5.1
23
+ librosa==0.10.1
24
+ pandas==1.4.2
25
+ python3-openid==3.2.0
26
+ pytorch-lightning==1.6.2
27
+ pytorch-ranger==0.1.1
28
+ tensorboard-plugin-wit==1.8.1
29
+ torch-optimizer==0.3.0
30
+ torch-stoi==0.1.2
31
+ torchmetrics==0.8.1
32
+ timm==0.5.4
33
+ einops==0.8.0
34
+ h5py==3.11.0
35
+ moviepy==1.0.3
36
+ scikit-image==0.23.2
37
+ modelscope
38
+ modelscope[audio]
run.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torchvision.transforms as transforms
4
+ import torchvision.transforms.functional as TF
5
+ from torchvision.io import read_video
6
+ import torch.utils.data
7
+ import numpy as np
8
+ from sklearn.metrics import average_precision_score, precision_recall_curve, accuracy_score
9
+ import pickle
10
+ from tqdm import tqdm
11
+ from datetime import datetime
12
+ from copy import deepcopy
13
+ from dataset_paths import DATASET_PATHS
14
+ import random
15
+
16
+ from datasetss import create_test_dataloader
17
+ from utilss.logger import create_logger
18
+ import options
19
+ from networks.validator import Validator
20
+
21
+
22
+ def get_model():
23
+ val_opt = options.TestOptions().parse(print_options=False)
24
+ output_dir=os.path.join(val_opt.output, val_opt.name)
25
+ os.makedirs(output_dir, exist_ok=True)
26
+
27
+ # logger = create_logger(output_dir=output_dir, name="FakeVideoDetector")
28
+ print(f"working...")
29
+
30
+ model = Validator(val_opt)
31
+ model.load_state_dict(val_opt.ckpt)
32
+ print("ckpt loaded!")
33
+ return model
34
+
35
+
36
+ def detect_video(video_path, model):
37
+ frames, _, _ = read_video(str(video_path), pts_unit='sec')
38
+ frames = frames[:16]
39
+ frames = frames.permute(0, 3, 1, 2) # (T,H,W,C) -> (T,C,H,W)
40
+
41
+ video_frames = torch.cat([model.clip_model.preprocess(TF.to_pil_image(frame)).unsqueeze(0) for frame in frames])
42
+
43
+ with torch.no_grad():
44
+ model.set_input([torch.as_tensor(video_frames), torch.tensor([0])])
45
+
46
+ pred = model.model(model.input).view(-1).unsqueeze(1).sigmoid()
47
+
48
+ return pred[0].item()
49
+
50
+
51
+ if __name__ == '__main__':
52
+ video_path = '../../dataset/MSRVTT/videos/all/video1.mp4'
53
+ # val_opt = options.TestOptions().parse()
54
+
55
+ # output_dir=os.path.join(val_opt.output, val_opt.name)
56
+ # os.makedirs(output_dir, exist_ok=True)
57
+ # # logger = create_logger(output_dir=output_dir, name="FakeVideoDetector")
58
+ # print(f"working...")
59
+
60
+ # model = Validator(val_opt)
61
+ # model.load_state_dict(val_opt.ckpt)
62
+ # print("ckpt loaded!")
63
+
64
+ # # val_loader = create_test_dataloader(val_opt, clip_model = None, transform = model.clip_model.preprocess)
65
+ # frames, _, _ = read_video(str(video_path), pts_unit='sec')
66
+ # frames = frames[:16]
67
+ # frames = frames.permute(0, 3, 1, 2) # (T,H,W,C) -> (T,C,H,W)
68
+
69
+
70
+ # video_frames = torch.cat([model.clip_model.preprocess(TF.to_pil_image(frame)).unsqueeze(0) for frame in frames])
71
+
72
+ # with torch.no_grad():
73
+ # model.set_input([torch.as_tensor(video_frames), torch.tensor([0])])
74
+
75
+ # pred = model.model(model.input).view(-1).unsqueeze(1).sigmoid()
76
+
77
+ model = get_model()
78
+
79
+ pred = detect_video(video_path, model)
80
+ if pred > 0.5:
81
+ print(f"Fake: {pred*100:.2f}%")
82
+ else:
83
+ print(f"Real: {(1-pred)*100:.2f}%")
train.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ from datetime import datetime
4
+ from tqdm import tqdm
5
+ from tensorboardX import SummaryWriter
6
+ import torch
7
+ import torchinfo
8
+ import numpy as np
9
+
10
+ import options
11
+ from validate import validate, calculate_acc
12
+ from datasetss import *
13
+ from utilss.logger import create_logger
14
+ from utilss.earlystop import EarlyStopping
15
+ from networks.trainer import Trainer
16
+
17
+
18
+
19
+ if __name__ == '__main__':
20
+ train_opt = options.TrainOptions().parse()
21
+ # val_opt = options.TestOptions().parse()
22
+
23
+ # logger
24
+ logger = create_logger(output_dir=train_opt.checkpoints_dir, name="FeatureTransformer")
25
+ logger.info(f"working dir: {train_opt.checkpoints_dir}")
26
+
27
+
28
+ model = Trainer(train_opt)
29
+ # logger.info(opt.gpu_ids[0])
30
+ logger.info(model.device)
31
+
32
+ # extract_feature_model = model.extract_feature_model
33
+ train_loader, val_loader = create_train_val_dataloader(train_opt, clip_model = None, transform = model.clip_model.preprocess, k_split=0.8)
34
+ logger.info(f"train {len(train_loader)}")
35
+ logger.info(f"validate {len(val_loader)}")
36
+
37
+
38
+ train_writer = SummaryWriter(os.path.join(train_opt.checkpoints_dir, train_opt.name, "train"))
39
+ val_writer = SummaryWriter(os.path.join(train_opt.checkpoints_dir, train_opt.name, "val"))
40
+
41
+ early_stopping = EarlyStopping(save_path=train_opt.checkpoints_dir, patience=train_opt.earlystop_epoch, delta=-0.001, verbose=True)
42
+
43
+ start_time = time.time()
44
+ logger.info(torchinfo.summary(model.model, input_size=(train_opt.batch_size, 16, 768), col_width=20,
45
+ col_names=['input_size', 'output_size', 'num_params', 'trainable'], row_settings=['var_names'], verbose=0))
46
+
47
+
48
+ logger.info("Length of train loader: %d" %(len(train_loader)))
49
+ for epoch in range(train_opt.niter):
50
+ y_true, y_pred = [], []
51
+ pbar = tqdm(train_loader)
52
+ for i, data in enumerate(pbar):
53
+ pbar.set_description(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
54
+
55
+ model.total_steps += 1
56
+
57
+ model.set_input(data)
58
+ model.optimize_parameters()
59
+
60
+ y_pred.extend(model.output.sigmoid().flatten().tolist())
61
+ y_true.extend(data[1].flatten().tolist())
62
+
63
+ if model.total_steps % train_opt.loss_freq == 0:
64
+ logger.info("Train loss: {} at step: {}".format(model.loss, model.total_steps))
65
+ train_writer.add_scalar('loss', model.loss, model.total_steps)
66
+ logger.info("Iter time: {}".format((time.time()-start_time)/model.total_steps) )
67
+
68
+ if model.total_steps in [10,30,50,100,1000,5000,10000] and False: # save models at these iters
69
+ model.save_networks('model_iters_%s.pth' % model.total_steps)
70
+ # logger.info("trained one batch")
71
+ pbar.set_postfix_str(f"loss: {model.loss}, ")
72
+ r_acc0, f_acc0, acc0 = calculate_acc(np.array(y_true), np.array(y_pred), 0.5)
73
+ logger.info(f"TrainSet r_acc: {r_acc0}, f_acc: {f_acc0}, acc: {acc0}")
74
+
75
+ if epoch % train_opt.save_epoch_freq == 0:
76
+ logger.info('saving the model at the end of epoch %d' % (epoch))
77
+ model.save_networks( 'model_epoch_%s.pth' % epoch )
78
+
79
+ # Validation
80
+ model.eval()
81
+ ap, r_acc, f_acc, acc = validate(model, val_loader, logger=logger)
82
+ val_writer.add_scalar('accuracy', acc, model.total_steps)
83
+ val_writer.add_scalar('ap', ap, model.total_steps)
84
+ logger.info("(Val @ epoch {}) acc: {}; ap: {}".format(epoch, acc, ap))
85
+
86
+ early_stopping(acc, model.model)
87
+ if early_stopping.early_stop:
88
+ cont_train = model.adjust_learning_rate()
89
+ if cont_train:
90
+ logger.info("Learning rate dropped by 10, continue training...")
91
+ early_stopping = EarlyStopping(save_path=train_opt.checkpoints_dir, patience=train_opt.earlystop_epoch, delta=-0.002, verbose=True)
92
+ else:
93
+ logger.info("Early stopping.")
94
+ break
95
+
96
+ model.train()
97
+
utilss/earlystop.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import os
4
+
5
+ class EarlyStopping:
6
+ """Early stops the training if validation loss doesn't improve after a given patience."""
7
+ def __init__(self, save_path, patience=7, verbose=False, delta=0):
8
+ """
9
+ Args:
10
+ save_path : 模型保存文件夹
11
+ patience (int): How long to wait after last time validation loss improved.
12
+ Default: 7
13
+ verbose (bool): If True, prints a message for each validation loss improvement.
14
+ Default: False
15
+ delta (float): Minimum change in the monitored quantity to qualify as an improvement.
16
+ Default: 0
17
+ """
18
+ self.save_path = save_path
19
+ self.patience = patience
20
+ self.verbose = verbose
21
+ self.counter = 0
22
+ self.best_score = None
23
+ self.early_stop = False
24
+ self.val_loss_min = np.Inf
25
+ self.delta = delta
26
+
27
+ def __call__(self, val_loss, model):
28
+
29
+ score = -val_loss
30
+
31
+ if self.best_score is None:
32
+ self.best_score = score
33
+ self.save_checkpoint(val_loss, model)
34
+ elif score < self.best_score + self.delta:
35
+ self.counter += 1
36
+ print(f'EarlyStopping counter: {self.counter} out of {self.patience}')
37
+ if self.counter >= self.patience:
38
+ self.early_stop = True
39
+ else:
40
+ self.best_score = score
41
+ self.save_checkpoint(val_loss, model)
42
+ self.counter = 0
43
+
44
+ def save_checkpoint(self, val_loss, model):
45
+ '''Saves model when validation loss decrease.'''
46
+ if self.verbose:
47
+ print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ... best_network.pth ...')
48
+ path = os.path.join(self.save_path, 'best_network.pth')
49
+ # torch.save(model.state_dict(), path) # 这里会存储迄今最优模型的参数
50
+ self.save_networks(path, model)
51
+ self.val_loss_min = val_loss
52
+
53
+ def save_networks(self, save_path, model):
54
+
55
+ # serialize model and optimizer to dict
56
+ state_dict = {
57
+ 'model': model.state_dict(),
58
+ }
59
+
60
+ torch.save(state_dict, save_path)
utilss/logger.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import logging
4
+ import functools
5
+ from termcolor import colored
6
+
7
+
8
+ @functools.lru_cache()
9
+ def create_logger(output_dir, dist_rank=0, name=''):
10
+ # create logger
11
+ logger = logging.getLogger(name)
12
+ logger.setLevel(logging.DEBUG)
13
+ logger.propagate = False
14
+
15
+ # create formatter
16
+ fmt = '[%(asctime)s %(name)s] (%(filename)s %(lineno)d): %(levelname)s %(message)s'
17
+ color_fmt = colored('[%(asctime)s %(name)s]', 'green') + \
18
+ colored('(%(filename)s %(lineno)d)', 'yellow') + ': %(levelname)s %(message)s'
19
+
20
+ # create console handlers for master process
21
+ if dist_rank == 0:
22
+ console_handler = logging.StreamHandler(sys.stdout)
23
+ console_handler.setLevel(logging.DEBUG)
24
+ console_handler.setFormatter(
25
+ logging.Formatter(fmt=color_fmt, datefmt='%Y-%m-%d %H:%M:%S'))
26
+ logger.addHandler(console_handler)
27
+
28
+ # create file handlers
29
+ file_handler = logging.FileHandler(os.path.join(output_dir, f'log_rank{dist_rank}.txt'), mode='a')
30
+ file_handler.setLevel(logging.DEBUG)
31
+ file_handler.setFormatter(logging.Formatter(fmt=fmt, datefmt='%Y-%m-%d %H:%M:%S'))
32
+ logger.addHandler(file_handler)
33
+
34
+ return logger
validate.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torchvision.transforms as transforms
4
+ import torch.utils.data
5
+ import numpy as np
6
+ from sklearn.metrics import average_precision_score, precision_recall_curve, accuracy_score
7
+ import pickle
8
+ from tqdm import tqdm
9
+ from datetime import datetime
10
+ from copy import deepcopy
11
+ from dataset_paths import DATASET_PATHS
12
+ import random
13
+
14
+ from datasetss import create_test_dataloader
15
+ from utilss.logger import create_logger
16
+ import options
17
+ from networks.validator import Validator
18
+
19
+
20
+ SEED = 0
21
+ def set_seed():
22
+ torch.manual_seed(SEED)
23
+ torch.cuda.manual_seed(SEED)
24
+ np.random.seed(SEED)
25
+ random.seed(SEED)
26
+
27
+
28
+ MEAN = {
29
+ "imagenet":[0.485, 0.456, 0.406],
30
+ "clip":[0.48145466, 0.4578275, 0.40821073]
31
+ }
32
+
33
+ STD = {
34
+ "imagenet":[0.229, 0.224, 0.225],
35
+ "clip":[0.26862954, 0.26130258, 0.27577711]
36
+ }
37
+
38
+
39
+
40
+ def find_best_threshold(y_true, y_pred):
41
+ "We assume first half is real 0, and the second half is fake 1"
42
+
43
+ N = y_true.shape[0]
44
+
45
+ if y_pred[0:N//2].max() <= y_pred[N//2:N].min(): # perfectly separable case
46
+ return (y_pred[0:N//2].max() + y_pred[N//2:N].min()) / 2
47
+
48
+ best_acc = 0
49
+ best_thres = 0
50
+ for thres in y_pred:
51
+ temp = deepcopy(y_pred)
52
+ temp[temp>=thres] = 1
53
+ temp[temp<thres] = 0
54
+
55
+ acc = (temp == y_true).sum() / N
56
+ if acc >= best_acc:
57
+ best_thres = thres
58
+ best_acc = acc
59
+
60
+ return best_thres
61
+
62
+
63
+ def calculate_acc(y_true, y_pred, thres):
64
+ r_acc = accuracy_score(y_true[y_true==0], y_pred[y_true==0] > thres)
65
+ f_acc = accuracy_score(y_true[y_true==1], y_pred[y_true==1] > thres)
66
+ acc = accuracy_score(y_true, y_pred > thres)
67
+ return r_acc, f_acc, acc
68
+
69
+
70
+ def validate(model, loader, logger, find_thres=False):
71
+
72
+ with torch.no_grad():
73
+ y_true, y_pred = [], []
74
+ logger.info ("Length of dataset: %d" %(len(loader)))
75
+ pbar = tqdm(loader)
76
+ for data in pbar:
77
+ pbar.set_description(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
78
+ model.set_input(data)
79
+
80
+ y_pred.extend(model.model(model.input).view(-1).unsqueeze(1).sigmoid().flatten().tolist())
81
+ y_true.extend(data[1].flatten().tolist())
82
+
83
+ y_true, y_pred = np.array(y_true), np.array(y_pred)
84
+
85
+ # ================== save this if you want to plot the curves =========== #
86
+ # torch.save( torch.stack( [torch.tensor(y_true), torch.tensor(y_pred)] ), 'baseline_predication_for_pr_roc_curve.pth' )
87
+ # exit()
88
+ # =================================================================== #
89
+ # print(y_pred, '\n', y_true)
90
+ # Get AP
91
+ ap = average_precision_score(y_true, y_pred)
92
+
93
+ # Acc based on 0.5
94
+ r_acc0, f_acc0, acc0 = calculate_acc(y_true, y_pred, 0.5)
95
+ if not find_thres:
96
+ return ap, r_acc0, f_acc0, acc0
97
+
98
+
99
+ # Acc based on the best thres
100
+ best_thres = find_best_threshold(y_true, y_pred)
101
+ r_acc1, f_acc1, acc1 = calculate_acc(y_true, y_pred, best_thres)
102
+
103
+ return ap, r_acc0, f_acc0, acc0, r_acc1, f_acc1, acc1, best_thres
104
+
105
+
106
+
107
+ # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #
108
+
109
+ def recursively_read(rootdir, must_contain, exts=["png", "jpg", "JPEG", "jpeg", "bmp"]):
110
+ out = []
111
+ for r, d, f in os.walk(rootdir):
112
+ for file in f:
113
+ if (file.split('.')[1] in exts) and (must_contain in os.path.join(r, file)):
114
+ out.append(os.path.join(r, file))
115
+ return out
116
+
117
+
118
+ def get_list(path, must_contain=''):
119
+ if ".pickle" in path:
120
+ with open(path, 'rb') as f:
121
+ image_list = pickle.load(f)
122
+ image_list = [ item for item in image_list if must_contain in item ]
123
+ else:
124
+ image_list = recursively_read(path, must_contain)
125
+ return image_list
126
+
127
+
128
+
129
+ if __name__ == '__main__':
130
+ val_opt = options.TestOptions().parse()
131
+
132
+ output_dir=os.path.join(val_opt.output, val_opt.name)
133
+ os.makedirs(output_dir, exist_ok=True)
134
+ logger = create_logger(output_dir=output_dir, name="FakeVideoDetector")
135
+ logger.info(f"working dir: {output_dir}")
136
+
137
+ model = Validator(val_opt)
138
+ model.load_state_dict(val_opt.ckpt)
139
+ logger.info("ckpt loaded!")
140
+
141
+ val_loader = create_test_dataloader(val_opt, clip_model = None, transform = model.clip_model.preprocess)
142
+
143
+
144
+ ap, r_acc0, f_acc0, acc0, r_acc1, f_acc1, acc1, best_thres = validate(model, val_loader, logger, find_thres=True, )
145
+
146
+ print(f"ap: {ap}, r_acc0: {r_acc0}, f_acc0: {f_acc0}, acc0:{acc0}, r_acc1: {r_acc1}, f_acc1: {f_acc1}, acc1: {acc1}, best_thres: {best_thres} ")
147
+
148
+ with open( os.path.join(val_opt.name,'ap.txt'), 'a') as f:
149
+ f.write(str(round(ap*100, 2))+'\n' )
150
+
151
+ with open( os.path.join(val_opt.name,'acc0.txt'), 'a') as f:
152
+ f.write(str(round(r_acc0*100, 2))+' '+str(round(f_acc0*100, 2))+' '+str(round(acc0*100, 2))+'\n' )
153
+