Spaces:
Sleeping
Sleeping
ubuntu
commited on
Commit
•
3fdc2a4
1
Parent(s):
1905078
Initial Commit
Browse files- app.py +121 -0
- clip/bpe_simple_vocab_16e6.txt +0 -0
- clip/clip.py +237 -0
- clip/model.py +452 -0
- clip/simple_tokenizer.py +132 -0
- detect.py +90 -0
- example/fake/fake_001.jpg +0 -0
- example/fake/fake_002.jpg +0 -0
- example/fake/fake_003.jpg +0 -0
- example/fake/fake_004.jpg +0 -0
- example/real/real_001.jpg +0 -0
- example/real/real_002.jpg +0 -0
- example/real/real_003.jpg +0 -0
- example/real/real_004.jpg +0 -0
- fc_weights.pth +0 -0
- media/fake_detect_default.png +0 -0
- media/fake_detect_pie.png +0 -0
- model.py +15 -0
- requirements.txt +9 -0
app.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import shutil
|
4 |
+
import gradio as gr
|
5 |
+
from detect import detect
|
6 |
+
import pygmtools as pygm
|
7 |
+
|
8 |
+
|
9 |
+
# Define file address constant
|
10 |
+
FD_IMG_DEFAULT_PATH = "media/fake_detect_default.png"
|
11 |
+
FD_SOLUTION_PATH = "media/fake_detect_pie.png"
|
12 |
+
PRETRAINED_PATH = "fc_weights.pth"
|
13 |
+
|
14 |
+
|
15 |
+
def _handle_fd_solve(img_path: str):
|
16 |
+
# Check file upload status
|
17 |
+
if img_path is None:
|
18 |
+
raise gr.Error("Please upload file completely!")
|
19 |
+
|
20 |
+
# gzip
|
21 |
+
os.system("gzip clip/bpe_simple_vocab_16e6.txt")
|
22 |
+
|
23 |
+
# Begin solve and record the solving time
|
24 |
+
start_time = time.time()
|
25 |
+
detect(
|
26 |
+
img_path=img_path,
|
27 |
+
save_path=FD_SOLUTION_PATH,
|
28 |
+
pretrained_path=PRETRAINED_PATH
|
29 |
+
)
|
30 |
+
solved_time = time.time() - start_time
|
31 |
+
|
32 |
+
# Message
|
33 |
+
message = "Successfully detect the image, using time ({:.3f}s).".format(solved_time)
|
34 |
+
|
35 |
+
return message, FD_SOLUTION_PATH
|
36 |
+
|
37 |
+
|
38 |
+
def handle_fd_solve(img_path: str):
|
39 |
+
try:
|
40 |
+
message = _handle_fd_solve(img_path)
|
41 |
+
return message
|
42 |
+
except Exception as e:
|
43 |
+
message = str(e)
|
44 |
+
return message, FD_SOLUTION_PATH
|
45 |
+
|
46 |
+
|
47 |
+
def handle_ged_clear():
|
48 |
+
# Replace the original image with the default image
|
49 |
+
shutil.copy(
|
50 |
+
src=FD_IMG_DEFAULT_PATH,
|
51 |
+
dst=FD_SOLUTION_PATH
|
52 |
+
)
|
53 |
+
|
54 |
+
message = "successfully clear the files!"
|
55 |
+
return message, FD_SOLUTION_PATH
|
56 |
+
|
57 |
+
|
58 |
+
with gr.Blocks() as ged_page:
|
59 |
+
|
60 |
+
gr.Markdown(
|
61 |
+
'''
|
62 |
+
This space displays that how to detect the images generated by AI.
|
63 |
+
## How to use this Space?
|
64 |
+
- Upload a '.png' or '.jpg' image.
|
65 |
+
- The detection result will be shown after you click the detect button.
|
66 |
+
- Click the 'clear' button to clear all the files.
|
67 |
+
## Examples
|
68 |
+
- You can get the test examples from our [FakeDetect Dataset Repo.](https://huggingface.co/datasets/SJTU-TES/FakeDetect)
|
69 |
+
'''
|
70 |
+
)
|
71 |
+
|
72 |
+
with gr.Row(variant="panel"):
|
73 |
+
with gr.Column(scale=1):
|
74 |
+
with gr.Row():
|
75 |
+
fd_img = gr.Image(
|
76 |
+
type="filepath"
|
77 |
+
)
|
78 |
+
info = gr.Textbox(
|
79 |
+
value="",
|
80 |
+
label="Log",
|
81 |
+
scale=4,
|
82 |
+
)
|
83 |
+
with gr.Row():
|
84 |
+
with gr.Column(scale=1, min_width=100):
|
85 |
+
solve_button = gr.Button(
|
86 |
+
value="Detect",
|
87 |
+
variant="primary",
|
88 |
+
scale=1
|
89 |
+
)
|
90 |
+
with gr.Column(scale=1, min_width=100):
|
91 |
+
clear_button = gr.Button(
|
92 |
+
"Clear",
|
93 |
+
variant="secondary",
|
94 |
+
scale=1
|
95 |
+
)
|
96 |
+
with gr.Column(scale=8):
|
97 |
+
pass
|
98 |
+
with gr.Row(variant="panel"):
|
99 |
+
fd_solution = gr.Image(
|
100 |
+
value=FD_SOLUTION_PATH,
|
101 |
+
type="filepath",
|
102 |
+
label="Detection Result"
|
103 |
+
)
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
solve_button.click(
|
108 |
+
handle_fd_solve,
|
109 |
+
[fd_img],
|
110 |
+
outputs=[info, fd_solution]
|
111 |
+
)
|
112 |
+
|
113 |
+
clear_button.click(
|
114 |
+
handle_ged_clear,
|
115 |
+
inputs=None,
|
116 |
+
outputs=[info, fd_solution]
|
117 |
+
)
|
118 |
+
|
119 |
+
|
120 |
+
if __name__ == "__main__":
|
121 |
+
ged_page.launch(debug = True)
|
clip/bpe_simple_vocab_16e6.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
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
|
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()
|
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
|
detect.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
import torchvision.transforms as transforms
|
4 |
+
from PIL import Image
|
5 |
+
from io import BytesIO
|
6 |
+
from scipy.ndimage import gaussian_filter
|
7 |
+
from model import CLIPViTL14Model
|
8 |
+
import seaborn as sns
|
9 |
+
import matplotlib.pyplot as plt
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
MEAN = {
|
14 |
+
"imagenet":[0.485, 0.456, 0.406],
|
15 |
+
"clip":[0.48145466, 0.4578275, 0.40821073]
|
16 |
+
}
|
17 |
+
|
18 |
+
STD = {
|
19 |
+
"imagenet":[0.229, 0.224, 0.225],
|
20 |
+
"clip":[0.26862954, 0.26130258, 0.27577711]
|
21 |
+
}
|
22 |
+
|
23 |
+
|
24 |
+
def png2jpg(img, quality):
|
25 |
+
out = BytesIO()
|
26 |
+
img.save(out, format='jpeg', quality=quality) # ranging from 0-95, 75 is default
|
27 |
+
img = Image.open(out)
|
28 |
+
# load from memory before ByteIO closes
|
29 |
+
img = np.array(img)
|
30 |
+
out.close()
|
31 |
+
return Image.fromarray(img)
|
32 |
+
|
33 |
+
|
34 |
+
def gaussian_blur(img, sigma):
|
35 |
+
img = np.array(img)
|
36 |
+
|
37 |
+
gaussian_filter(img[:,:,0], output=img[:,:,0], sigma=sigma)
|
38 |
+
gaussian_filter(img[:,:,1], output=img[:,:,1], sigma=sigma)
|
39 |
+
gaussian_filter(img[:,:,2], output=img[:,:,2], sigma=sigma)
|
40 |
+
|
41 |
+
return Image.fromarray(img)
|
42 |
+
|
43 |
+
|
44 |
+
def plot_pie_chart(false_prob, save_path):
|
45 |
+
labels = ['Real', 'Fake']
|
46 |
+
probabilities = [1-false_prob, false_prob]
|
47 |
+
colors = ['#ADD8E6', '#FFC0CB'] # 浅蓝色和浅红色
|
48 |
+
explode = (0.1, 0) # 设置偏移量
|
49 |
+
|
50 |
+
plt.figure(figsize=(6, 6))
|
51 |
+
plt.pie(probabilities, labels=labels, colors=colors, explode=explode, autopct='%1.1f%%', startangle=90)
|
52 |
+
plt.axis('equal')
|
53 |
+
plt.savefig(save_path)
|
54 |
+
|
55 |
+
|
56 |
+
def detect(
|
57 |
+
img_path: str,
|
58 |
+
save_path: str,
|
59 |
+
pretrained_path: str=None,
|
60 |
+
stat_from: str="clip",
|
61 |
+
gaussian_sigma: int=None,
|
62 |
+
jpeg_quality: int=None,
|
63 |
+
device: str="cpu"
|
64 |
+
):
|
65 |
+
img = Image.open(img_path).convert("RGB")
|
66 |
+
if gaussian_sigma is not None:
|
67 |
+
img = gaussian_blur(img, gaussian_sigma)
|
68 |
+
if jpeg_quality is not None:
|
69 |
+
img = png2jpg(img, jpeg_quality)
|
70 |
+
|
71 |
+
# transform
|
72 |
+
transform = transforms.Compose([
|
73 |
+
transforms.Resize((224, 224)),
|
74 |
+
# transforms.CenterCrop(224),
|
75 |
+
transforms.ToTensor(),
|
76 |
+
transforms.Normalize( mean=MEAN[stat_from], std=STD[stat_from] ),
|
77 |
+
])
|
78 |
+
img = transform(img)
|
79 |
+
img: torch.Tensor
|
80 |
+
if img.ndim == 3:
|
81 |
+
img = img.unsqueeze(dim=0)
|
82 |
+
img = img.to(device=device)
|
83 |
+
model = CLIPViTL14Model()
|
84 |
+
if pretrained_path:
|
85 |
+
state_dict = torch.load(pretrained_path, map_location=device)
|
86 |
+
model.fc.load_state_dict(state_dict)
|
87 |
+
model.eval()
|
88 |
+
model.to(device=device)
|
89 |
+
probs = model(img).sigmoid().flatten().tolist()[0]
|
90 |
+
plot_pie_chart(probs, save_path)
|
example/fake/fake_001.jpg
ADDED
example/fake/fake_002.jpg
ADDED
example/fake/fake_003.jpg
ADDED
example/fake/fake_004.jpg
ADDED
example/real/real_001.jpg
ADDED
example/real/real_002.jpg
ADDED
example/real/real_003.jpg
ADDED
example/real/real_004.jpg
ADDED
fc_weights.pth
ADDED
Binary file (4.08 kB). View file
|
|
media/fake_detect_default.png
ADDED
media/fake_detect_pie.png
ADDED
model.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from clip.clip import load
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
|
5 |
+
class CLIPViTL14Model(nn.Module):
|
6 |
+
def __init__(self, num_classes=1):
|
7 |
+
super(CLIPViTL14Model, self).__init__()
|
8 |
+
self.model, self.preprocess = load("ViT-L/14", device="cpu")
|
9 |
+
self.fc = nn.Linear(768, num_classes)
|
10 |
+
|
11 |
+
def forward(self, x, return_feature=False):
|
12 |
+
features = self.model.encode_image(x)
|
13 |
+
if return_feature:
|
14 |
+
return features
|
15 |
+
return self.fc(features)
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
pygmtools
|
3 |
+
matplotlib
|
4 |
+
torch==2.0.0
|
5 |
+
torchvision==0.15.1
|
6 |
+
scikit-learn
|
7 |
+
ftfy
|
8 |
+
regex
|
9 |
+
seaborn
|