Spaces:
Sleeping
Sleeping
Ana Sanchez
commited on
Commit
·
979e31c
1
Parent(s):
e504a65
Add src
Browse files- app.py +2 -1
- src/clip/__init__ +0 -0
- src/clip/clip.py +258 -0
- src/clip/model.py +736 -0
- src/training/datasets.py +240 -0
- src/training/model_configs/RN101.json +17 -0
- src/training/model_configs/RN50-pre.json +17 -0
- src/training/model_configs/RN50.json +15 -0
- src/training/model_configs/RN50x16.json +17 -0
- src/training/model_configs/RN50x4.json +17 -0
- src/training/model_configs/ViT-B-16.json +12 -0
- src/training/model_configs/ViT-B-32.json +12 -0
app.py
CHANGED
@@ -16,7 +16,8 @@ import torch
|
|
16 |
from torch.utils.data import DataLoader
|
17 |
from torch.utils.tensorboard import SummaryWriter
|
18 |
|
19 |
-
|
|
|
20 |
from clip.clip import _transform
|
21 |
from training.datasets import CellPainting
|
22 |
from clip.model import convert_weights, CLIPGeneral
|
|
|
16 |
from torch.utils.data import DataLoader
|
17 |
from torch.utils.tensorboard import SummaryWriter
|
18 |
|
19 |
+
sys.path.insert(0, os.path.abspath("src/"))
|
20 |
+
|
21 |
from clip.clip import _transform
|
22 |
from training.datasets import CellPainting
|
23 |
from clip.model import convert_weights, CLIPGeneral
|
src/clip/__init__
ADDED
File without changes
|
src/clip/clip.py
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Code ported from https://github.com/openai/CLIP
|
2 |
+
|
3 |
+
import hashlib
|
4 |
+
import os
|
5 |
+
import urllib
|
6 |
+
import warnings
|
7 |
+
from typing import Union, List
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from PIL import Image
|
11 |
+
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize, RandomResizedCrop, InterpolationMode, RandomCrop, RandomRotation
|
12 |
+
from tqdm import tqdm
|
13 |
+
|
14 |
+
from clip.model import build_model
|
15 |
+
# from clip.tokenizer import SimpleTokenizer as _Tokenizer
|
16 |
+
|
17 |
+
__all__ = ["available_models", "load", "tokenize"]
|
18 |
+
# _tokenizer = _Tokenizer()
|
19 |
+
|
20 |
+
_MODELS = {
|
21 |
+
"RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
|
22 |
+
"RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
|
23 |
+
"RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
|
24 |
+
"ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
|
25 |
+
}
|
26 |
+
|
27 |
+
|
28 |
+
class NormalizeByImage(object):
|
29 |
+
"""Normalize an tensor image with mean and standard deviation.
|
30 |
+
Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform
|
31 |
+
will normalize each channel of the input ``torch.*Tensor`` i.e.
|
32 |
+
``input[channel] = (input[channel] - mean[channel]) / std[channel]``
|
33 |
+
Args:
|
34 |
+
mean (sequence): Sequence of means for each channel.
|
35 |
+
std (sequence): Sequence of standard deviations for each channel.
|
36 |
+
"""
|
37 |
+
|
38 |
+
def __call__(self, tensor):
|
39 |
+
"""
|
40 |
+
Args:
|
41 |
+
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
|
42 |
+
Returns:
|
43 |
+
Tensor: Normalized Tensor image.
|
44 |
+
"""
|
45 |
+
for t in tensor:
|
46 |
+
t.sub_(t.mean()).div_(t.std() + 1e-7)
|
47 |
+
return tensor
|
48 |
+
|
49 |
+
|
50 |
+
def _download(url: str, root: str = os.path.expanduser("~/.cache/clip")):
|
51 |
+
os.makedirs(root, exist_ok=True)
|
52 |
+
filename = os.path.basename(url)
|
53 |
+
|
54 |
+
expected_sha256 = url.split("/")[-2]
|
55 |
+
download_target = os.path.join(root, filename)
|
56 |
+
|
57 |
+
if os.path.exists(download_target) and not os.path.isfile(download_target):
|
58 |
+
raise RuntimeError(f"{download_target} exists and is not a regular file")
|
59 |
+
|
60 |
+
if os.path.isfile(download_target):
|
61 |
+
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
|
62 |
+
return download_target
|
63 |
+
else:
|
64 |
+
warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
|
65 |
+
|
66 |
+
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
|
67 |
+
with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop:
|
68 |
+
while True:
|
69 |
+
buffer = source.read(8192)
|
70 |
+
if not buffer:
|
71 |
+
break
|
72 |
+
|
73 |
+
output.write(buffer)
|
74 |
+
loop.update(len(buffer))
|
75 |
+
|
76 |
+
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
|
77 |
+
raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
|
78 |
+
|
79 |
+
return download_target
|
80 |
+
|
81 |
+
def _convert_to_rgb(image):
|
82 |
+
return image.convert('RGB')
|
83 |
+
|
84 |
+
def _transform(n_px_tr: int, n_px_val: int, is_train: bool, normalize:str = "dataset", preprocess:str = "downsize"):
|
85 |
+
#normalize = Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
|
86 |
+
# print(n_px_tr)
|
87 |
+
# print(n_px_val)
|
88 |
+
if normalize == "img":
|
89 |
+
normalize = NormalizeByImage()
|
90 |
+
elif normalize == "dataset":
|
91 |
+
normalize = Normalize((47.1314, 40.8138, 53.7692, 46.2656, 28.7243), (47.1314, 40.8138, 53.7692, 46.2656, 28.7243)) # normalize for CellPainting
|
92 |
+
if normalize == "None":
|
93 |
+
normalize = None
|
94 |
+
|
95 |
+
if is_train:
|
96 |
+
if preprocess == "crop":
|
97 |
+
#resize = RandomResizedCrop(n_px_tr, scale=(0.25,0.3), ratio=(0.95, 1.05), interpolation=InterpolationMode.BICUBIC)
|
98 |
+
resize = RandomCrop(n_px_tr)
|
99 |
+
elif preprocess == "downsize":
|
100 |
+
resize = RandomResizedCrop(n_px_tr, scale=(0.9, 1.0), interpolation=InterpolationMode.BICUBIC)
|
101 |
+
elif preprocess == "rotate":
|
102 |
+
resize = Compose([
|
103 |
+
RandomRotation((0, 360)),
|
104 |
+
CenterCrop(n_px_tr)
|
105 |
+
])
|
106 |
+
|
107 |
+
else:
|
108 |
+
if preprocess == "crop" or "rotate":
|
109 |
+
resize = Compose([
|
110 |
+
#RandomResizedCrop(n_px_tr, scale=(0.25,0.3), ratio=(0.95, 1.05), interpolation=InterpolationMode.BICUBIC)
|
111 |
+
CenterCrop(n_px_val),
|
112 |
+
])
|
113 |
+
elif preprocess == "downsize":
|
114 |
+
resize = Compose([
|
115 |
+
Resize(n_px_val, interpolation=InterpolationMode.BICUBIC),
|
116 |
+
CenterCrop(n_px_val),
|
117 |
+
])
|
118 |
+
if normalize:
|
119 |
+
return Compose([
|
120 |
+
ToTensor(),
|
121 |
+
resize,
|
122 |
+
normalize,
|
123 |
+
])
|
124 |
+
else:
|
125 |
+
return Compose([
|
126 |
+
ToTensor(),
|
127 |
+
resize,
|
128 |
+
])
|
129 |
+
|
130 |
+
|
131 |
+
|
132 |
+
def available_models() -> List[str]:
|
133 |
+
"""Returns the names of available CLIP models"""
|
134 |
+
return list(_MODELS.keys())
|
135 |
+
|
136 |
+
|
137 |
+
def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit=True, is_train=False, pretrained=True):
|
138 |
+
"""Load a CLIP model
|
139 |
+
Parameters
|
140 |
+
----------
|
141 |
+
name : str
|
142 |
+
A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
|
143 |
+
device : Union[str, torch.device]
|
144 |
+
The device to put the loaded model
|
145 |
+
jit : bool
|
146 |
+
Whether to load the optimized JIT model (default) or more hackable non-JIT model.
|
147 |
+
Returns
|
148 |
+
-------
|
149 |
+
model : torch.nn.Module
|
150 |
+
The CLIP model
|
151 |
+
preprocess : Callable[[PIL.Image], torch.Tensor]
|
152 |
+
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
|
153 |
+
"""
|
154 |
+
if name in _MODELS:
|
155 |
+
model_path = _download(_MODELS[name])
|
156 |
+
elif os.path.isfile(name):
|
157 |
+
model_path = name
|
158 |
+
else:
|
159 |
+
raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
|
160 |
+
|
161 |
+
try:
|
162 |
+
# loading JIT archive
|
163 |
+
model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval()
|
164 |
+
state_dict = None
|
165 |
+
except RuntimeError:
|
166 |
+
# loading saved state dict
|
167 |
+
if jit:
|
168 |
+
warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
|
169 |
+
jit = False
|
170 |
+
state_dict = torch.load(model_path, map_location="cpu")
|
171 |
+
|
172 |
+
if not jit:
|
173 |
+
try:
|
174 |
+
model = build_model(state_dict or model.state_dict()).to(device)
|
175 |
+
except KeyError:
|
176 |
+
sd = {k[7:]: v for k,v in state_dict["state_dict"].items()}
|
177 |
+
model = build_model(sd).to(device)
|
178 |
+
|
179 |
+
if str(device) == "cpu":
|
180 |
+
model.float()
|
181 |
+
return model, \
|
182 |
+
_transform(model.visual.input_resolution, is_train=True), \
|
183 |
+
_transform(model.visual.input_resolution, is_train=False)
|
184 |
+
|
185 |
+
# patch the device names
|
186 |
+
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
|
187 |
+
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
|
188 |
+
|
189 |
+
def patch_device(module):
|
190 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
191 |
+
if hasattr(module, "forward1"):
|
192 |
+
graphs.append(module.forward1.graph)
|
193 |
+
|
194 |
+
for graph in graphs:
|
195 |
+
for node in graph.findAllNodes("prim::Constant"):
|
196 |
+
if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
|
197 |
+
node.copyAttributes(device_node)
|
198 |
+
|
199 |
+
model.apply(patch_device)
|
200 |
+
patch_device(model.encode_image)
|
201 |
+
patch_device(model.encode_text)
|
202 |
+
|
203 |
+
# patch dtype to float32 on CPU
|
204 |
+
if str(device) == "cpu":
|
205 |
+
float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
|
206 |
+
float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
|
207 |
+
float_node = float_input.node()
|
208 |
+
|
209 |
+
def patch_float(module):
|
210 |
+
graphs = [module.graph] if hasattr(module, "graph") else []
|
211 |
+
if hasattr(module, "forward1"):
|
212 |
+
graphs.append(module.forward1.graph)
|
213 |
+
|
214 |
+
for graph in graphs:
|
215 |
+
for node in graph.findAllNodes("aten::to"):
|
216 |
+
inputs = list(node.inputs())
|
217 |
+
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
|
218 |
+
if inputs[i].node()["value"] == 5:
|
219 |
+
inputs[i].node().copyAttributes(float_node)
|
220 |
+
|
221 |
+
model.apply(patch_float)
|
222 |
+
patch_float(model.encode_image)
|
223 |
+
patch_float(model.encode_text)
|
224 |
+
|
225 |
+
model.float()
|
226 |
+
|
227 |
+
return model, \
|
228 |
+
_transform(model.input_resolution.item(), is_train=True), \
|
229 |
+
_transform(model.input_resolution.item(), is_train=False)
|
230 |
+
|
231 |
+
|
232 |
+
def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor:
|
233 |
+
"""
|
234 |
+
Returns the tokenized representation of given input string(s)
|
235 |
+
Parameters
|
236 |
+
----------
|
237 |
+
texts : Union[str, List[str]]
|
238 |
+
An input string or a list of input strings to tokenize
|
239 |
+
context_length : int
|
240 |
+
The context length to use; all CLIP models use 77 as the context length
|
241 |
+
Returns
|
242 |
+
-------
|
243 |
+
A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
|
244 |
+
"""
|
245 |
+
if isinstance(texts, str):
|
246 |
+
texts = [texts]
|
247 |
+
|
248 |
+
sot_token = _tokenizer.encoder["<start_of_text>"]
|
249 |
+
eot_token = _tokenizer.encoder["<end_of_text>"]
|
250 |
+
all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
|
251 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
|
252 |
+
|
253 |
+
for i, tokens in enumerate(all_tokens):
|
254 |
+
if len(tokens) > context_length: # Truncate
|
255 |
+
tokens = tokens[:context_length]
|
256 |
+
result[i, :len(tokens)] = torch.tensor(tokens)
|
257 |
+
|
258 |
+
return result
|
src/clip/model.py
ADDED
@@ -0,0 +1,736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import OrderedDict
|
2 |
+
from typing import Tuple, Union, List
|
3 |
+
|
4 |
+
import timm
|
5 |
+
import os
|
6 |
+
import json
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import torch.nn.functional as F
|
10 |
+
from torch import nn
|
11 |
+
|
12 |
+
|
13 |
+
class Bottleneck(nn.Module):
|
14 |
+
expansion = 4
|
15 |
+
|
16 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
17 |
+
super().__init__()
|
18 |
+
|
19 |
+
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
|
20 |
+
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
|
21 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
22 |
+
|
23 |
+
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
|
24 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
25 |
+
|
26 |
+
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
|
27 |
+
|
28 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
|
29 |
+
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
|
30 |
+
|
31 |
+
self.relu = nn.ReLU(inplace=True)
|
32 |
+
self.downsample = None
|
33 |
+
self.stride = stride
|
34 |
+
|
35 |
+
if stride > 1 or inplanes != planes * Bottleneck.expansion:
|
36 |
+
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
|
37 |
+
self.downsample = nn.Sequential(OrderedDict([
|
38 |
+
("-1", nn.AvgPool2d(stride)),
|
39 |
+
("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
|
40 |
+
("1", nn.BatchNorm2d(planes * self.expansion))
|
41 |
+
]))
|
42 |
+
|
43 |
+
def forward(self, x: torch.Tensor):
|
44 |
+
identity = x
|
45 |
+
|
46 |
+
out = self.relu(self.bn1(self.conv1(x)))
|
47 |
+
out = self.relu(self.bn2(self.conv2(out)))
|
48 |
+
out = self.avgpool(out)
|
49 |
+
out = self.bn3(self.conv3(out))
|
50 |
+
|
51 |
+
if self.downsample is not None:
|
52 |
+
identity = self.downsample(x)
|
53 |
+
|
54 |
+
out += identity
|
55 |
+
out = self.relu(out)
|
56 |
+
return out
|
57 |
+
|
58 |
+
|
59 |
+
class ResNet(nn.Module):
|
60 |
+
def __init__(self, block="bottleneck", layers: list = (3, 4, 23, 3), input_shape=None, output_dim=None, regression=False):
|
61 |
+
self.inplanes = 64
|
62 |
+
self.input_resolution = input_shape
|
63 |
+
|
64 |
+
super().__init__()
|
65 |
+
|
66 |
+
if block == "bottleneck":
|
67 |
+
block = Bottleneck
|
68 |
+
elif block == "basic":
|
69 |
+
block = BasicBlock
|
70 |
+
#self.n_classes = num_classes
|
71 |
+
if input_shape is not None:
|
72 |
+
channels_in = input_shape
|
73 |
+
else:
|
74 |
+
channels_in = 3
|
75 |
+
|
76 |
+
self.is_regression = regression
|
77 |
+
self.conv1 = nn.Conv2d(channels_in, 64, kernel_size=7, stride=2, padding=3, bias=False)
|
78 |
+
self.bn1 = nn.BatchNorm2d(64)
|
79 |
+
self.relu = nn.ReLU(inplace=True)
|
80 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
81 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
82 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
83 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
84 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
|
85 |
+
self.avgpool = nn.AvgPool2d(7, stride=1)
|
86 |
+
self.fc = nn.Linear(512 * block.expansion, output_dim)
|
87 |
+
|
88 |
+
for m in self.modules():
|
89 |
+
if isinstance(m, nn.Conv2d):
|
90 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
91 |
+
elif isinstance(m, nn.BatchNorm2d):
|
92 |
+
nn.init.constant_(m.weight, 1)
|
93 |
+
nn.init.constant_(m.bias, 0)
|
94 |
+
|
95 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
96 |
+
downsample = None
|
97 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
98 |
+
downsample = nn.Sequential(
|
99 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
100 |
+
kernel_size=1, stride=stride, bias=False),
|
101 |
+
nn.BatchNorm2d(planes * block.expansion),
|
102 |
+
)
|
103 |
+
|
104 |
+
layers = []
|
105 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
106 |
+
self.inplanes = planes * block.expansion
|
107 |
+
for i in range(1, blocks):
|
108 |
+
layers.append(block(self.inplanes, planes))
|
109 |
+
|
110 |
+
return nn.Sequential(*layers)
|
111 |
+
|
112 |
+
def forward(self, x):
|
113 |
+
x = self.conv1(x)
|
114 |
+
x = self.bn1(x)
|
115 |
+
x = self.relu(x)
|
116 |
+
x = self.maxpool(x)
|
117 |
+
|
118 |
+
x = self.layer1(x)
|
119 |
+
x = self.layer2(x)
|
120 |
+
x = self.layer3(x)
|
121 |
+
x = self.layer4(x)
|
122 |
+
|
123 |
+
x = self.avgpool(x)
|
124 |
+
if x.shape[-2:] != (1, 1):
|
125 |
+
x = nn.AvgPool2d(x.shape[2:])(x)
|
126 |
+
x = x.view(x.size(0), -1)
|
127 |
+
x = self.fc(x)
|
128 |
+
|
129 |
+
return x
|
130 |
+
|
131 |
+
|
132 |
+
class MLP(nn.Module):
|
133 |
+
def __init__(self, input_dim, hidden_dim, output_dim, n_layers):
|
134 |
+
super().__init__()
|
135 |
+
|
136 |
+
self.layers = nn.ModuleList()
|
137 |
+
|
138 |
+
for layer in range(n_layers):
|
139 |
+
dim = input_dim if layer == 0 else hidden_dim
|
140 |
+
self.layers.append(nn.Sequential(
|
141 |
+
nn.Linear(dim, hidden_dim),
|
142 |
+
nn.BatchNorm1d(hidden_dim),
|
143 |
+
nn.ReLU())
|
144 |
+
)
|
145 |
+
|
146 |
+
self.layers.append(nn.Sequential(
|
147 |
+
nn.Linear(hidden_dim, output_dim))
|
148 |
+
)
|
149 |
+
|
150 |
+
def forward(self, x):
|
151 |
+
for layer in self.layers:
|
152 |
+
x = layer(x)
|
153 |
+
return x
|
154 |
+
|
155 |
+
|
156 |
+
class AttentionPool2d(nn.Module):
|
157 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
|
158 |
+
super().__init__()
|
159 |
+
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
|
160 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim)
|
161 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim)
|
162 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim)
|
163 |
+
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
|
164 |
+
self.num_heads = num_heads
|
165 |
+
|
166 |
+
def forward(self, x):
|
167 |
+
x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
|
168 |
+
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
|
169 |
+
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
|
170 |
+
x, _ = F.multi_head_attention_forward(
|
171 |
+
query=x, key=x, value=x,
|
172 |
+
embed_dim_to_check=x.shape[-1],
|
173 |
+
num_heads=self.num_heads,
|
174 |
+
q_proj_weight=self.q_proj.weight,
|
175 |
+
k_proj_weight=self.k_proj.weight,
|
176 |
+
v_proj_weight=self.v_proj.weight,
|
177 |
+
in_proj_weight=None,
|
178 |
+
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
|
179 |
+
bias_k=None,
|
180 |
+
bias_v=None,
|
181 |
+
add_zero_attn=False,
|
182 |
+
dropout_p=0,
|
183 |
+
out_proj_weight=self.c_proj.weight,
|
184 |
+
out_proj_bias=self.c_proj.bias,
|
185 |
+
use_separate_proj_weight=True,
|
186 |
+
training=self.training,
|
187 |
+
need_weights=False
|
188 |
+
)
|
189 |
+
|
190 |
+
return x[0]
|
191 |
+
|
192 |
+
|
193 |
+
class ModifiedResNet(nn.Module):
|
194 |
+
"""
|
195 |
+
A ResNet class that is similar to torchvision's but contains the following changes:
|
196 |
+
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
|
197 |
+
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
|
198 |
+
- The final pooling layer is a QKV attention instead of an average pool
|
199 |
+
"""
|
200 |
+
|
201 |
+
def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
|
202 |
+
super().__init__()
|
203 |
+
self.output_dim = output_dim
|
204 |
+
self.input_resolution = input_resolution
|
205 |
+
|
206 |
+
# the 3-layer stem
|
207 |
+
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
|
208 |
+
self.bn1 = nn.BatchNorm2d(width // 2)
|
209 |
+
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
|
210 |
+
self.bn2 = nn.BatchNorm2d(width // 2)
|
211 |
+
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
|
212 |
+
self.bn3 = nn.BatchNorm2d(width)
|
213 |
+
self.avgpool = nn.AvgPool2d(2)
|
214 |
+
self.relu = nn.ReLU(inplace=True)
|
215 |
+
|
216 |
+
# residual layers
|
217 |
+
self._inplanes = width # this is a *mutable* variable used during construction
|
218 |
+
self.layer1 = self._make_layer(width, layers[0])
|
219 |
+
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
|
220 |
+
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
|
221 |
+
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
|
222 |
+
|
223 |
+
embed_dim = width * 32 # the ResNet feature dimension
|
224 |
+
self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
|
225 |
+
self.initialize_parameters()
|
226 |
+
|
227 |
+
def _make_layer(self, planes, blocks, stride=1):
|
228 |
+
layers = [Bottleneck(self._inplanes, planes, stride)]
|
229 |
+
|
230 |
+
self._inplanes = planes * Bottleneck.expansion
|
231 |
+
for _ in range(1, blocks):
|
232 |
+
layers.append(Bottleneck(self._inplanes, planes))
|
233 |
+
|
234 |
+
return nn.Sequential(*layers)
|
235 |
+
|
236 |
+
def initialize_parameters(self):
|
237 |
+
if self.attnpool is not None:
|
238 |
+
std = self.attnpool.c_proj.in_features ** -0.5
|
239 |
+
nn.init.normal_(self.attnpool.q_proj.weight, std=std)
|
240 |
+
nn.init.normal_(self.attnpool.k_proj.weight, std=std)
|
241 |
+
nn.init.normal_(self.attnpool.v_proj.weight, std=std)
|
242 |
+
nn.init.normal_(self.attnpool.c_proj.weight, std=std)
|
243 |
+
|
244 |
+
for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]:
|
245 |
+
for name, param in resnet_block.named_parameters():
|
246 |
+
if name.endswith("bn3.weight"):
|
247 |
+
nn.init.zeros_(param)
|
248 |
+
|
249 |
+
def forward(self, x):
|
250 |
+
def stem(x):
|
251 |
+
for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]:
|
252 |
+
x = self.relu(bn(conv(x)))
|
253 |
+
x = self.avgpool(x)
|
254 |
+
return x
|
255 |
+
|
256 |
+
x = x.type(self.conv1.weight.dtype)
|
257 |
+
x = stem(x)
|
258 |
+
x = self.layer1(x)
|
259 |
+
x = self.layer2(x)
|
260 |
+
x = self.layer3(x)
|
261 |
+
x = self.layer4(x)
|
262 |
+
x = self.attnpool(x)
|
263 |
+
|
264 |
+
return x
|
265 |
+
|
266 |
+
|
267 |
+
class PretrainedResNet(nn.Module):
|
268 |
+
"""docstring for PretrainedResNet."""
|
269 |
+
|
270 |
+
def __init__(self, input_shape, output_dim, adapt=False):
|
271 |
+
super().__init__()
|
272 |
+
|
273 |
+
self.adapt = adapt
|
274 |
+
|
275 |
+
if self.adapt:
|
276 |
+
input_channels = 3
|
277 |
+
else:
|
278 |
+
input_channels = input_shape
|
279 |
+
|
280 |
+
self.conv1 = nn.Conv2d(input_shape, input_channels, kernel_size=7, padding=1, bias=False)
|
281 |
+
self.pretrained_resnet = timm.create_model('resnet50', pretrained=True, in_chans=input_channels)
|
282 |
+
self.pretrained_resnet.fc = nn.Linear(2048, output_dim)
|
283 |
+
|
284 |
+
def forward(self, x: torch.Tensor):
|
285 |
+
if self.adapt:
|
286 |
+
x = self.conv1(x)
|
287 |
+
x = self.pretrained_resnet(x)
|
288 |
+
return x
|
289 |
+
|
290 |
+
|
291 |
+
class LayerNorm(nn.LayerNorm):
|
292 |
+
"""Subclass torch's LayerNorm to handle fp16."""
|
293 |
+
|
294 |
+
def forward(self, x: torch.Tensor):
|
295 |
+
orig_type = x.dtype
|
296 |
+
ret = super().forward(x.type(torch.float32))
|
297 |
+
return ret.type(orig_type)
|
298 |
+
|
299 |
+
|
300 |
+
class QuickGELU(nn.Module):
|
301 |
+
def forward(self, x: torch.Tensor):
|
302 |
+
return x * torch.sigmoid(1.702 * x)
|
303 |
+
|
304 |
+
|
305 |
+
class ResidualAttentionBlock(nn.Module):
|
306 |
+
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
|
307 |
+
super().__init__()
|
308 |
+
|
309 |
+
self.attn = nn.MultiheadAttention(d_model, n_head)
|
310 |
+
self.ln_1 = LayerNorm(d_model)
|
311 |
+
self.mlp = nn.Sequential(OrderedDict([
|
312 |
+
("c_fc", nn.Linear(d_model, d_model * 4)),
|
313 |
+
("gelu", QuickGELU()),
|
314 |
+
("c_proj", nn.Linear(d_model * 4, d_model))
|
315 |
+
]))
|
316 |
+
self.ln_2 = LayerNorm(d_model)
|
317 |
+
self.attn_mask = attn_mask
|
318 |
+
|
319 |
+
def attention(self, x: torch.Tensor):
|
320 |
+
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
|
321 |
+
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
|
322 |
+
|
323 |
+
def forward(self, x: torch.Tensor):
|
324 |
+
x = x + self.attention(self.ln_1(x))
|
325 |
+
x = x + self.mlp(self.ln_2(x))
|
326 |
+
return x
|
327 |
+
|
328 |
+
|
329 |
+
class Transformer(nn.Module):
|
330 |
+
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
|
331 |
+
super().__init__()
|
332 |
+
self.width = width
|
333 |
+
self.layers = layers
|
334 |
+
self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
|
335 |
+
|
336 |
+
def forward(self, x: torch.Tensor):
|
337 |
+
return self.resblocks(x)
|
338 |
+
|
339 |
+
|
340 |
+
class VisualTransformer(nn.Module):
|
341 |
+
def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
|
342 |
+
super().__init__()
|
343 |
+
self.input_resolution = input_resolution
|
344 |
+
self.output_dim = output_dim
|
345 |
+
self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
|
346 |
+
|
347 |
+
scale = width ** -0.5
|
348 |
+
self.class_embedding = nn.Parameter(scale * torch.randn(width))
|
349 |
+
self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
|
350 |
+
self.ln_pre = LayerNorm(width)
|
351 |
+
|
352 |
+
self.transformer = Transformer(width, layers, heads)
|
353 |
+
|
354 |
+
self.ln_post = LayerNorm(width)
|
355 |
+
self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
|
356 |
+
|
357 |
+
def forward(self, x: torch.Tensor):
|
358 |
+
x = self.conv1(x) # shape = [*, width, grid, grid]
|
359 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
360 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
361 |
+
x = torch.cat(
|
362 |
+
[self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
|
363 |
+
x], dim=1) # shape = [*, grid ** 2 + 1, width]
|
364 |
+
x = x + self.positional_embedding.to(x.dtype)
|
365 |
+
x = self.ln_pre(x)
|
366 |
+
|
367 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
368 |
+
x = self.transformer(x)
|
369 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
370 |
+
|
371 |
+
x = self.ln_post(x[:, 0, :])
|
372 |
+
|
373 |
+
if self.proj is not None:
|
374 |
+
x = x @ self.proj
|
375 |
+
|
376 |
+
return x
|
377 |
+
|
378 |
+
|
379 |
+
class TextTransformer(nn.Module):
|
380 |
+
def __init__(self,
|
381 |
+
embed_dim: int,
|
382 |
+
context_length: int,
|
383 |
+
vocab_size: int,
|
384 |
+
transformer_width: int,
|
385 |
+
transformer_heads: int,
|
386 |
+
transformer_layers: int):
|
387 |
+
super().__init__()
|
388 |
+
self.context_length = context_length
|
389 |
+
self.transformer = Transformer(
|
390 |
+
width=transformer_width,
|
391 |
+
layers=transformer_layers,
|
392 |
+
heads=transformer_heads,
|
393 |
+
attn_mask=self.build_attention_mask()
|
394 |
+
)
|
395 |
+
self.vocab_size = vocab_size
|
396 |
+
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
|
397 |
+
self.positional_embedding = nn.Parameter(
|
398 |
+
torch.empty(self.context_length, transformer_width))
|
399 |
+
self.ln_final = LayerNorm(transformer_width)
|
400 |
+
self.text_projection = nn.Parameter(
|
401 |
+
torch.empty(transformer_width, embed_dim))
|
402 |
+
self.initialize_parameters()
|
403 |
+
|
404 |
+
def initialize_parameters(self):
|
405 |
+
torch.nn.init.normal_(self.token_embedding.weight, std=0.02)
|
406 |
+
torch.nn.init.normal_(self.positional_embedding, std=0.01)
|
407 |
+
proj_std = (self.transformer.width ** -0.5) * (
|
408 |
+
(2 * self.transformer.layers) ** -0.5)
|
409 |
+
attn_std = self.transformer.width ** -0.5
|
410 |
+
fc_std = (2 * self.transformer.width) ** -0.5
|
411 |
+
for block in self.transformer.resblocks:
|
412 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
413 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
414 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
415 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
416 |
+
|
417 |
+
if self.text_projection is not None:
|
418 |
+
nn.init.normal_(
|
419 |
+
self.text_projection, std=self.transformer.width ** -0.5)
|
420 |
+
|
421 |
+
@property
|
422 |
+
def dtype(self):
|
423 |
+
return self.text_projection.dtype
|
424 |
+
|
425 |
+
def build_attention_mask(self):
|
426 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
427 |
+
# pytorch uses additive attention mask; fill with -inf
|
428 |
+
mask = torch.empty(self.context_length, self.context_length)
|
429 |
+
mask.fill_(float("-inf"))
|
430 |
+
mask.triu_(1) # zero out the lower diagonal
|
431 |
+
return mask
|
432 |
+
|
433 |
+
def forward(self, text):
|
434 |
+
x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
|
435 |
+
|
436 |
+
x = x + self.positional_embedding.type(self.dtype)
|
437 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
438 |
+
x = self.transformer(x)
|
439 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
440 |
+
x = self.ln_final(x).type(self.dtype)
|
441 |
+
|
442 |
+
# x.shape = [batch_size, n_ctx, transformer.width]
|
443 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
444 |
+
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
|
445 |
+
return x
|
446 |
+
|
447 |
+
|
448 |
+
def get_backbone(architecture, **kwargs):
|
449 |
+
if 'seed' in kwargs.keys():
|
450 |
+
torch.manual_seed(kwargs['seed'])
|
451 |
+
if architecture == "ResNet-pre":
|
452 |
+
print(PretrainedResNet(kwargs['input_channels'], kwargs['embed_dim'], adapt=kwargs['adapt']))
|
453 |
+
return PretrainedResNet(
|
454 |
+
input_shape=kwargs['input_channels'],
|
455 |
+
output_dim=kwargs['embed_dim'],
|
456 |
+
adapt=kwargs['adapt'])
|
457 |
+
if architecture == 'ResNet':
|
458 |
+
return ResNet(
|
459 |
+
layers=kwargs['vision_layers'],
|
460 |
+
output_dim=kwargs['embed_dim'],
|
461 |
+
input_shape=kwargs['input_channels'])
|
462 |
+
if architecture == 'MLP':
|
463 |
+
return MLP(
|
464 |
+
input_dim=kwargs['input_size'],
|
465 |
+
n_layers=kwargs['molecule_layers'],
|
466 |
+
hidden_dim=kwargs['hidden_dim'],
|
467 |
+
output_dim=kwargs['embed_dim'])
|
468 |
+
if architecture == 'ModifiedResNet':
|
469 |
+
return ModifiedResNet(
|
470 |
+
layers=kwargs['vision_layers'],
|
471 |
+
output_dim=kwargs['embed_dim'],
|
472 |
+
heads=kwargs['vision_width'] * 32 // 64,
|
473 |
+
input_resolution=kwargs['image_resolution'],
|
474 |
+
width=kwargs['vision_width'])
|
475 |
+
elif architecture == 'VisualTransformer':
|
476 |
+
return VisualTransformer(
|
477 |
+
input_resolution=kwargs['image_resolution'],
|
478 |
+
patch_size=kwargs['vision_patch_size'],
|
479 |
+
width=kwargs['vision_width'],
|
480 |
+
layers=kwargs['vision_layers'],
|
481 |
+
heads=kwargs['vision_width'] // 64,
|
482 |
+
output_dim=kwargs['embed_dim'])
|
483 |
+
elif architecture == 'TextTransformer':
|
484 |
+
return TextTransformer(
|
485 |
+
embed_dim=kwargs['embed_dim'],
|
486 |
+
context_length=kwargs['context_length'],
|
487 |
+
vocab_size=kwargs['vocab_size'],
|
488 |
+
transformer_width=kwargs['transformer_width'],
|
489 |
+
transformer_heads=kwargs['transformer_heads'],
|
490 |
+
transformer_layers=kwargs['transformer_layers'])
|
491 |
+
|
492 |
+
|
493 |
+
class CLIPGeneral(nn.Module):
|
494 |
+
def __init__(self,
|
495 |
+
init_inv_tau: float = 14.3,
|
496 |
+
learnable_inv_tau: bool = True,
|
497 |
+
backbone_architecture: List[str] = ['ResNet', 'MLP'],
|
498 |
+
**kwargs
|
499 |
+
):
|
500 |
+
super().__init__()
|
501 |
+
|
502 |
+
self.visual = get_backbone(
|
503 |
+
backbone_architecture[0],
|
504 |
+
**kwargs.get(f"{backbone_architecture[0]}-0", kwargs))
|
505 |
+
self.transformer = get_backbone(
|
506 |
+
backbone_architecture[1],
|
507 |
+
**kwargs.get(f"{backbone_architecture[1]}-1", kwargs))
|
508 |
+
|
509 |
+
# Logit scales for the inner product in the InfoNCE loss
|
510 |
+
self.logit_inv_tau = nn.Parameter(torch.ones([]) * np.log(init_inv_tau))
|
511 |
+
self.logit_inv_tau.requires_grad = learnable_inv_tau
|
512 |
+
|
513 |
+
@property
|
514 |
+
def dtype(self):
|
515 |
+
try:
|
516 |
+
return self.visual.conv1.weight.dtype
|
517 |
+
except:
|
518 |
+
return self.visual.fc.weight.dtype
|
519 |
+
|
520 |
+
def encode_image(self, image):
|
521 |
+
return self.visual(image.type(self.dtype))
|
522 |
+
|
523 |
+
def encode_text(self, text):
|
524 |
+
return self.transformer(text.type(self.dtype))
|
525 |
+
|
526 |
+
def forward(self, image, text):
|
527 |
+
if image is None:
|
528 |
+
return self.encode_text(text)
|
529 |
+
elif text is None:
|
530 |
+
return self.encode_image(image)
|
531 |
+
image_features = self.encode_image(image)
|
532 |
+
text_features = self.encode_text(text)
|
533 |
+
|
534 |
+
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
535 |
+
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
|
536 |
+
|
537 |
+
return image_features, text_features, self.logit_inv_tau.exp()
|
538 |
+
|
539 |
+
|
540 |
+
class CLIP(nn.Module):
|
541 |
+
def __init__(self,
|
542 |
+
embed_dim: int,
|
543 |
+
# vision
|
544 |
+
image_resolution: int,
|
545 |
+
vision_layers: Union[Tuple[int, int, int, int], int],
|
546 |
+
vision_width: int,
|
547 |
+
vision_patch_size: int,
|
548 |
+
# text
|
549 |
+
context_length: int,
|
550 |
+
vocab_size: int,
|
551 |
+
transformer_width: int,
|
552 |
+
transformer_heads: int,
|
553 |
+
transformer_layers: int,
|
554 |
+
init_inv_tau: float = 14.3,
|
555 |
+
learnable_inv_tau: bool = True
|
556 |
+
):
|
557 |
+
super().__init__()
|
558 |
+
|
559 |
+
self.context_length = context_length
|
560 |
+
|
561 |
+
if isinstance(vision_layers, (tuple, list)):
|
562 |
+
vision_heads = vision_width * 32 // 64
|
563 |
+
self.visual = ModifiedResNet(
|
564 |
+
layers=vision_layers,
|
565 |
+
output_dim=embed_dim,
|
566 |
+
heads=vision_heads,
|
567 |
+
input_resolution=image_resolution,
|
568 |
+
width=vision_width
|
569 |
+
)
|
570 |
+
else:
|
571 |
+
vision_heads = vision_width // 64
|
572 |
+
self.visual = VisualTransformer(
|
573 |
+
input_resolution=image_resolution,
|
574 |
+
patch_size=vision_patch_size,
|
575 |
+
width=vision_width,
|
576 |
+
layers=vision_layers,
|
577 |
+
heads=vision_heads,
|
578 |
+
output_dim=embed_dim
|
579 |
+
)
|
580 |
+
|
581 |
+
self.transformer = Transformer(
|
582 |
+
width=transformer_width,
|
583 |
+
layers=transformer_layers,
|
584 |
+
heads=transformer_heads,
|
585 |
+
attn_mask=self.build_attention_mask()
|
586 |
+
)
|
587 |
+
|
588 |
+
self.vocab_size = vocab_size
|
589 |
+
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
|
590 |
+
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
|
591 |
+
self.ln_final = LayerNorm(transformer_width)
|
592 |
+
|
593 |
+
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
|
594 |
+
|
595 |
+
# Logit scales for the inner product in the InfoNCE loss
|
596 |
+
self.logit_inv_tau = nn.Parameter(torch.ones([]) * np.log(init_inv_tau))
|
597 |
+
self.logit_inv_tau.requires_grad = learnable_inv_tau
|
598 |
+
|
599 |
+
self.initialize_parameters()
|
600 |
+
|
601 |
+
def initialize_parameters(self):
|
602 |
+
nn.init.normal_(self.token_embedding.weight, std=0.02)
|
603 |
+
nn.init.normal_(self.positional_embedding, std=0.01)
|
604 |
+
|
605 |
+
if isinstance(self.visual, ModifiedResNet):
|
606 |
+
if self.visual.attnpool is not None:
|
607 |
+
std = self.visual.attnpool.c_proj.in_features ** -0.5
|
608 |
+
nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
|
609 |
+
nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
|
610 |
+
nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
|
611 |
+
nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
|
612 |
+
|
613 |
+
for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
|
614 |
+
for name, param in resnet_block.named_parameters():
|
615 |
+
if name.endswith("bn3.weight"):
|
616 |
+
nn.init.zeros_(param)
|
617 |
+
|
618 |
+
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
|
619 |
+
attn_std = self.transformer.width ** -0.5
|
620 |
+
fc_std = (2 * self.transformer.width) ** -0.5
|
621 |
+
for block in self.transformer.resblocks:
|
622 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
|
623 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
|
624 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
|
625 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
|
626 |
+
|
627 |
+
if self.text_projection is not None:
|
628 |
+
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
|
629 |
+
|
630 |
+
def build_attention_mask(self):
|
631 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
632 |
+
# pytorch uses additive attention mask; fill with -inf
|
633 |
+
mask = torch.empty(self.context_length, self.context_length)
|
634 |
+
mask.fill_(float("-inf"))
|
635 |
+
mask.triu_(1) # zero out the lower diagonal
|
636 |
+
return mask
|
637 |
+
|
638 |
+
@property
|
639 |
+
def dtype(self):
|
640 |
+
return self.visual.conv1.weight.dtype
|
641 |
+
|
642 |
+
def encode_image(self, image):
|
643 |
+
return self.visual(image.type(self.dtype))
|
644 |
+
|
645 |
+
def encode_text(self, text):
|
646 |
+
x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
|
647 |
+
|
648 |
+
x = x + self.positional_embedding.type(self.dtype)
|
649 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
650 |
+
x = self.transformer(x)
|
651 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
652 |
+
x = self.ln_final(x).type(self.dtype)
|
653 |
+
|
654 |
+
# x.shape = [batch_size, n_ctx, transformer.width]
|
655 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
656 |
+
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
|
657 |
+
|
658 |
+
return x
|
659 |
+
|
660 |
+
def forward(self, image, text):
|
661 |
+
if image is None:
|
662 |
+
return self.encode_text(text)
|
663 |
+
elif text is None:
|
664 |
+
return self.encode_image(image)
|
665 |
+
image_features = self.encode_image(image)
|
666 |
+
text_features = self.encode_text(text)
|
667 |
+
|
668 |
+
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
669 |
+
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
|
670 |
+
return image_features, text_features, self.logit_inv_tau.exp()
|
671 |
+
|
672 |
+
|
673 |
+
def convert_weights(model: nn.Module):
|
674 |
+
"""Convert applicable model parameters to fp16"""
|
675 |
+
|
676 |
+
def _convert_weights_to_fp16(l):
|
677 |
+
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
|
678 |
+
l.weight.data = l.weight.data.half()
|
679 |
+
if l.bias is not None:
|
680 |
+
l.bias.data = l.bias.data.half()
|
681 |
+
|
682 |
+
if isinstance(l, nn.MultiheadAttention):
|
683 |
+
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
|
684 |
+
tensor = getattr(l, attr)
|
685 |
+
if tensor is not None:
|
686 |
+
tensor.data = tensor.data.half()
|
687 |
+
|
688 |
+
for name in ["text_projection", "proj"]:
|
689 |
+
if hasattr(l, name):
|
690 |
+
attr = getattr(l, name)
|
691 |
+
if attr is not None:
|
692 |
+
attr.data = attr.data.half()
|
693 |
+
|
694 |
+
model.apply(_convert_weights_to_fp16)
|
695 |
+
|
696 |
+
|
697 |
+
def build_model(state_dict: dict):
|
698 |
+
vit = "visual.proj" in state_dict
|
699 |
+
|
700 |
+
if vit:
|
701 |
+
vision_width = state_dict["visual.conv1.weight"].shape[0]
|
702 |
+
vision_layers = len(
|
703 |
+
[k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
704 |
+
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
|
705 |
+
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
706 |
+
image_resolution = vision_patch_size * grid_size
|
707 |
+
else:
|
708 |
+
counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in
|
709 |
+
[1, 2, 3, 4]]
|
710 |
+
vision_layers = tuple(counts)
|
711 |
+
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
|
712 |
+
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
|
713 |
+
vision_patch_size = None
|
714 |
+
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
|
715 |
+
image_resolution = output_width * 32
|
716 |
+
|
717 |
+
embed_dim = state_dict["text_projection"].shape[1]
|
718 |
+
context_length = state_dict["positional_embedding"].shape[0]
|
719 |
+
vocab_size = state_dict["token_embedding.weight"].shape[0]
|
720 |
+
transformer_width = state_dict["ln_final.weight"].shape[0]
|
721 |
+
transformer_heads = transformer_width // 64
|
722 |
+
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
|
723 |
+
|
724 |
+
model = CLIP(
|
725 |
+
embed_dim,
|
726 |
+
image_resolution, vision_layers, vision_width, vision_patch_size,
|
727 |
+
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
|
728 |
+
)
|
729 |
+
|
730 |
+
for key in ["input_resolution", "context_length", "vocab_size"]:
|
731 |
+
if key in state_dict:
|
732 |
+
del state_dict[key]
|
733 |
+
|
734 |
+
convert_weights(model)
|
735 |
+
model.load_state_dict(state_dict)
|
736 |
+
return model.eval()
|
src/training/datasets.py
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
import pandas as pd
|
5 |
+
from pathlib import Path
|
6 |
+
from scipy.io import mmread
|
7 |
+
from torchvision.transforms import Compose
|
8 |
+
from torch.utils.data import Dataset
|
9 |
+
|
10 |
+
class CellPainting(Dataset):
|
11 |
+
def __init__(self, sample_index_file: str, image_directory_path: str = None, molecule_file: str = None, label_matrix_file: str = None,
|
12 |
+
label_row_index_file: str = None, label_col_index_file: str = None, auxiliary_labels=None,
|
13 |
+
transforms=None, group_views: bool = False,
|
14 |
+
subset: float = 1., num_classes: int = None, verbose: bool = False):
|
15 |
+
""" Read samples from cellpainting dataset."""
|
16 |
+
self.verbose = verbose
|
17 |
+
self.molecules = False
|
18 |
+
self.images = False
|
19 |
+
|
20 |
+
assert (os.path.exists(sample_index_file))
|
21 |
+
print(image_directory_path)
|
22 |
+
print(molecule_file)
|
23 |
+
# Read sample index
|
24 |
+
sample_index = pd.read_csv(sample_index_file, sep=",", header=0)
|
25 |
+
sample_index.set_index(["SAMPLE_KEY"])
|
26 |
+
|
27 |
+
# read auxiliary labels if provided
|
28 |
+
if auxiliary_labels is not None:
|
29 |
+
pddata = pd.read_csv(auxiliary_labels, sep=",", header=0)
|
30 |
+
self.auxiliary_data = pddata.as_matrix()[:, 2:].astype(np.float32)
|
31 |
+
# threshold
|
32 |
+
self.auxiliary_data[self.auxiliary_data < 0.75] = -1
|
33 |
+
self.auxiliary_data[self.auxiliary_data >= 0.75] = 1
|
34 |
+
self.auxiliary_assays = list(pddata)[2:]
|
35 |
+
self.n_auxiliary_classes = len(self.auxiliary_assays)
|
36 |
+
self.auxiliary_smiles = pddata["SMILES"].tolist()
|
37 |
+
else:
|
38 |
+
self.n_auxiliary_classes = 0
|
39 |
+
|
40 |
+
if image_directory_path:
|
41 |
+
self.images = True
|
42 |
+
assert (os.path.exists(image_directory_path))
|
43 |
+
|
44 |
+
if group_views:
|
45 |
+
sample_groups = sample_index.groupby(['PLATE_ID', 'WELL_POSITION'])
|
46 |
+
sample_keys = list(sample_groups.groups.keys())
|
47 |
+
sample_index = sample_groups
|
48 |
+
self.sample_to_smiles = None # TODO
|
49 |
+
else:
|
50 |
+
sample_keys = sample_index['SAMPLE_KEY'].tolist()
|
51 |
+
|
52 |
+
if auxiliary_labels is not None:
|
53 |
+
self.sample_to_smiles = dict(zip(sample_index.SAMPLE_KEY, [self.auxiliary_smiles.index(s) for s in sample_index.SMILES]))
|
54 |
+
else:
|
55 |
+
self.sample_to_smiles = None
|
56 |
+
|
57 |
+
if molecule_file:
|
58 |
+
self.molecules = True
|
59 |
+
|
60 |
+
assert (os.path.exists(molecule_file))
|
61 |
+
|
62 |
+
molecule_df = pd.read_hdf(molecule_file, key="df")
|
63 |
+
#molecule_objs = {index: row.values for index, row in molecule_df.iterrows()}
|
64 |
+
|
65 |
+
#keys = list(set(sample_keys) & set(list(molecule_df.index.values)))
|
66 |
+
mol_keys = list(molecule_df.index.values)
|
67 |
+
|
68 |
+
if self.images and self.molecules:
|
69 |
+
keys = list(set(sample_keys) & set(list(molecule_df.index.values)))
|
70 |
+
elif self.images:
|
71 |
+
keys = sample_keys
|
72 |
+
elif self.molecules:
|
73 |
+
keys = mol_keys
|
74 |
+
|
75 |
+
|
76 |
+
if len(keys) == 0:
|
77 |
+
raise Exception("Empty dataset!")
|
78 |
+
else:
|
79 |
+
self.log("Found {} samples".format(len(keys)))
|
80 |
+
|
81 |
+
if subset != 1.:
|
82 |
+
sample_keys = sample_keys[:int(len(sample_keys) * subset)]
|
83 |
+
|
84 |
+
# Read Label Matrix if specified
|
85 |
+
if label_matrix_file is not None:
|
86 |
+
assert (os.path.exists(label_matrix_file))
|
87 |
+
|
88 |
+
assert (os.path.exists(label_row_index_file))
|
89 |
+
|
90 |
+
assert (os.path.exists(label_col_index_file))
|
91 |
+
|
92 |
+
|
93 |
+
if label_row_index_file is not None and label_col_index_file is not None:
|
94 |
+
col_index = pd.read_csv(label_col_index_file, sep=",", header=0)
|
95 |
+
row_index = pd.read_csv(label_row_index_file, sep=",", header=0)
|
96 |
+
label_matrix = mmread(label_matrix_file).tocsr()
|
97 |
+
# --
|
98 |
+
self.label_matrix = label_matrix
|
99 |
+
self.row_index = row_index
|
100 |
+
self.col_index = col_index
|
101 |
+
if group_views:
|
102 |
+
self.label_dict = dict(
|
103 |
+
(key, sample_groups.get_group(key).iloc[0].ROW_NR_LABEL_MAT) for key in sample_keys)
|
104 |
+
else:
|
105 |
+
self.label_dict = dict(zip(sample_index.SAMPLE_KEY, sample_index.ROW_NR_LABEL_MAT))
|
106 |
+
self.n_classes = label_matrix.shape[1]
|
107 |
+
else:
|
108 |
+
raise Exception("If label is specified index files must be passed!")
|
109 |
+
else:
|
110 |
+
self.label_matrix = None
|
111 |
+
self.row_index = None
|
112 |
+
self.col_index = None
|
113 |
+
self.label_dict = None
|
114 |
+
self.n_classes = num_classes
|
115 |
+
|
116 |
+
if auxiliary_labels is not None:
|
117 |
+
self.n_classes += self.n_auxiliary_classes
|
118 |
+
|
119 |
+
# expose everything important
|
120 |
+
self.data_directory = image_directory_path
|
121 |
+
self.sample_index = sample_index
|
122 |
+
if self.molecules:
|
123 |
+
self.molecule_objs = molecule_df
|
124 |
+
self.keys = keys
|
125 |
+
self.n_samples = len(keys)
|
126 |
+
self.sample_keys = list(keys)
|
127 |
+
self.group_views = group_views
|
128 |
+
self.transforms = transforms
|
129 |
+
|
130 |
+
# load first sample and check shape
|
131 |
+
i = 0
|
132 |
+
|
133 |
+
sample = self[i][0] if self.molecules else self[i] #getitem returns tuple of img and fp
|
134 |
+
|
135 |
+
|
136 |
+
# while sample["input"] is np.nan and i < len(self):
|
137 |
+
# sample = self[i][0] if self.molecules else self[i]
|
138 |
+
# i += 1
|
139 |
+
#
|
140 |
+
# if sample["input"] is not None and not np.nan:
|
141 |
+
# self.data_shape = sample["input"].shape
|
142 |
+
# else:
|
143 |
+
# self.data_shape = "Unknown"
|
144 |
+
# self.log("Discovered {} samples (subset={}) with shape {}".format(self.n_samples, subset, self.data_shape))
|
145 |
+
|
146 |
+
|
147 |
+
def __len__(self):
|
148 |
+
return len(self.keys)
|
149 |
+
|
150 |
+
## TODO: Clean!
|
151 |
+
def __getitem__(self, idx):
|
152 |
+
sample_key = self.keys[idx]
|
153 |
+
|
154 |
+
|
155 |
+
if self.molecules and self.images:
|
156 |
+
mol = self.molecule_objs.loc[sample_key].values
|
157 |
+
img = self.read_img(sample_key)
|
158 |
+
# mol = list(self.molecule_objs.loc[sample_key].values)
|
159 |
+
return img, mol
|
160 |
+
elif self.images:
|
161 |
+
img = self.read_img(sample_key)
|
162 |
+
return img
|
163 |
+
elif self.molecules:
|
164 |
+
mol = self.molecule_objs.loc[sample_key].values
|
165 |
+
return mol
|
166 |
+
|
167 |
+
|
168 |
+
@property
|
169 |
+
def shape(self):
|
170 |
+
return self.data_shape
|
171 |
+
|
172 |
+
@property
|
173 |
+
def num_classes(self):
|
174 |
+
return self.n_classes
|
175 |
+
|
176 |
+
def log(self, message):
|
177 |
+
if self.verbose:
|
178 |
+
print(message)
|
179 |
+
|
180 |
+
|
181 |
+
def read_img(self, key):
|
182 |
+
if self.group_views:
|
183 |
+
X = self.load_view_group(key)
|
184 |
+
else:
|
185 |
+
filepath = os.path.join(self.data_directory, "{}.npz".format(key))
|
186 |
+
if os.path.exists(filepath):
|
187 |
+
X = self.load_view(filepath=filepath)
|
188 |
+
|
189 |
+
index = int(np.where(self.sample_index["SAMPLE_KEY"]==key)[0])
|
190 |
+
|
191 |
+
#cpd = str(self.sample_index["CPD_NAME"])
|
192 |
+
|
193 |
+
else:
|
194 |
+
#print("ERROR: Missing sample '{}'".format(key))
|
195 |
+
return dict(input=np.nan, ID=key)
|
196 |
+
|
197 |
+
if self.transforms:
|
198 |
+
X = self.transforms(X)
|
199 |
+
|
200 |
+
# get label
|
201 |
+
if self.label_dict is not None:
|
202 |
+
label_idx = self.label_dict[key]
|
203 |
+
y = self.label_matrix[label_idx].toarray()[0].astype(np.float32)
|
204 |
+
if self.sample_to_smiles is not None and key in self.sample_to_smiles:
|
205 |
+
y = np.concatenate([y, self.auxiliary_data[self.sample_to_smiles[key], :]])
|
206 |
+
|
207 |
+
return dict(input=X, target=y, ID=key)
|
208 |
+
else:
|
209 |
+
return dict(input=X, row_id=index, ID=key)
|
210 |
+
|
211 |
+
|
212 |
+
def get_sample_keys(self):
|
213 |
+
return self.sample_keys.copy()
|
214 |
+
|
215 |
+
def load_view(self, filepath):
|
216 |
+
"""Load all channels for one sample"""
|
217 |
+
npz = np.load(filepath, allow_pickle=True)
|
218 |
+
if "sample" in npz:
|
219 |
+
image = npz["sample"].astype(np.float32)
|
220 |
+
#image_reshaped = np.transpose(image, (2, 0, 1))
|
221 |
+
# for c in range(image.shape[-1]):
|
222 |
+
# image[:, :, c] = (image[:, :, c] - image[:, :, c].mean()) / image[:, :, c].std()
|
223 |
+
# image[:, :, c] = ((image[:, :, c] - image[:, :, c].mean()) / image[:, :, c].std() * 255).astype(np.uint8)
|
224 |
+
# image = (image - image.mean()) / image.std()
|
225 |
+
return image
|
226 |
+
|
227 |
+
return None
|
228 |
+
|
229 |
+
def load_view_group(self, groupkey):
|
230 |
+
result = np.empty((1040, 2088 - 12, 5), dtype=np.uint8)
|
231 |
+
viewgroup = self.sample_index.get_group(groupkey)
|
232 |
+
for i, view in enumerate(viewgroup.sort_values("SITE", ascending=True).iterrows()):
|
233 |
+
corner = (0 if int(i / 3) == 0 else 520, i % 3 * 692)
|
234 |
+
filepath = os.path.join(self.data_directory, "{}.npz".format(view[1].SAMPLE_KEY))
|
235 |
+
v = self.load_view(filepath=filepath)[:, 4:, :]
|
236 |
+
# for j in range(v.shape[-1]):
|
237 |
+
# plt.imshow(v[:, :, j])
|
238 |
+
# plt.savefig("{}-{}-{}-{}.png".format(groupkey[0], groupkey[1], i, j))
|
239 |
+
result[corner[0]:corner[0] + 520, corner[1]:corner[1] + 692, :] = v
|
240 |
+
return result
|
src/training/model_configs/RN101.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"image_resolution": 224,
|
4 |
+
"vision_layers": [
|
5 |
+
3,
|
6 |
+
4,
|
7 |
+
23,
|
8 |
+
3
|
9 |
+
],
|
10 |
+
"vision_width": 64,
|
11 |
+
"vision_patch_size": null,
|
12 |
+
"context_length": 77,
|
13 |
+
"vocab_size": 49408,
|
14 |
+
"transformer_width": 512,
|
15 |
+
"transformer_heads": 8,
|
16 |
+
"transformer_layers": 12
|
17 |
+
}
|
src/training/model_configs/RN50-pre.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_block": "bottleneck",
|
4 |
+
"input_channels": 5,
|
5 |
+
"vision_layers": [
|
6 |
+
3,
|
7 |
+
4,
|
8 |
+
6,
|
9 |
+
3
|
10 |
+
],
|
11 |
+
"vision_width": 64,
|
12 |
+
"input_size": 1024,
|
13 |
+
"molecule_layers": 4,
|
14 |
+
"hidden_dim": 1024,
|
15 |
+
"adapt": true,
|
16 |
+
"backbone_architecture": ["ResNet-pre", "MLP"]
|
17 |
+
}
|
src/training/model_configs/RN50.json
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_block": "bottleneck",
|
4 |
+
"input_channels": 5,
|
5 |
+
"vision_layers": [
|
6 |
+
3,
|
7 |
+
4,
|
8 |
+
6,
|
9 |
+
3
|
10 |
+
],
|
11 |
+
"vision_width": 64,
|
12 |
+
"input_size": 1024,
|
13 |
+
"molecule_layers": 4,
|
14 |
+
"hidden_dim": 1024
|
15 |
+
}
|
src/training/model_configs/RN50x16.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"image_resolution": 384,
|
4 |
+
"vision_layers": [
|
5 |
+
6,
|
6 |
+
8,
|
7 |
+
18,
|
8 |
+
8
|
9 |
+
],
|
10 |
+
"vision_width": 96,
|
11 |
+
"vision_patch_size": null,
|
12 |
+
"context_length": 77,
|
13 |
+
"vocab_size": 49408,
|
14 |
+
"transformer_width": 768,
|
15 |
+
"transformer_heads": 12,
|
16 |
+
"transformer_layers": 12
|
17 |
+
}
|
src/training/model_configs/RN50x4.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 640,
|
3 |
+
"image_resolution": 288,
|
4 |
+
"vision_layers": [
|
5 |
+
4,
|
6 |
+
6,
|
7 |
+
10,
|
8 |
+
6
|
9 |
+
],
|
10 |
+
"vision_width": 80,
|
11 |
+
"vision_patch_size": null,
|
12 |
+
"context_length": 77,
|
13 |
+
"vocab_size": 49408,
|
14 |
+
"transformer_width": 640,
|
15 |
+
"transformer_heads": 10,
|
16 |
+
"transformer_layers": 12
|
17 |
+
}
|
src/training/model_configs/ViT-B-16.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"image_resolution": 224,
|
4 |
+
"vision_layers": 12,
|
5 |
+
"vision_width": 768,
|
6 |
+
"vision_patch_size": 16,
|
7 |
+
"context_length": 77,
|
8 |
+
"vocab_size": 49408,
|
9 |
+
"transformer_width": 512,
|
10 |
+
"transformer_heads": 8,
|
11 |
+
"transformer_layers": 12
|
12 |
+
}
|
src/training/model_configs/ViT-B-32.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"image_resolution": 224,
|
4 |
+
"vision_layers": 12,
|
5 |
+
"vision_width": 768,
|
6 |
+
"vision_patch_size": 32,
|
7 |
+
"context_length": 77,
|
8 |
+
"vocab_size": 49408,
|
9 |
+
"transformer_width": 512,
|
10 |
+
"transformer_heads": 8,
|
11 |
+
"transformer_layers": 12
|
12 |
+
}
|