osanseviero JamesXu commited on
Commit
67a8158
·
0 Parent(s):

Duplicate from shi-labs/Versatile-Diffusion

Browse files

Co-authored-by: Xingqian Xu <[email protected]>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +37 -0
  2. .gitignore +7 -0
  3. README.md +15 -0
  4. app.py +729 -0
  5. assets/benz.jpg +3 -0
  6. assets/boy_and_girl.jpg +3 -0
  7. assets/church.jpg +3 -0
  8. assets/firework.jpg +3 -0
  9. assets/ghibli.jpg +3 -0
  10. assets/horse.png +3 -0
  11. assets/house_by_lake.jpg +3 -0
  12. assets/matisse.jpg +3 -0
  13. assets/night_light.jpg +3 -0
  14. assets/penguin.png +3 -0
  15. assets/san_diego.jpg +3 -0
  16. assets/scream.jpg +3 -0
  17. assets/space.jpg +3 -0
  18. assets/tiger.jpg +3 -0
  19. assets/train.jpg +3 -0
  20. assets/vermeer.jpg +3 -0
  21. configs/model/clip.yaml +50 -0
  22. configs/model/openai_unet.yaml +72 -0
  23. configs/model/optimus.yaml +102 -0
  24. configs/model/sd.yaml +68 -0
  25. configs/model/vd.yaml +61 -0
  26. lib/__init__.py +0 -0
  27. lib/cfg_helper.py +664 -0
  28. lib/cfg_holder.py +28 -0
  29. lib/data_factory/__init__.py +6 -0
  30. lib/data_factory/common/__init__.py +6 -0
  31. lib/data_factory/common/ds_base.py +272 -0
  32. lib/data_factory/common/ds_estimator.py +39 -0
  33. lib/data_factory/common/ds_formatter.py +37 -0
  34. lib/data_factory/common/ds_loader.py +96 -0
  35. lib/data_factory/common/ds_sampler.py +273 -0
  36. lib/data_factory/common/ds_transform.py +177 -0
  37. lib/evaluator/__init__.py +1 -0
  38. lib/evaluator/eva_base.py +292 -0
  39. lib/evaluator/eva_null.py +25 -0
  40. lib/experiments/__init__.py +0 -0
  41. lib/experiments/sd_default.py +441 -0
  42. lib/log_service.py +166 -0
  43. lib/model_zoo/__init__.py +4 -0
  44. lib/model_zoo/attention.py +435 -0
  45. lib/model_zoo/autoencoder.py +428 -0
  46. lib/model_zoo/bert.py +142 -0
  47. lib/model_zoo/clip.py +226 -0
  48. lib/model_zoo/clip_justin/__init__.py +1 -0
  49. lib/model_zoo/clip_justin/clip.py +237 -0
  50. lib/model_zoo/clip_justin/model.py +436 -0
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.pth filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
37
+ *.jpg filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ .vscode/
3
+ src/
4
+ data/
5
+ data
6
+ log/
7
+ log
README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Versatile Diffusion
3
+ emoji: null
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 3.9.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ python_version: 3.8.5
12
+ duplicated_from: shi-labs/Versatile-Diffusion
13
+ ---
14
+
15
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import PIL
4
+ from PIL import Image
5
+ from pathlib import Path
6
+ import numpy as np
7
+ import numpy.random as npr
8
+ from contextlib import nullcontext
9
+
10
+ import torch
11
+ import torchvision.transforms as tvtrans
12
+ from lib.cfg_helper import model_cfg_bank
13
+ from lib.model_zoo import get_model
14
+ from lib.model_zoo.ddim_vd import DDIMSampler_VD, DDIMSampler_VD_DualContext
15
+ from lib.model_zoo.ddim_dualcontext import DDIMSampler_DualContext
16
+
17
+ from lib.experiments.sd_default import color_adjust
18
+
19
+ n_sample_image = 2
20
+ n_sample_text = 4
21
+ cache_examples = True
22
+
23
+ class vd_inference(object):
24
+ def __init__(self, type='official'):
25
+ if type in ['dc', '2-flow']:
26
+ cfgm_name = 'vd_dc_noema'
27
+ sampler = DDIMSampler_DualContext
28
+ pth = 'pretrained/vd-dc.pth'
29
+ elif type in ['official', '4-flow']:
30
+ cfgm_name = 'vd_noema'
31
+ sampler = DDIMSampler_VD
32
+ pth = 'pretrained/vd-official.pth'
33
+ cfgm = model_cfg_bank()(cfgm_name)
34
+ net = get_model()(cfgm)
35
+
36
+ sd = torch.load(pth, map_location='cpu')
37
+ net.load_state_dict(sd, strict=False)
38
+
39
+ self.use_cuda = torch.cuda.is_available()
40
+ if self.use_cuda:
41
+ net.to('cuda')
42
+ self.model_name = cfgm_name
43
+ self.net = net
44
+ self.sampler = sampler(net)
45
+
46
+ def regularize_image(self, x):
47
+ BICUBIC = PIL.Image.Resampling.BICUBIC
48
+ if isinstance(x, str):
49
+ x = Image.open(x).resize([512, 512], resample=BICUBIC)
50
+ x = tvtrans.ToTensor()(x)
51
+ elif isinstance(x, PIL.Image.Image):
52
+ x = x.resize([512, 512], resample=BICUBIC)
53
+ x = tvtrans.ToTensor()(x)
54
+ elif isinstance(x, np.ndarray):
55
+ x = PIL.Image.fromarray(x).resize([512, 512], resample=BICUBIC)
56
+ x = tvtrans.ToTensor()(x)
57
+ elif isinstance(x, torch.Tensor):
58
+ pass
59
+ else:
60
+ assert False, 'Unknown image type'
61
+
62
+ assert (x.shape[1]==512) & (x.shape[2]==512), \
63
+ 'Wrong image size'
64
+ if self.use_cuda:
65
+ x = x.to('cuda')
66
+ return x
67
+
68
+ def decode(self, z, xtype, ctype, color_adj='None', color_adj_to=None):
69
+ net = self.net
70
+ if xtype == 'image':
71
+ x = net.autokl_decode(z)
72
+
73
+ color_adj_flag = (color_adj!='None') and (color_adj is not None)
74
+ color_adj_simple = color_adj=='Simple'
75
+ color_adj_keep_ratio = 0.5
76
+
77
+ if color_adj_flag and (ctype=='vision'):
78
+ x_adj = []
79
+ for xi in x:
80
+ color_adj_f = color_adjust(ref_from=(xi+1)/2, ref_to=color_adj_to)
81
+ xi_adj = color_adj_f((xi+1)/2, keep=color_adj_keep_ratio, simple=color_adj_simple)
82
+ x_adj.append(xi_adj)
83
+ x = x_adj
84
+ else:
85
+ x = torch.clamp((x+1.0)/2.0, min=0.0, max=1.0)
86
+ x = [tvtrans.ToPILImage()(xi) for xi in x]
87
+ return x
88
+
89
+ elif xtype == 'text':
90
+ prompt_temperature = 1.0
91
+ prompt_merge_same_adj_word = True
92
+ x = net.optimus_decode(z, temperature=prompt_temperature)
93
+ if prompt_merge_same_adj_word:
94
+ xnew = []
95
+ for xi in x:
96
+ xi_split = xi.split()
97
+ xinew = []
98
+ for idxi, wi in enumerate(xi_split):
99
+ if idxi!=0 and wi==xi_split[idxi-1]:
100
+ continue
101
+ xinew.append(wi)
102
+ xnew.append(' '.join(xinew))
103
+ x = xnew
104
+ return x
105
+
106
+ def inference(self, xtype, cin, ctype, scale=7.5, n_samples=None, color_adj=None,):
107
+ net = self.net
108
+ sampler = self.sampler
109
+ ddim_steps = 50
110
+ ddim_eta = 0.0
111
+
112
+ if xtype == 'image':
113
+ n_samples = n_sample_image if n_samples is None else n_samples
114
+ elif xtype == 'text':
115
+ n_samples = n_sample_text if n_samples is None else n_samples
116
+
117
+ if ctype in ['prompt', 'text']:
118
+ c = net.clip_encode_text(n_samples * [cin])
119
+ u = None
120
+ if scale != 1.0:
121
+ u = net.clip_encode_text(n_samples * [""])
122
+
123
+ elif ctype in ['vision', 'image']:
124
+ cin = self.regularize_image(cin)
125
+ ctemp = cin*2 - 1
126
+ ctemp = ctemp[None].repeat(n_samples, 1, 1, 1)
127
+ c = net.clip_encode_vision(ctemp)
128
+ u = None
129
+ if scale != 1.0:
130
+ dummy = torch.zeros_like(ctemp)
131
+ u = net.clip_encode_vision(dummy)
132
+
133
+ if xtype == 'image':
134
+ h, w = [512, 512]
135
+ shape = [n_samples, 4, h//8, w//8]
136
+ z, _ = sampler.sample(
137
+ steps=ddim_steps,
138
+ shape=shape,
139
+ conditioning=c,
140
+ unconditional_guidance_scale=scale,
141
+ unconditional_conditioning=u,
142
+ xtype=xtype, ctype=ctype,
143
+ eta=ddim_eta,
144
+ verbose=False,)
145
+ x = self.decode(z, xtype, ctype, color_adj=color_adj, color_adj_to=cin)
146
+ return x
147
+
148
+ elif xtype == 'text':
149
+ n = 768
150
+ shape = [n_samples, n]
151
+ z, _ = sampler.sample(
152
+ steps=ddim_steps,
153
+ shape=shape,
154
+ conditioning=c,
155
+ unconditional_guidance_scale=scale,
156
+ unconditional_conditioning=u,
157
+ xtype=xtype, ctype=ctype,
158
+ eta=ddim_eta,
159
+ verbose=False,)
160
+ x = self.decode(z, xtype, ctype)
161
+ return x
162
+
163
+ def application_disensemble(self, cin, n_samples=None, level=0, color_adj=None,):
164
+ net = self.net
165
+ scale = 7.5
166
+ sampler = self.sampler
167
+ ddim_steps = 50
168
+ ddim_eta = 0.0
169
+ n_samples = n_sample_image if n_samples is None else n_samples
170
+
171
+ cin = self.regularize_image(cin)
172
+ ctemp = cin*2 - 1
173
+ ctemp = ctemp[None].repeat(n_samples, 1, 1, 1)
174
+ c = net.clip_encode_vision(ctemp)
175
+ u = None
176
+ if scale != 1.0:
177
+ dummy = torch.zeros_like(ctemp)
178
+ u = net.clip_encode_vision(dummy)
179
+
180
+ if level == 0:
181
+ pass
182
+ else:
183
+ c_glb = c[:, 0:1]
184
+ c_loc = c[:, 1: ]
185
+ u_glb = u[:, 0:1]
186
+ u_loc = u[:, 1: ]
187
+
188
+ if level == -1:
189
+ c_loc = self.remove_low_rank(c_loc, demean=True, q=50, q_remove=1)
190
+ u_loc = self.remove_low_rank(u_loc, demean=True, q=50, q_remove=1)
191
+ if level == -2:
192
+ c_loc = self.remove_low_rank(c_loc, demean=True, q=50, q_remove=2)
193
+ u_loc = self.remove_low_rank(u_loc, demean=True, q=50, q_remove=2)
194
+ if level == 1:
195
+ c_loc = self.find_low_rank(c_loc, demean=True, q=10)
196
+ u_loc = self.find_low_rank(u_loc, demean=True, q=10)
197
+ if level == 2:
198
+ c_loc = self.find_low_rank(c_loc, demean=True, q=2)
199
+ u_loc = self.find_low_rank(u_loc, demean=True, q=2)
200
+
201
+ c = torch.cat([c_glb, c_loc], dim=1)
202
+ u = torch.cat([u_glb, u_loc], dim=1)
203
+
204
+ h, w = [512, 512]
205
+ shape = [n_samples, 4, h//8, w//8]
206
+ z, _ = sampler.sample(
207
+ steps=ddim_steps,
208
+ shape=shape,
209
+ conditioning=c,
210
+ unconditional_guidance_scale=scale,
211
+ unconditional_conditioning=u,
212
+ xtype='image', ctype='vision',
213
+ eta=ddim_eta,
214
+ verbose=False,)
215
+ x = self.decode(z, 'image', 'vision', color_adj=color_adj, color_adj_to=cin)
216
+ return x
217
+
218
+ def find_low_rank(self, x, demean=True, q=20, niter=10):
219
+ if demean:
220
+ x_mean = x.mean(-1, keepdim=True)
221
+ x_input = x - x_mean
222
+ else:
223
+ x_input = x
224
+
225
+ u, s, v = torch.pca_lowrank(x_input, q=q, center=False, niter=niter)
226
+ ss = torch.stack([torch.diag(si) for si in s])
227
+ x_lowrank = torch.bmm(torch.bmm(u, ss), torch.permute(v, [0, 2, 1]))
228
+
229
+ if demean:
230
+ x_lowrank += x_mean
231
+ return x_lowrank
232
+
233
+ def remove_low_rank(self, x, demean=True, q=20, niter=10, q_remove=10):
234
+ if demean:
235
+ x_mean = x.mean(-1, keepdim=True)
236
+ x_input = x - x_mean
237
+ else:
238
+ x_input = x
239
+
240
+ u, s, v = torch.pca_lowrank(x_input, q=q, center=False, niter=niter)
241
+ s[:, 0:q_remove] = 0
242
+ ss = torch.stack([torch.diag(si) for si in s])
243
+ x_lowrank = torch.bmm(torch.bmm(u, ss), torch.permute(v, [0, 2, 1]))
244
+
245
+ if demean:
246
+ x_lowrank += x_mean
247
+ return x_lowrank
248
+
249
+ def application_dualguided(self, cim, ctx, n_samples=None, mixing=0.5, color_adj=None, ):
250
+ net = self.net
251
+ scale = 7.5
252
+ sampler = DDIMSampler_VD_DualContext(net)
253
+ ddim_steps = 50
254
+ ddim_eta = 0.0
255
+ n_samples = n_sample_image if n_samples is None else n_samples
256
+
257
+ ctemp0 = self.regularize_image(cim)
258
+ ctemp1 = ctemp0*2 - 1
259
+ ctemp1 = ctemp1[None].repeat(n_samples, 1, 1, 1)
260
+ cim = net.clip_encode_vision(ctemp1)
261
+ uim = None
262
+ if scale != 1.0:
263
+ dummy = torch.zeros_like(ctemp1)
264
+ uim = net.clip_encode_vision(dummy)
265
+
266
+ ctx = net.clip_encode_text(n_samples * [ctx])
267
+ utx = None
268
+ if scale != 1.0:
269
+ utx = net.clip_encode_text(n_samples * [""])
270
+
271
+ h, w = [512, 512]
272
+ shape = [n_samples, 4, h//8, w//8]
273
+
274
+ z, _ = sampler.sample_dc(
275
+ steps=ddim_steps,
276
+ shape=shape,
277
+ first_conditioning=[uim, cim],
278
+ second_conditioning=[utx, ctx],
279
+ unconditional_guidance_scale=scale,
280
+ xtype='image',
281
+ first_ctype='vision',
282
+ second_ctype='prompt',
283
+ eta=ddim_eta,
284
+ verbose=False,
285
+ mixed_ratio=(1-mixing), )
286
+ x = self.decode(z, 'image', 'vision', color_adj=color_adj, color_adj_to=ctemp0)
287
+ return x
288
+
289
+ def application_i2t2i(self, cim, ctx_n, ctx_p, n_samples=None, color_adj=None,):
290
+ net = self.net
291
+ scale = 7.5
292
+ sampler = DDIMSampler_VD_DualContext(net)
293
+ ddim_steps = 50
294
+ ddim_eta = 0.0
295
+ prompt_temperature = 1.0
296
+ n_samples = n_sample_image if n_samples is None else n_samples
297
+
298
+ ctemp0 = self.regularize_image(cim)
299
+ ctemp1 = ctemp0*2 - 1
300
+ ctemp1 = ctemp1[None].repeat(n_samples, 1, 1, 1)
301
+ cim = net.clip_encode_vision(ctemp1)
302
+ uim = None
303
+ if scale != 1.0:
304
+ dummy = torch.zeros_like(ctemp1)
305
+ uim = net.clip_encode_vision(dummy)
306
+
307
+ n = 768
308
+ shape = [n_samples, n]
309
+ zt, _ = sampler.sample(
310
+ steps=ddim_steps,
311
+ shape=shape,
312
+ conditioning=cim,
313
+ unconditional_guidance_scale=scale,
314
+ unconditional_conditioning=uim,
315
+ xtype='text', ctype='vision',
316
+ eta=ddim_eta,
317
+ verbose=False,)
318
+ ztn = net.optimus_encode([ctx_n])
319
+ ztp = net.optimus_encode([ctx_p])
320
+
321
+ ztn_norm = ztn / ztn.norm(dim=1)
322
+ zt_proj_mag = torch.matmul(zt, ztn_norm[0])
323
+ zt_perp = zt - zt_proj_mag[:, None] * ztn_norm
324
+ zt_newd = zt_perp + ztp
325
+ ctx_new = net.optimus_decode(zt_newd, temperature=prompt_temperature)
326
+
327
+ ctx_new = net.clip_encode_text(ctx_new)
328
+ ctx_p = net.clip_encode_text([ctx_p])
329
+ ctx_new = torch.cat([ctx_new, ctx_p.repeat(n_samples, 1, 1)], dim=1)
330
+ utx_new = net.clip_encode_text(n_samples * [""])
331
+ utx_new = torch.cat([utx_new, utx_new], dim=1)
332
+
333
+ cim_loc = cim[:, 1: ]
334
+ cim_loc_new = self.find_low_rank(cim_loc, demean=True, q=10)
335
+ cim_new = cim_loc_new
336
+ uim_new = uim[:, 1:]
337
+
338
+ h, w = [512, 512]
339
+ shape = [n_samples, 4, h//8, w//8]
340
+ z, _ = sampler.sample_dc(
341
+ steps=ddim_steps,
342
+ shape=shape,
343
+ first_conditioning=[uim_new, cim_new],
344
+ second_conditioning=[utx_new, ctx_new],
345
+ unconditional_guidance_scale=scale,
346
+ xtype='image',
347
+ first_ctype='vision',
348
+ second_ctype='prompt',
349
+ eta=ddim_eta,
350
+ verbose=False,
351
+ mixed_ratio=0.33, )
352
+
353
+ x = self.decode(z, 'image', 'vision', color_adj=color_adj, color_adj_to=ctemp0)
354
+ return x
355
+
356
+ vd_inference = vd_inference('official')
357
+
358
+ def main(mode,
359
+ image=None,
360
+ prompt=None,
361
+ nprompt=None,
362
+ pprompt=None,
363
+ color_adj=None,
364
+ disentanglement_level=None,
365
+ dual_guided_mixing=None,
366
+ seed=0,):
367
+
368
+ if seed<0:
369
+ seed = 0
370
+ np.random.seed(seed)
371
+ torch.manual_seed(seed+100)
372
+
373
+ if mode == 'Text-to-Image':
374
+ if (prompt is None) or (prompt == ""):
375
+ return None, None
376
+ with torch.no_grad():
377
+ rv = vd_inference.inference(
378
+ xtype = 'image',
379
+ cin = prompt,
380
+ ctype = 'prompt', )
381
+ return rv, None
382
+ elif mode == 'Image-Variation':
383
+ if image is None:
384
+ return None, None
385
+ with torch.no_grad():
386
+ rv = vd_inference.inference(
387
+ xtype = 'image',
388
+ cin = image,
389
+ ctype = 'vision',
390
+ color_adj = color_adj,)
391
+ return rv, None
392
+ elif mode == 'Image-to-Text':
393
+ if image is None:
394
+ return None, None
395
+ with torch.no_grad():
396
+ rv = vd_inference.inference(
397
+ xtype = 'text',
398
+ cin = image,
399
+ ctype = 'vision',)
400
+ return None, '\n'.join(rv)
401
+ elif mode == 'Text-Variation':
402
+ if prompt is None:
403
+ return None, None
404
+ with torch.no_grad():
405
+ rv = vd_inference.inference(
406
+ xtype = 'text',
407
+ cin = prompt,
408
+ ctype = 'prompt',)
409
+ return None, '\n'.join(rv)
410
+ elif mode == 'Disentanglement':
411
+ if image is None:
412
+ return None, None
413
+ with torch.no_grad():
414
+ rv = vd_inference.application_disensemble(
415
+ cin = image,
416
+ level = disentanglement_level,
417
+ color_adj = color_adj,)
418
+ return rv, None
419
+ elif mode == 'Dual-Guided':
420
+ if (image is None) or (prompt is None) or (prompt==""):
421
+ return None, None
422
+ with torch.no_grad():
423
+ rv = vd_inference.application_dualguided(
424
+ cim = image,
425
+ ctx = prompt,
426
+ mixing = dual_guided_mixing,
427
+ color_adj = color_adj,)
428
+ return rv, None
429
+ elif mode == 'Latent-I2T2I':
430
+ if (image is None) or (nprompt is None) or (nprompt=="") \
431
+ or (pprompt is None) or (pprompt==""):
432
+ return None, None
433
+ with torch.no_grad():
434
+ rv = vd_inference.application_i2t2i(
435
+ cim = image,
436
+ ctx_n = nprompt,
437
+ ctx_p = pprompt,
438
+ color_adj = color_adj,)
439
+ return rv, None
440
+ else:
441
+ assert False, "No such mode!"
442
+
443
+ def get_instruction(mode):
444
+ t2i_instruction = ["Generate image from text prompt."]
445
+ i2i_instruction = [
446
+ "Generate image conditioned on reference image.",
447
+ "Color Calibration provide an opinion to adjust image color according to reference image.", ]
448
+ i2t_instruction = ["Generate text from reference image."]
449
+ t2t_instruction = ["Generate text from reference text prompt. (Model insufficiently trained, thus results are still experimental)"]
450
+ dis_instruction = [
451
+ "Generate a variation of reference image that disentangled for semantic or style.",
452
+ "Color Calibration provide an opinion to adjust image color according to reference image.",
453
+ "Disentanglement level controls the level of focus towards semantic (-2, -1) or style (1 2). Level 0 serves as Image-Variation.", ]
454
+ dug_instruction = [
455
+ "Generate image from dual guidance of reference image and text prompt.",
456
+ "Color Calibration provide an opinion to adjust image color according to reference image.",
457
+ "Guidance Mixing provides linear balances between image and text context. (0 towards image, 1 towards text)", ]
458
+ iti_instruction = [
459
+ "Generate image variations via image-to-text, text-latent-editing, and then text-to-image. (Still under exploration)",
460
+ "Color Calibration provide an opinion to adjust image color according to reference image.",
461
+ "Input prompt that will be substract from text/text latent code.",
462
+ "Input prompt that will be added to text/text latent code.", ]
463
+
464
+ if mode == "Text-to-Image":
465
+ return '\n'.join(t2i_instruction)
466
+ elif mode == "Image-Variation":
467
+ return '\n'.join(i2i_instruction)
468
+ elif mode == "Image-to-Text":
469
+ return '\n'.join(i2t_instruction)
470
+ elif mode == "Text-Variation":
471
+ return '\n'.join(t2t_instruction)
472
+ elif mode == "Disentanglement":
473
+ return '\n'.join(dis_instruction)
474
+ elif mode == "Dual-Guided":
475
+ return '\n'.join(dug_instruction)
476
+ elif mode == "Latent-I2T2I":
477
+ return '\n'.join(iti_instruction)
478
+
479
+ #############
480
+ # Interface #
481
+ #############
482
+
483
+ if True:
484
+ img_output = gr.Gallery(label="Image Result").style(grid=n_sample_image)
485
+ txt_output = gr.Textbox(lines=4, label='Text Result', visible=False)
486
+
487
+ with gr.Blocks() as demo:
488
+ gr.HTML(
489
+ """
490
+ <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
491
+ <h1 style="font-weight: 900; font-size: 3rem;">
492
+ Versatile Diffusion
493
+ </h1>
494
+ <br>
495
+ <h2 style="font-weight: 450; font-size: 1rem;">
496
+ We built <b>Versatile Diffusion (VD), the first unified multi-flow multimodal diffusion framework</b>, as a step towards <b>Universal Generative AI</b>.
497
+ VD can natively support image-to-text, image-variation, text-to-image, and text-variation,
498
+ and can be further extended to other applications such as
499
+ semantic-style disentanglement, image-text dual-guided generation, latent image-to-text-to-image editing, and more.
500
+ Future versions will support more modalities such as speech, music, video and 3D.
501
+ </h2>
502
+ <br>
503
+ <h3>Xingqian Xu, Atlas Wang, Eric Zhang, Kai Wang,
504
+ and <a href="https://www.humphreyshi.com/home">Humphrey Shi</a>
505
+ [<a href="https://arxiv.org/abs/2211.08332" style="color:blue;">arXiv</a>]
506
+ [<a href="https://github.com/SHI-Labs/Versatile-Diffusion" style="color:blue;">GitHub</a>]
507
+ </h3>
508
+ </div>
509
+ """)
510
+ mode_input = gr.Radio([
511
+ "Text-to-Image", "Image-Variation", "Image-to-Text", "Text-Variation",
512
+ "Disentanglement", "Dual-Guided", "Latent-I2T2I"], value='Text-to-Image', label="VD Flows and Applications")
513
+
514
+ instruction = gr.Textbox(get_instruction("Text-to-Image"), label='Info')
515
+
516
+ with gr.Row():
517
+ with gr.Column():
518
+ img_input = gr.Image(label='Image Input', visible=False)
519
+ txt_input = gr.Textbox(lines=4, placeholder="Input prompt...", label='Text Input')
520
+ ntxt_input = gr.Textbox(label='Remove Prompt', visible=False)
521
+ ptxt_input = gr.Textbox(label='Add Prompt', visible=False)
522
+ coladj_input = gr.Radio(["None", "Simple"], value='Simple', label="Color Calibration", visible=False)
523
+ dislvl_input = gr.Slider(-2, 2, value=0, step=1, label="Disentanglement level", visible=False)
524
+ dguide_input = gr.Slider(0, 1, value=0.5, step=0.01, label="Guidance Mixing", visible=False)
525
+ seed_input = gr.Number(100, label="Seed", precision=0)
526
+
527
+ btn = gr.Button("Run")
528
+ btn.click(
529
+ main,
530
+ inputs=[
531
+ mode_input,
532
+ img_input,
533
+ txt_input,
534
+ ntxt_input,
535
+ ptxt_input,
536
+ coladj_input,
537
+ dislvl_input,
538
+ dguide_input,
539
+ seed_input, ],
540
+ outputs=[img_output, txt_output])
541
+
542
+ with gr.Column():
543
+ img_output.render()
544
+ txt_output.render()
545
+
546
+ example_mode = [
547
+ "Text-to-Image",
548
+ "Image-Variation",
549
+ "Image-to-Text",
550
+ "Text-Variation",
551
+ "Disentanglement",
552
+ "Dual-Guided",
553
+ "Latent-I2T2I"]
554
+
555
+ def get_example(mode):
556
+ if mode == 'Text-to-Image':
557
+ case = [
558
+ ['a dream of a village in china, by Caspar David Friedrich, matte painting trending on artstation HQ', 23],
559
+ ['a beautiful grand nebula in the universe', 24],
560
+ ['heavy arms gundam penguin mech', 25],
561
+ ]
562
+ elif mode == "Image-Variation":
563
+ case = [
564
+ ['assets/space.jpg', 'None', 26],
565
+ ['assets/train.jpg', 'Simple', 27],
566
+ ]
567
+ elif mode == "Image-to-Text":
568
+ case = [
569
+ ['assets/boy_and_girl.jpg' , 28],
570
+ ['assets/house_by_lake.jpg', 29],
571
+ ]
572
+ elif mode == "Text-Variation":
573
+ case = [
574
+ ['a dream of a village in china, by Caspar David Friedrich, matte painting trending on artstation HQ' , 32],
575
+ ['a beautiful grand nebula in the universe' , 33],
576
+ ['heavy arms gundam penguin mech', 34],
577
+ ]
578
+ elif mode == "Disentanglement":
579
+ case = [
580
+ ['assets/vermeer.jpg', 'Simple', -2, 30],
581
+ ['assets/matisse.jpg', 'Simple', 2, 31],
582
+ ]
583
+ elif mode == "Dual-Guided":
584
+ case = [
585
+ ['assets/benz.jpg', 'cyberpunk 2077', 'Simple', 0.75, 22],
586
+ ['assets/vermeer.jpg', 'a girl with a diamond necklace', 'Simple', 0.66, 21],
587
+ ]
588
+ elif mode == "Latent-I2T2I":
589
+ case = [
590
+ ['assets/ghibli.jpg', 'white house', 'tall castle', 'Simple', 20],
591
+ ['assets/matisse.jpg', 'fruits and bottles on the table', 'flowers on the table', 'Simple', 21],
592
+ ]
593
+ else:
594
+ raise ValueError
595
+ case = [[mode] + casei for casei in case]
596
+ return case
597
+
598
+ def get_example_iof(mode):
599
+ if mode == 'Text-to-Image':
600
+ inps = [txt_input, seed_input]
601
+ oups = [img_output]
602
+ fn = lambda m, x, y: \
603
+ main(mode=m, prompt=x, seed=y)[0]
604
+ elif mode == "Image-Variation":
605
+ inps = [img_input, coladj_input, seed_input]
606
+ oups = [img_output]
607
+ fn = lambda m, x, y, z: \
608
+ main(mode=m, image=x, color_adj=y, seed=z)[0]
609
+ elif mode == "Image-to-Text":
610
+ inps = [img_input, seed_input]
611
+ oups = [txt_output]
612
+ fn = lambda m, x, y: \
613
+ main(mode=m, image=x, seed=y)[1]
614
+ elif mode == "Text-Variation":
615
+ inps = [txt_input, seed_input]
616
+ oups = [txt_output]
617
+ fn = lambda m, x, y: \
618
+ main(mode=m, prompt=x, seed=y)[1]
619
+ elif mode == "Disentanglement":
620
+ inps = [img_input, coladj_input, dislvl_input, seed_input]
621
+ oups = [img_output]
622
+ fn = lambda m, x, y, z, w: \
623
+ main(mode=m, image=x, color_adj=y, disentanglement_level=z, seed=w)[0]
624
+ elif mode == "Dual-Guided":
625
+ inps = [img_input, txt_input, coladj_input, dguide_input, seed_input]
626
+ oups = [img_output]
627
+ fn = lambda m, x, y, z, w, u: \
628
+ main(mode=m, image=x, prompt=y, color_adj=z, dual_guided_mixing=w, seed=u)[0]
629
+ elif mode == "Latent-I2T2I":
630
+ inps = [img_input, ntxt_input, ptxt_input, coladj_input, seed_input]
631
+ oups = [img_output]
632
+ fn = lambda m, x, y, z, w, u: \
633
+ main(mode=m, image=x, nprompt=y, pprompt=z, color_adj=w, seed=u)[0]
634
+ else:
635
+ raise ValueError
636
+ return [mode_input]+inps, oups, fn
637
+
638
+ with gr.Row():
639
+ for emode in example_mode[0:4]:
640
+ with gr.Column():
641
+ gr.Examples(
642
+ label=emode+' Examples',
643
+ examples=get_example(emode),
644
+ inputs=get_example_iof(emode)[0],
645
+ outputs=get_example_iof(emode)[1],
646
+ fn = get_example_iof(emode)[2],
647
+ cache_examples=cache_examples),
648
+ with gr.Row():
649
+ for emode in example_mode[4:7]:
650
+ with gr.Column():
651
+ gr.Examples(
652
+ label=emode+' Examples',
653
+ examples=get_example(emode),
654
+ inputs=get_example_iof(emode)[0],
655
+ outputs=get_example_iof(emode)[1],
656
+ fn = get_example_iof(emode)[2],
657
+ cache_examples=cache_examples),
658
+
659
+ mode_input.change(
660
+ fn=lambda x: gr.update(value=get_instruction(x)),
661
+ inputs=mode_input,
662
+ outputs=instruction,)
663
+
664
+ mode_input.change(
665
+ fn=lambda x: gr.update(visible=(x not in ['Text-to-Image', 'Text-Variation'])),
666
+ inputs=mode_input,
667
+ outputs=img_input,)
668
+
669
+ mode_input.change(
670
+ fn=lambda x: gr.update(visible=(x in ['Text-to-Image', 'Text-Variation', 'Dual-Guided'])),
671
+ inputs=mode_input,
672
+ outputs=txt_input,)
673
+
674
+ mode_input.change(
675
+ fn=lambda x: gr.update(visible=(x in ['Latent-I2T2I'])),
676
+ inputs=mode_input,
677
+ outputs=ntxt_input,)
678
+ mode_input.change(
679
+ fn=lambda x: gr.update(visible=(x in ['Latent-I2T2I'])),
680
+ inputs=mode_input,
681
+ outputs=ptxt_input,)
682
+
683
+ mode_input.change(
684
+ fn=lambda x: gr.update(visible=(x not in ['Text-to-Image', 'Image-to-Text', 'Text-Variation'])),
685
+ inputs=mode_input,
686
+ outputs=coladj_input,)
687
+
688
+ mode_input.change(
689
+ fn=lambda x: gr.update(visible=(x=='Disentanglement')),
690
+ inputs=mode_input,
691
+ outputs=dislvl_input,)
692
+
693
+ mode_input.change(
694
+ fn=lambda x: gr.update(visible=(x=='Dual-Guided')),
695
+ inputs=mode_input,
696
+ outputs=dguide_input,)
697
+
698
+ mode_input.change(
699
+ fn=lambda x: gr.update(visible=(x not in ['Image-to-Text', 'Text-Variation'])),
700
+ inputs=mode_input,
701
+ outputs=img_output,)
702
+ mode_input.change(
703
+ fn=lambda x: gr.update(visible=(x in ['Image-to-Text', 'Text-Variation'])),
704
+ inputs=mode_input,
705
+ outputs=txt_output,)
706
+
707
+ gr.HTML(
708
+ """
709
+ <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
710
+ <h3>
711
+ <b>Caution</b>:
712
+ We would like the raise the awareness of users of this demo of its potential issues and concerns.
713
+ Like previous large foundation models, Versatile Diffusion could be problematic in some cases, partially due to the imperfect training data and pretrained network (VAEs / context encoders) with limited scope.
714
+ In its future research phase, VD may do better on tasks such as text-to-image, image-to-text, etc., with the help of more powerful VAEs, more sophisticated network designs, and more cleaned data.
715
+ So far, we keep all features available for research testing both to show the great potential of the VD framework and to collect important feedback to improve the model in the future.
716
+ We welcome researchers and users to report issues with the HuggingFace community discussion feature or email the authors.
717
+ </h3>
718
+ <br>
719
+ <h3>
720
+ <b>Biases and content acknowledgement</b>:
721
+ Beware that VD may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography, and violence.
722
+ VD was trained on the LAION-2B dataset, which scraped non-curated online images and text, and may contained unintended exceptions as we removed illegal content.
723
+ VD in this demo is meant only for research purposes.
724
+ </h3>
725
+ </div>
726
+ """)
727
+
728
+ # demo.launch(share=True)
729
+ demo.launch(debug=True)
assets/benz.jpg ADDED

Git LFS Details

  • SHA256: bdfdfb603af2179878013b08500fdc78c5f20d70efd581f2ebfed1b65321f9a2
  • Pointer size: 131 Bytes
  • Size of remote file: 204 kB
assets/boy_and_girl.jpg ADDED

Git LFS Details

  • SHA256: aba3f4834a4f82fb65ff8e6c5e5a1b60d248d2e83d97321b98a0d24ba999390c
  • Pointer size: 131 Bytes
  • Size of remote file: 139 kB
assets/church.jpg ADDED

Git LFS Details

  • SHA256: ec3be4a83b1ceb43cfee1c5bd125f564e0b42a71c440e731fa9cecc2b761263d
  • Pointer size: 131 Bytes
  • Size of remote file: 338 kB
assets/firework.jpg ADDED

Git LFS Details

  • SHA256: 6040aeca347b2896de63b3bf9145e307ad06fa4ab0435609e1d7df5587c29bd6
  • Pointer size: 131 Bytes
  • Size of remote file: 279 kB
assets/ghibli.jpg ADDED

Git LFS Details

  • SHA256: 153e34326ce625f2a6c41d6922549ad690b63d8e18de43532e7fd9808cb9de8b
  • Pointer size: 131 Bytes
  • Size of remote file: 145 kB
assets/horse.png ADDED

Git LFS Details

  • SHA256: 27c5ba007e2984f2e8128df6418c780fefcbd940025ccece14a5a13894065457
  • Pointer size: 131 Bytes
  • Size of remote file: 395 kB
assets/house_by_lake.jpg ADDED

Git LFS Details

  • SHA256: 3d3dcc9f8d8eb90b69fb0a17967440b960bb1d545bcf85de37c4d08f9e5d4606
  • Pointer size: 131 Bytes
  • Size of remote file: 189 kB
assets/matisse.jpg ADDED

Git LFS Details

  • SHA256: ea0428092cbca5224b72a3665c140e96142b5df9c78b36b66f910f42093ecd4f
  • Pointer size: 131 Bytes
  • Size of remote file: 271 kB
assets/night_light.jpg ADDED

Git LFS Details

  • SHA256: 5103ce525e00f0f8ff3c83bcbf954ebda5deb869377a8ccd2b5b6362f7b0aa4a
  • Pointer size: 131 Bytes
  • Size of remote file: 213 kB
assets/penguin.png ADDED

Git LFS Details

  • SHA256: e22e87eec01455b342a849d868ea6cf893b8ae7d81da54eba2f620dbccf972ac
  • Pointer size: 131 Bytes
  • Size of remote file: 147 kB
assets/san_diego.jpg ADDED

Git LFS Details

  • SHA256: 491e93d1b0e99ae2223d85beb4cc98aa790c377b51a938721c3d0c62645a81e4
  • Pointer size: 131 Bytes
  • Size of remote file: 235 kB
assets/scream.jpg ADDED

Git LFS Details

  • SHA256: e154dbe35cb10c4f65c022e97ba9d6ccd7f6ebf3285ff56ebcd9c43b0246e309
  • Pointer size: 131 Bytes
  • Size of remote file: 246 kB
assets/space.jpg ADDED

Git LFS Details

  • SHA256: 7cb01b250297f088ecb1310d746a18b141ab26cd6f3f46e41c52285bb4c7e3d4
  • Pointer size: 131 Bytes
  • Size of remote file: 236 kB
assets/tiger.jpg ADDED

Git LFS Details

  • SHA256: a4b58a11be073fad21a218bcf6478a4da61532b8520176a6454542eb9368081d
  • Pointer size: 131 Bytes
  • Size of remote file: 272 kB
assets/train.jpg ADDED

Git LFS Details

  • SHA256: 50b45524dc627d0042ed789e4495250e71aae7f2935b9a0879d09cf73d8aff37
  • Pointer size: 131 Bytes
  • Size of remote file: 310 kB
assets/vermeer.jpg ADDED

Git LFS Details

  • SHA256: d884ddfe302572f6c4eb8607942cc59807b3dc8321f27ff9358b8e5a3657d015
  • Pointer size: 130 Bytes
  • Size of remote file: 65.5 kB
configs/model/clip.yaml ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ clip:
3
+ symbol: clip
4
+ args: {}
5
+
6
+ clip_frozen:
7
+ super_cfg: clip
8
+ type: clip_frozen
9
+ args: {}
10
+
11
+ clip_text_frozen:
12
+ super_cfg: clip
13
+ type: clip_text_frozen
14
+ args: {}
15
+
16
+ clip_vision_frozen:
17
+ super_cfg: clip
18
+ type: clip_vision_frozen
19
+ args: {}
20
+
21
+ ############################
22
+ # clip with focused encode #
23
+ ############################
24
+
25
+ clip_frozen_encode_text:
26
+ super_cfg: clip
27
+ type: clip_frozen
28
+ args:
29
+ encode_type : encode_text
30
+
31
+ clip_frozen_encode_vision:
32
+ super_cfg: clip
33
+ type: clip_frozen
34
+ args:
35
+ encode_type : encode_vision
36
+
37
+ clip_frozen_encode_text_noproj:
38
+ super_cfg: clip
39
+ type: clip_frozen
40
+ args:
41
+ encode_type : encode_text_noproj
42
+
43
+ #####################################
44
+ # clip vision forzen justin version #
45
+ #####################################
46
+
47
+ clip_vision_frozen_justin:
48
+ super_cfg: clip
49
+ type: clip_vision_frozen_justin
50
+ args: {}
configs/model/openai_unet.yaml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ openai_unet_sd:
2
+ type: openai_unet
3
+ args:
4
+ image_size: null # no use
5
+ in_channels: 4
6
+ out_channels: 4
7
+ model_channels: 320
8
+ attention_resolutions: [ 4, 2, 1 ]
9
+ num_res_blocks: [ 2, 2, 2, 2 ]
10
+ channel_mult: [ 1, 2, 4, 4 ]
11
+ # disable_self_attentions: [ False, False, False, False ] # converts the self-attention to a cross-attention layer if true
12
+ num_heads: 8
13
+ use_spatial_transformer: True
14
+ transformer_depth: 1
15
+ context_dim: 768
16
+ use_checkpoint: True
17
+ legacy: False
18
+
19
+ openai_unet_dual_context:
20
+ super_cfg: openai_unet_sd
21
+ type: openai_unet_dual_context
22
+
23
+ ########################
24
+ # Code cleaned version #
25
+ ########################
26
+
27
+ openai_unet_2d:
28
+ type: openai_unet_2d
29
+ args:
30
+ input_channels: 4
31
+ model_channels: 320
32
+ output_channels: 4
33
+ num_noattn_blocks: [ 2, 2, 2, 2 ]
34
+ channel_mult: [ 1, 2, 4, 4 ]
35
+ with_attn: [true, true, true, false]
36
+ num_heads: 8
37
+ context_dim: 768
38
+ use_checkpoint: True
39
+
40
+ openai_unet_0d:
41
+ type: openai_unet_0d
42
+ args:
43
+ input_channels: 768
44
+ model_channels: 320
45
+ output_channels: 768
46
+ num_noattn_blocks: [ 2, 2, 2, 2 ]
47
+ channel_mult: [ 1, 2, 4, 4 ]
48
+ with_attn: [true, true, true, false]
49
+ num_heads: 8
50
+ context_dim: 768
51
+ use_checkpoint: True
52
+
53
+ openai_unet_0dmd:
54
+ type: openai_unet_0dmd
55
+ args:
56
+ input_channels: 768
57
+ model_channels: 320
58
+ output_channels: 768
59
+ num_noattn_blocks: [ 2, 2, 2, 2 ]
60
+ channel_mult: [ 1, 2, 4, 4 ]
61
+ second_dim: [ 4, 4, 4, 4 ]
62
+ with_attn: [true, true, true, false]
63
+ num_heads: 8
64
+ context_dim: 768
65
+ use_checkpoint: True
66
+
67
+ openai_unet_vd:
68
+ type: openai_unet_vd
69
+ args:
70
+ unet_image_cfg: MODEL(openai_unet_2d)
71
+ unet_test_cfg: MODEL(openai_unet_0dmd)
72
+
configs/model/optimus.yaml ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ optimus:
3
+ symbol: optimus
4
+ find_unused_parameters: false
5
+ args: {}
6
+
7
+ optimus_bert_encoder:
8
+ super_cfg: optimus
9
+ type: optimus_bert_connector
10
+ # pth: pretrained/optimus_bert_encoder.pth
11
+ args:
12
+ config:
13
+ architectures:
14
+ - BertForMaskedLM
15
+ attention_probs_dropout_prob: 0.1
16
+ finetuning_task: null
17
+ hidden_act: gelu
18
+ hidden_dropout_prob: 0.1
19
+ hidden_size: 768
20
+ initializer_range: 0.02
21
+ intermediate_size: 3072
22
+ layer_norm_eps: 1.e-12
23
+ max_position_embeddings: 512
24
+ num_attention_heads: 12
25
+ num_hidden_layers: 12
26
+ num_labels: 2
27
+ output_attentions: false
28
+ output_hidden_states: false
29
+ pruned_heads: {}
30
+ torchscript: false
31
+ type_vocab_size: 2
32
+ vocab_size: 28996
33
+ latent_size: 768
34
+
35
+ optimus_bert_tokenizer:
36
+ super_cfg: optimus
37
+ type: optimus_bert_tokenizer
38
+ args:
39
+ do_lower_case: false
40
+ max_len: 512
41
+ vocab_file: lib/model_zoo/optimus_models/vocab/bert-base-cased-vocab.txt
42
+
43
+ optimus_gpt2_decoder:
44
+ super_cfg: optimus
45
+ type: optimus_gpt2_connector
46
+ # pth: pretrained/optimus_gpt2_decoder.pth
47
+ args:
48
+ config:
49
+ architectures:
50
+ - GPT2LMHeadModel
51
+ attn_pdrop: 0.1
52
+ embd_pdrop: 0.1
53
+ finetuning_task: null
54
+ hidden_size: 768
55
+ initializer_range: 0.02
56
+ latent_size: 768
57
+ layer_norm_epsilon: 1.e-05
58
+ max_position_embeddings: 1024
59
+ n_ctx: 1024
60
+ n_embd: 768
61
+ n_head: 12
62
+ n_layer: 12
63
+ n_positions: 1024
64
+ num_attention_heads: 12
65
+ num_hidden_layers: 12
66
+ num_labels: 1
67
+ output_attentions: false
68
+ output_hidden_states: false
69
+ pretrained_config_archive_map:
70
+ gpt2 : https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json
71
+ gpt2-medium : https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-medium-config.json
72
+ gpt2-large : https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-config.json
73
+ pruned_heads: {}
74
+ resid_pdrop: 0.1
75
+ summary_activation: null
76
+ summary_first_dropout: 0.1
77
+ summary_proj_to_labels: true
78
+ summary_type: cls_index
79
+ summary_use_proj: true
80
+ torchscript: false
81
+ vocab_size: 50260
82
+
83
+ optimus_gpt2_tokenizer:
84
+ super_cfg: optimus
85
+ type: optimus_gpt2_tokenizer
86
+ args:
87
+ do_lower_case: false
88
+ max_len: 1024
89
+ vocab_file: lib/model_zoo/optimus_models/vocab/gpt2-vocab.json
90
+ merges_file: lib/model_zoo/optimus_models/vocab/gpt2-merges.txt
91
+
92
+ optimus_vae:
93
+ super_cfg: optimus
94
+ type: optimus_vae
95
+ pth: pretrained/optimus-vae.pth
96
+ args:
97
+ encoder: MODEL(optimus_bert_encoder)
98
+ decoder: MODEL(optimus_gpt2_decoder)
99
+ tokenizer_encoder: MODEL(optimus_bert_tokenizer)
100
+ tokenizer_decoder: MODEL(optimus_gpt2_tokenizer)
101
+ args:
102
+ latent_size: 768
configs/model/sd.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sd_base:
2
+ symbol: sd
3
+ find_unused_parameters: true
4
+
5
+ sd_autoencoder:
6
+ type: autoencoderkl
7
+ args:
8
+ embed_dim: 4
9
+ monitor: val/rec_loss
10
+ ddconfig:
11
+ double_z: true
12
+ z_channels: 4
13
+ resolution: 256
14
+ in_channels: 3
15
+ out_ch: 3
16
+ ch: 128
17
+ ch_mult: [1, 2, 4, 4]
18
+ num_res_blocks: 2
19
+ attn_resolutions: []
20
+ dropout: 0.0
21
+ lossconfig:
22
+ target: torch.nn.Identity
23
+ pth: pretrained/kl-f8.pth
24
+
25
+ sd_t2i:
26
+ super_cfg: sd_base
27
+ type: sd_t2i
28
+ args:
29
+ first_stage_config: MODEL(sd_autoencoder)
30
+ cond_stage_config: MODEL(clip_text_frozen)
31
+ unet_config: MODEL(openai_unet_sd)
32
+ beta_linear_start: 0.00085
33
+ beta_linear_end: 0.012
34
+ num_timesteps_cond: 1
35
+ timesteps: 1000
36
+ scale_factor: 0.18215
37
+ use_ema: true
38
+
39
+ sd_t2i_noema:
40
+ super_cfg: sd
41
+ args:
42
+ use_ema: false
43
+
44
+ #####################
45
+ # sd with full clip #
46
+ #####################
47
+
48
+ sd_t2i_fullclip_backward_compatible:
49
+ super_cfg: sd_t2i
50
+ args:
51
+ cond_stage_config: MODEL(clip_frozen_encode_text_noproj)
52
+
53
+ sd_t2i_fullclip_backward_compatible_noema:
54
+ super_cfg: sd_t2i_noema
55
+ args:
56
+ cond_stage_config: MODEL(clip_frozen_encode_text_noproj)
57
+
58
+ sd_t2i_fullclip:
59
+ super_cfg: sd_t2i
60
+ args:
61
+ cond_stage_config: MODEL(clip_frozen_encode_text)
62
+
63
+ sd_variation:
64
+ super_cfg: sd_t2i
65
+ type: sd_variation
66
+ args:
67
+ cond_stage_config: MODEL(clip_vision_frozen_justin)
68
+
configs/model/vd.yaml ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # vd_base:
2
+ # symbol: vd
3
+ # find_unused_parameters: true
4
+
5
+ ############
6
+ # vd basic #
7
+ ############
8
+
9
+ vd_basic:
10
+ super_cfg: sd_t2i
11
+ type: vd_basic
12
+ symbol: vd
13
+ find_unused_parameters: true
14
+ args:
15
+ cond_stage_config: MODEL(clip_frozen_encode_vision)
16
+
17
+ vd_basic_noema:
18
+ super_cfg: vd_basic
19
+ args:
20
+ use_ema: false
21
+
22
+ ###################
23
+ # vd dual-context #
24
+ ###################
25
+
26
+ vd_dc:
27
+ super_cfg: sd_t2i_fullclip
28
+ type: vd_dc
29
+ symbol: vd
30
+ find_unused_parameters: true
31
+ args:
32
+ unet_config: MODEL(openai_unet_dual_context)
33
+
34
+ vd_dc_noema:
35
+ super_cfg: vd_dc
36
+ args:
37
+ use_ema: false
38
+
39
+ ######
40
+ # vd #
41
+ ######
42
+
43
+ vd:
44
+ type: vd
45
+ symbol: vd
46
+ find_unused_parameters: true
47
+ args:
48
+ autokl_cfg: MODEL(sd_autoencoder)
49
+ optimus_cfg: MODEL(optimus_vae)
50
+ clip_cfg: MODEL(clip_frozen)
51
+ unet_config: MODEL(openai_unet_vd)
52
+ beta_linear_start: 0.00085
53
+ beta_linear_end: 0.012
54
+ timesteps: 1000
55
+ scale_factor: 0.18215
56
+ use_ema: true
57
+
58
+ vd_noema:
59
+ super_cfg: vd
60
+ args:
61
+ use_ema: false
lib/__init__.py ADDED
File without changes
lib/cfg_helper.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path as osp
3
+ import shutil
4
+ import copy
5
+ import time
6
+ import pprint
7
+ import numpy as np
8
+ import torch
9
+ import matplotlib
10
+ import argparse
11
+ import json
12
+ import yaml
13
+ from easydict import EasyDict as edict
14
+
15
+ from .model_zoo import get_model
16
+
17
+ ############
18
+ # cfg_bank #
19
+ ############
20
+
21
+ def cfg_solvef(cmd, root):
22
+ if not isinstance(cmd, str):
23
+ return cmd
24
+
25
+ if cmd.find('SAME')==0:
26
+ zoom = root
27
+ p = cmd[len('SAME'):].strip('()').split('.')
28
+ p = [pi.strip() for pi in p]
29
+ for pi in p:
30
+ try:
31
+ pi = int(pi)
32
+ except:
33
+ pass
34
+
35
+ try:
36
+ zoom = zoom[pi]
37
+ except:
38
+ return cmd
39
+ return cfg_solvef(zoom, root)
40
+
41
+ if cmd.find('SEARCH')==0:
42
+ zoom = root
43
+ p = cmd[len('SEARCH'):].strip('()').split('.')
44
+ p = [pi.strip() for pi in p]
45
+ find = True
46
+ # Depth first search
47
+ for pi in p:
48
+ try:
49
+ pi = int(pi)
50
+ except:
51
+ pass
52
+
53
+ try:
54
+ zoom = zoom[pi]
55
+ except:
56
+ find = False
57
+ break
58
+
59
+ if find:
60
+ return cfg_solvef(zoom, root)
61
+ else:
62
+ if isinstance(root, dict):
63
+ for ri in root:
64
+ rv = cfg_solvef(cmd, root[ri])
65
+ if rv != cmd:
66
+ return rv
67
+ if isinstance(root, list):
68
+ for ri in root:
69
+ rv = cfg_solvef(cmd, ri)
70
+ if rv != cmd:
71
+ return rv
72
+ return cmd
73
+
74
+ if cmd.find('MODEL')==0:
75
+ goto = cmd[len('MODEL'):].strip('()')
76
+ return model_cfg_bank()(goto)
77
+
78
+ if cmd.find('DATASET')==0:
79
+ goto = cmd[len('DATASET'):].strip('()')
80
+ return dataset_cfg_bank()(goto)
81
+
82
+ return cmd
83
+
84
+ def cfg_solve(cfg, cfg_root):
85
+ # The function solve cfg element such that
86
+ # all sorrogate input are settled.
87
+ # (i.e. SAME(***) )
88
+ if isinstance(cfg, list):
89
+ for i in range(len(cfg)):
90
+ if isinstance(cfg[i], (list, dict)):
91
+ cfg[i] = cfg_solve(cfg[i], cfg_root)
92
+ else:
93
+ cfg[i] = cfg_solvef(cfg[i], cfg_root)
94
+ if isinstance(cfg, dict):
95
+ for k in cfg:
96
+ if isinstance(cfg[k], (list, dict)):
97
+ cfg[k] = cfg_solve(cfg[k], cfg_root)
98
+ else:
99
+ cfg[k] = cfg_solvef(cfg[k], cfg_root)
100
+ return cfg
101
+
102
+ class model_cfg_bank(object):
103
+ def __init__(self):
104
+ self.cfg_dir = osp.join('configs', 'model')
105
+ self.cfg_bank = edict()
106
+
107
+ def __call__(self, name):
108
+ if name not in self.cfg_bank:
109
+ cfg_path = self.get_yaml_path(name)
110
+ with open(cfg_path, 'r') as f:
111
+ cfg_new = yaml.load(
112
+ f, Loader=yaml.FullLoader)
113
+ cfg_new = edict(cfg_new)
114
+ self.cfg_bank.update(cfg_new)
115
+
116
+ cfg = self.cfg_bank[name]
117
+ cfg.name = name
118
+ if 'super_cfg' not in cfg:
119
+ cfg = cfg_solve(cfg, cfg)
120
+ self.cfg_bank[name] = cfg
121
+ return copy.deepcopy(cfg)
122
+
123
+ super_cfg = self.__call__(cfg.super_cfg)
124
+ # unlike other field,
125
+ # args will not be replaced but update.
126
+ if 'args' in cfg:
127
+ if 'args' in super_cfg:
128
+ super_cfg.args.update(cfg.args)
129
+ else:
130
+ super_cfg.args = cfg.args
131
+ cfg.pop('args')
132
+
133
+ super_cfg.update(cfg)
134
+ super_cfg.pop('super_cfg')
135
+ cfg = super_cfg
136
+ try:
137
+ delete_args = cfg.pop('delete_args')
138
+ except:
139
+ delete_args = []
140
+
141
+ for dargs in delete_args:
142
+ cfg.args.pop(dargs)
143
+
144
+ cfg = cfg_solve(cfg, cfg)
145
+ self.cfg_bank[name] = cfg
146
+ return copy.deepcopy(cfg)
147
+
148
+ def get_yaml_path(self, name):
149
+ if name.find('ldm')==0:
150
+ return osp.join(
151
+ self.cfg_dir, 'ldm.yaml')
152
+ elif name.find('comodgan')==0:
153
+ return osp.join(
154
+ self.cfg_dir, 'comodgan.yaml')
155
+ elif name.find('stylegan')==0:
156
+ return osp.join(
157
+ self.cfg_dir, 'stylegan.yaml')
158
+ elif name.find('absgan')==0:
159
+ return osp.join(
160
+ self.cfg_dir, 'absgan.yaml')
161
+ elif name.find('ashgan')==0:
162
+ return osp.join(
163
+ self.cfg_dir, 'ashgan.yaml')
164
+ elif name.find('sr3')==0:
165
+ return osp.join(
166
+ self.cfg_dir, 'sr3.yaml')
167
+ elif name.find('specdiffsr')==0:
168
+ return osp.join(
169
+ self.cfg_dir, 'specdiffsr.yaml')
170
+ elif name.find('openai_unet')==0:
171
+ return osp.join(
172
+ self.cfg_dir, 'openai_unet.yaml')
173
+ elif name.find('clip')==0:
174
+ return osp.join(
175
+ self.cfg_dir, 'clip.yaml')
176
+ elif name.find('sd')==0:
177
+ return osp.join(
178
+ self.cfg_dir, 'sd.yaml')
179
+ elif name.find('vd')==0:
180
+ return osp.join(
181
+ self.cfg_dir, 'vd.yaml')
182
+ elif name.find('optimus')==0:
183
+ return osp.join(
184
+ self.cfg_dir, 'optimus.yaml')
185
+ else:
186
+ raise ValueError
187
+
188
+ class dataset_cfg_bank(object):
189
+ def __init__(self):
190
+ self.cfg_dir = osp.join('configs', 'dataset')
191
+ self.cfg_bank = edict()
192
+
193
+ def __call__(self, name):
194
+ if name not in self.cfg_bank:
195
+ cfg_path = self.get_yaml_path(name)
196
+ with open(cfg_path, 'r') as f:
197
+ cfg_new = yaml.load(
198
+ f, Loader=yaml.FullLoader)
199
+ cfg_new = edict(cfg_new)
200
+ self.cfg_bank.update(cfg_new)
201
+
202
+ cfg = self.cfg_bank[name]
203
+ cfg.name = name
204
+ if cfg.get('super_cfg', None) is None:
205
+ cfg = cfg_solve(cfg, cfg)
206
+ self.cfg_bank[name] = cfg
207
+ return copy.deepcopy(cfg)
208
+
209
+ super_cfg = self.__call__(cfg.super_cfg)
210
+ super_cfg.update(cfg)
211
+ cfg = super_cfg
212
+ cfg.super_cfg = None
213
+ try:
214
+ delete = cfg.pop('delete')
215
+ except:
216
+ delete = []
217
+
218
+ for dargs in delete:
219
+ cfg.pop(dargs)
220
+
221
+ cfg = cfg_solve(cfg, cfg)
222
+ self.cfg_bank[name] = cfg
223
+ return copy.deepcopy(cfg)
224
+
225
+ def get_yaml_path(self, name):
226
+ if name.find('cityscapes')==0:
227
+ return osp.join(
228
+ self.cfg_dir, 'cityscapes.yaml')
229
+ elif name.find('div2k')==0:
230
+ return osp.join(
231
+ self.cfg_dir, 'div2k.yaml')
232
+ elif name.find('gandiv2k')==0:
233
+ return osp.join(
234
+ self.cfg_dir, 'gandiv2k.yaml')
235
+ elif name.find('srbenchmark')==0:
236
+ return osp.join(
237
+ self.cfg_dir, 'srbenchmark.yaml')
238
+ elif name.find('imagedir')==0:
239
+ return osp.join(
240
+ self.cfg_dir, 'imagedir.yaml')
241
+ elif name.find('places2')==0:
242
+ return osp.join(
243
+ self.cfg_dir, 'places2.yaml')
244
+ elif name.find('ffhq')==0:
245
+ return osp.join(
246
+ self.cfg_dir, 'ffhq.yaml')
247
+ elif name.find('imcpt')==0:
248
+ return osp.join(
249
+ self.cfg_dir, 'imcpt.yaml')
250
+ elif name.find('texture')==0:
251
+ return osp.join(
252
+ self.cfg_dir, 'texture.yaml')
253
+ elif name.find('openimages')==0:
254
+ return osp.join(
255
+ self.cfg_dir, 'openimages.yaml')
256
+ elif name.find('laion2b')==0:
257
+ return osp.join(
258
+ self.cfg_dir, 'laion2b.yaml')
259
+ elif name.find('laionart')==0:
260
+ return osp.join(
261
+ self.cfg_dir, 'laionart.yaml')
262
+ elif name.find('celeba')==0:
263
+ return osp.join(
264
+ self.cfg_dir, 'celeba.yaml')
265
+ elif name.find('coyo')==0:
266
+ return osp.join(
267
+ self.cfg_dir, 'coyo.yaml')
268
+ elif name.find('pafc')==0:
269
+ return osp.join(
270
+ self.cfg_dir, 'pafc.yaml')
271
+ elif name.find('coco')==0:
272
+ return osp.join(
273
+ self.cfg_dir, 'coco.yaml')
274
+ else:
275
+ raise ValueError
276
+
277
+ class experiment_cfg_bank(object):
278
+ def __init__(self):
279
+ self.cfg_dir = osp.join('configs', 'experiment')
280
+ self.cfg_bank = edict()
281
+
282
+ def __call__(self, name):
283
+ if name not in self.cfg_bank:
284
+ cfg_path = self.get_yaml_path(name)
285
+ with open(cfg_path, 'r') as f:
286
+ cfg = yaml.load(
287
+ f, Loader=yaml.FullLoader)
288
+ cfg = edict(cfg)
289
+
290
+ cfg = cfg_solve(cfg, cfg)
291
+ cfg = cfg_solve(cfg, cfg)
292
+ # twice for SEARCH
293
+ self.cfg_bank[name] = cfg
294
+ return copy.deepcopy(cfg)
295
+
296
+ def get_yaml_path(self, name):
297
+ return osp.join(
298
+ self.cfg_dir, name+'.yaml')
299
+
300
+ def load_cfg_yaml(path):
301
+ if osp.isfile(path):
302
+ cfg_path = path
303
+ elif osp.isfile(osp.join('configs', 'experiment', path)):
304
+ cfg_path = osp.join('configs', 'experiment', path)
305
+ elif osp.isfile(osp.join('configs', 'experiment', path+'.yaml')):
306
+ cfg_path = osp.join('configs', 'experiment', path+'.yaml')
307
+ else:
308
+ assert False, 'No such config!'
309
+
310
+ with open(cfg_path, 'r') as f:
311
+ cfg = yaml.load(f, Loader=yaml.FullLoader)
312
+ cfg = edict(cfg)
313
+ cfg = cfg_solve(cfg, cfg)
314
+ cfg = cfg_solve(cfg, cfg)
315
+ return cfg
316
+
317
+ ##############
318
+ # cfg_helper #
319
+ ##############
320
+
321
+ def get_experiment_id(ref=None):
322
+ if ref is None:
323
+ time.sleep(0.5)
324
+ return int(time.time()*100)
325
+ else:
326
+ try:
327
+ return int(ref)
328
+ except:
329
+ pass
330
+
331
+ _, ref = osp.split(ref)
332
+ ref = ref.split('_')[0]
333
+ try:
334
+ return int(ref)
335
+ except:
336
+ assert False, 'Invalid experiment ID!'
337
+
338
+ def record_resume_cfg(path):
339
+ cnt = 0
340
+ while True:
341
+ if osp.exists(path+'.{:04d}'.format(cnt)):
342
+ cnt += 1
343
+ continue
344
+ shutil.copyfile(path, path+'.{:04d}'.format(cnt))
345
+ break
346
+
347
+ def get_command_line_args():
348
+ parser = argparse.ArgumentParser()
349
+ parser.add_argument('--debug', action='store_true', default=False)
350
+ parser.add_argument('--config', type=str)
351
+ parser.add_argument('--gpu', nargs='+', type=int)
352
+
353
+ parser.add_argument('--node_rank', type=int, default=0)
354
+ parser.add_argument('--nodes', type=int, default=1)
355
+ parser.add_argument('--addr', type=str, default='127.0.0.1')
356
+ parser.add_argument('--port', type=int, default=11233)
357
+
358
+ parser.add_argument('--signature', nargs='+', type=str)
359
+ parser.add_argument('--seed', type=int)
360
+
361
+ parser.add_argument('--eval', type=str)
362
+ parser.add_argument('--eval_subdir', type=str)
363
+ parser.add_argument('--pretrained', type=str)
364
+
365
+ parser.add_argument('--resume_dir', type=str)
366
+ parser.add_argument('--resume_step', type=int)
367
+ parser.add_argument('--resume_weight', type=str)
368
+
369
+ args = parser.parse_args()
370
+
371
+ # Special handling the resume
372
+ if args.resume_dir is not None:
373
+ cfg = edict()
374
+ cfg.env = edict()
375
+ cfg.env.debug = args.debug
376
+ cfg.env.resume = edict()
377
+ cfg.env.resume.dir = args.resume_dir
378
+ cfg.env.resume.step = args.resume_step
379
+ cfg.env.resume.weight = args.resume_weight
380
+ return cfg
381
+
382
+ cfg = load_cfg_yaml(args.config)
383
+ cfg.env.debug = args.debug
384
+ cfg.env.gpu_device = [0] if args.gpu is None else list(args.gpu)
385
+ cfg.env.master_addr = args.addr
386
+ cfg.env.master_port = args.port
387
+ cfg.env.dist_url = 'tcp://{}:{}'.format(args.addr, args.port)
388
+ cfg.env.node_rank = args.node_rank
389
+ cfg.env.nodes = args.nodes
390
+
391
+ istrain = False if args.eval is not None else True
392
+ isdebug = cfg.env.debug
393
+
394
+ if istrain:
395
+ if isdebug:
396
+ cfg.env.experiment_id = 999999999999
397
+ cfg.train.signature = ['debug']
398
+ else:
399
+ cfg.env.experiment_id = get_experiment_id()
400
+ if args.signature is not None:
401
+ cfg.train.signature = args.signature
402
+ else:
403
+ if 'train' in cfg:
404
+ cfg.pop('train')
405
+ cfg.env.experiment_id = get_experiment_id(args.eval)
406
+ if args.signature is not None:
407
+ cfg.eval.signature = args.signature
408
+
409
+ if isdebug and (args.eval is None):
410
+ cfg.env.experiment_id = 999999999999
411
+ cfg.eval.signature = ['debug']
412
+
413
+ if args.eval_subdir is not None:
414
+ if isdebug:
415
+ cfg.eval.eval_subdir = 'debug'
416
+ else:
417
+ cfg.eval.eval_subdir = args.eval_subdir
418
+ if args.pretrained is not None:
419
+ cfg.eval.pretrained = args.pretrained
420
+ # The override pretrained over the setting in cfg.model
421
+
422
+ if args.seed is not None:
423
+ cfg.env.rnd_seed = args.seed
424
+
425
+ return cfg
426
+
427
+ def cfg_initiates(cfg):
428
+ cfge = cfg.env
429
+ isdebug = cfge.debug
430
+ isresume = 'resume' in cfge
431
+ istrain = 'train' in cfg
432
+ haseval = 'eval' in cfg
433
+ cfgt = cfg.train if istrain else None
434
+ cfgv = cfg.eval if haseval else None
435
+
436
+ ###############################
437
+ # get some environment params #
438
+ ###############################
439
+
440
+ cfge.computer = os.uname()
441
+ cfge.torch_version = str(torch.__version__)
442
+
443
+ ##########
444
+ # resume #
445
+ ##########
446
+
447
+ if isresume:
448
+ resume_cfg_path = osp.join(cfge.resume.dir, 'config.yaml')
449
+ record_resume_cfg(resume_cfg_path)
450
+ with open(resume_cfg_path, 'r') as f:
451
+ cfg_resume = yaml.load(f, Loader=yaml.FullLoader)
452
+ cfg_resume = edict(cfg_resume)
453
+ cfg_resume.env.update(cfge)
454
+ cfg = cfg_resume
455
+ cfge = cfg.env
456
+ log_file = cfg.train.log_file
457
+
458
+ print('')
459
+ print('##########')
460
+ print('# resume #')
461
+ print('##########')
462
+ print('')
463
+ with open(log_file, 'a') as f:
464
+ print('', file=f)
465
+ print('##########', file=f)
466
+ print('# resume #', file=f)
467
+ print('##########', file=f)
468
+ print('', file=f)
469
+
470
+ pprint.pprint(cfg)
471
+ with open(log_file, 'a') as f:
472
+ pprint.pprint(cfg, f)
473
+
474
+ ####################
475
+ # node distributed #
476
+ ####################
477
+
478
+ if cfg.env.master_addr!='127.0.0.1':
479
+ os.environ['MASTER_ADDR'] = cfge.master_addr
480
+ os.environ['MASTER_PORT'] = '{}'.format(cfge.master_port)
481
+ if cfg.env.dist_backend=='nccl':
482
+ os.environ['NCCL_SOCKET_FAMILY'] = 'AF_INET'
483
+ if cfg.env.dist_backend=='gloo':
484
+ os.environ['GLOO_SOCKET_FAMILY'] = 'AF_INET'
485
+
486
+ #######################
487
+ # cuda visible device #
488
+ #######################
489
+
490
+ os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(
491
+ [str(gid) for gid in cfge.gpu_device])
492
+
493
+ #####################
494
+ # return resume cfg #
495
+ #####################
496
+
497
+ if isresume:
498
+ return cfg
499
+
500
+ #############################################
501
+ # some misc setting that not need in resume #
502
+ #############################################
503
+
504
+ cfgm = cfg.model
505
+ cfge.gpu_count = len(cfge.gpu_device)
506
+
507
+ ##########################################
508
+ # align batch size and num worker config #
509
+ ##########################################
510
+
511
+ gpu_n = cfge.gpu_count * cfge.nodes
512
+ def align_batch_size(bs, bs_per_gpu):
513
+ assert (bs is not None) or (bs_per_gpu is not None)
514
+ bs = bs_per_gpu * gpu_n if bs is None else bs
515
+ bs_per_gpu = bs // gpu_n if bs_per_gpu is None else bs_per_gpu
516
+ assert (bs == bs_per_gpu * gpu_n)
517
+ return bs, bs_per_gpu
518
+
519
+ if istrain:
520
+ cfgt.batch_size, cfgt.batch_size_per_gpu = \
521
+ align_batch_size(cfgt.batch_size, cfgt.batch_size_per_gpu)
522
+ cfgt.dataset_num_workers, cfgt.dataset_num_workers_per_gpu = \
523
+ align_batch_size(cfgt.dataset_num_workers, cfgt.dataset_num_workers_per_gpu)
524
+ if haseval:
525
+ cfgv.batch_size, cfgv.batch_size_per_gpu = \
526
+ align_batch_size(cfgv.batch_size, cfgv.batch_size_per_gpu)
527
+ cfgv.dataset_num_workers, cfgv.dataset_num_workers_per_gpu = \
528
+ align_batch_size(cfgv.dataset_num_workers, cfgv.dataset_num_workers_per_gpu)
529
+
530
+ ##################
531
+ # create log dir #
532
+ ##################
533
+
534
+ if istrain:
535
+ if not isdebug:
536
+ sig = cfgt.get('signature', [])
537
+ version = get_model().get_version(cfgm.type)
538
+ sig = sig + ['v{}'.format(version), 's{}'.format(cfge.rnd_seed)]
539
+ else:
540
+ sig = ['debug']
541
+
542
+ log_dir = [
543
+ cfge.log_root_dir,
544
+ '{}_{}'.format(cfgm.symbol, cfgt.dataset.symbol),
545
+ '_'.join([str(cfge.experiment_id)] + sig)
546
+ ]
547
+ log_dir = osp.join(*log_dir)
548
+ log_file = osp.join(log_dir, 'train.log')
549
+ if not osp.exists(log_file):
550
+ os.makedirs(osp.dirname(log_file))
551
+ cfgt.log_dir = log_dir
552
+ cfgt.log_file = log_file
553
+
554
+ if haseval:
555
+ cfgv.log_dir = log_dir
556
+ cfgv.log_file = log_file
557
+ else:
558
+ model_symbol = cfgm.symbol
559
+ if cfgv.get('dataset', None) is None:
560
+ dataset_symbol = 'nodataset'
561
+ else:
562
+ dataset_symbol = cfgv.dataset.symbol
563
+
564
+ log_dir = osp.join(cfge.log_root_dir, '{}_{}'.format(model_symbol, dataset_symbol))
565
+ exp_dir = search_experiment_folder(log_dir, cfge.experiment_id)
566
+ if exp_dir is None:
567
+ if not isdebug:
568
+ sig = cfgv.get('signature', []) + ['evalonly']
569
+ else:
570
+ sig = ['debug']
571
+ exp_dir = '_'.join([str(cfge.experiment_id)] + sig)
572
+
573
+ eval_subdir = cfgv.get('eval_subdir', None)
574
+ # override subdir in debug mode (if eval_subdir is set)
575
+ eval_subdir = 'debug' if (eval_subdir is not None) and isdebug else eval_subdir
576
+
577
+ if eval_subdir is not None:
578
+ log_dir = osp.join(log_dir, exp_dir, eval_subdir)
579
+ else:
580
+ log_dir = osp.join(log_dir, exp_dir)
581
+
582
+ disable_log_override = cfgv.get('disable_log_override', False)
583
+ if osp.isdir(log_dir):
584
+ if disable_log_override:
585
+ assert False, 'Override an exsited log_dir is disabled at [{}]'.format(log_dir)
586
+ else:
587
+ os.makedirs(log_dir)
588
+
589
+ log_file = osp.join(log_dir, 'eval.log')
590
+ cfgv.log_dir = log_dir
591
+ cfgv.log_file = log_file
592
+
593
+ ######################
594
+ # print and save cfg #
595
+ ######################
596
+
597
+ pprint.pprint(cfg)
598
+ with open(log_file, 'w') as f:
599
+ pprint.pprint(cfg, f)
600
+ with open(osp.join(log_dir, 'config.yaml'), 'w') as f:
601
+ yaml.dump(edict_2_dict(cfg), f)
602
+
603
+ #############
604
+ # save code #
605
+ #############
606
+
607
+ save_code = False
608
+ if istrain:
609
+ save_code = cfgt.get('save_code', False)
610
+ elif haseval:
611
+ save_code = cfgv.get('save_code', False)
612
+
613
+ if save_code:
614
+ codedir = osp.join(log_dir, 'code')
615
+ if osp.exists(codedir):
616
+ shutil.rmtree(codedir)
617
+ for d in ['configs', 'lib']:
618
+ fromcodedir = d
619
+ tocodedir = osp.join(codedir, d)
620
+ shutil.copytree(
621
+ fromcodedir, tocodedir,
622
+ ignore=shutil.ignore_patterns(
623
+ '*__pycache__*', '*build*'))
624
+ for codei in os.listdir('.'):
625
+ if osp.splitext(codei)[1] == 'py':
626
+ shutil.copy(codei, codedir)
627
+
628
+ #######################
629
+ # set matplotlib mode #
630
+ #######################
631
+
632
+ if 'matplotlib_mode' in cfge:
633
+ try:
634
+ matplotlib.use(cfge.matplotlib_mode)
635
+ except:
636
+ print('Warning: matplotlib mode [{}] failed to be set!'.format(cfge.matplotlib_mode))
637
+
638
+ return cfg
639
+
640
+ def edict_2_dict(x):
641
+ if isinstance(x, dict):
642
+ xnew = {}
643
+ for k in x:
644
+ xnew[k] = edict_2_dict(x[k])
645
+ return xnew
646
+ elif isinstance(x, list):
647
+ xnew = []
648
+ for i in range(len(x)):
649
+ xnew.append( edict_2_dict(x[i]) )
650
+ return xnew
651
+ else:
652
+ return x
653
+
654
+ def search_experiment_folder(root, exid):
655
+ target = None
656
+ for fi in os.listdir(root):
657
+ if not osp.isdir(osp.join(root, fi)):
658
+ continue
659
+ if int(fi.split('_')[0]) == exid:
660
+ if target is not None:
661
+ return None # duplicated
662
+ elif target is None:
663
+ target = fi
664
+ return target
lib/cfg_holder.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+ def singleton(class_):
4
+ instances = {}
5
+ def getinstance(*args, **kwargs):
6
+ if class_ not in instances:
7
+ instances[class_] = class_(*args, **kwargs)
8
+ return instances[class_]
9
+ return getinstance
10
+
11
+ ##############
12
+ # cfg_holder #
13
+ ##############
14
+
15
+ @singleton
16
+ class cfg_unique_holder(object):
17
+ def __init__(self):
18
+ self.cfg = None
19
+ # this is use to track the main codes.
20
+ self.code = set()
21
+ def save_cfg(self, cfg):
22
+ self.cfg = copy.deepcopy(cfg)
23
+ def add_code(self, code):
24
+ """
25
+ A new main code is reached and
26
+ its name is added.
27
+ """
28
+ self.code.add(code)
lib/data_factory/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .common.ds_base import collate, get_dataset
2
+ from .common.ds_loader import get_loader
3
+ from .common.ds_transform import get_transform
4
+ from .common.ds_estimator import get_estimator
5
+ from .common.ds_formatter import get_formatter
6
+ from .common.ds_sampler import get_sampler
lib/data_factory/common/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .ds_base import ds_base, collate, register as regdataset
2
+ from .ds_loader import pre_loader_checkings, register as regloader
3
+ from .ds_transform import TBase, have, register as regtrans
4
+ from .ds_estimator import register as regestmat
5
+ from .ds_formatter import register as regformat
6
+ from .ds_sampler import register as regsampler
lib/data_factory/common/ds_base.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path as osp
3
+ import numpy as np
4
+ import numpy.random as npr
5
+ import torch
6
+ import torch.distributed as dist
7
+ import torchvision
8
+ import copy
9
+ import itertools
10
+
11
+ from ... import sync
12
+ from ...cfg_holder import cfg_unique_holder as cfguh
13
+ from ...log_service import print_log
14
+
15
+ import torch.distributed as dist
16
+ from multiprocessing import shared_memory
17
+ import pickle
18
+ import hashlib
19
+ import random
20
+
21
+ class ds_base(torch.utils.data.Dataset):
22
+ def __init__(self,
23
+ cfg,
24
+ loader = None,
25
+ estimator = None,
26
+ transforms = None,
27
+ formatter = None):
28
+
29
+ self.cfg = cfg
30
+ self.load_info = None
31
+ self.init_load_info()
32
+ self.loader = loader
33
+ self.transforms = transforms
34
+ self.formatter = formatter
35
+
36
+ if self.load_info is not None:
37
+ load_info_order_by = getattr(self.cfg, 'load_info_order_by', 'default')
38
+ if load_info_order_by == 'default':
39
+ self.load_info = sorted(self.load_info, key=lambda x:x['unique_id'])
40
+ else:
41
+ try:
42
+ load_info_order_by, reverse = load_info_order_by.split('|')
43
+ reverse = reverse == 'reverse'
44
+ except:
45
+ reverse = False
46
+ self.load_info = sorted(
47
+ self.load_info, key=lambda x:x[load_info_order_by], reverse=reverse)
48
+
49
+ load_info_add_idx = getattr(self.cfg, 'load_info_add_idx', True)
50
+ if (self.load_info is not None) and load_info_add_idx:
51
+ for idx, info in enumerate(self.load_info):
52
+ info['idx'] = idx
53
+
54
+ if estimator is not None:
55
+ self.load_info = estimator(self.load_info)
56
+
57
+ self.try_sample = getattr(self.cfg, 'try_sample', None)
58
+ if self.try_sample is not None:
59
+ try:
60
+ start, end = self.try_sample
61
+ except:
62
+ start, end = 0, self.try_sample
63
+ self.load_info = self.load_info[start:end]
64
+
65
+ self.repeat = getattr(self.cfg, 'repeat', 1)
66
+
67
+ pick = getattr(self.cfg, 'pick', None)
68
+ if pick is not None:
69
+ self.load_info = [i for i in self.load_info if i['filename'] in pick]
70
+
71
+ #########
72
+ # cache #
73
+ #########
74
+
75
+ self.cache_sm = getattr(self.cfg, 'cache_sm', False)
76
+ self.cache_cnt = 0
77
+ if self.cache_sm:
78
+ self.cache_pct = getattr(self.cfg, 'cache_pct', 0)
79
+ cache_unique_id = sync.nodewise_sync().random_sync_id()
80
+ self.cache_unique_id = hashlib.sha256(pickle.dumps(cache_unique_id)).hexdigest()
81
+ self.__cache__(self.cache_pct)
82
+
83
+ #######
84
+ # log #
85
+ #######
86
+
87
+ if self.load_info is not None:
88
+ console_info = '{}: '.format(self.__class__.__name__)
89
+ console_info += 'total {} unique images, '.format(len(self.load_info))
90
+ console_info += 'total {} unique sample. Cached {}. Repeat {} times.'.format(
91
+ len(self.load_info), self.cache_cnt, self.repeat)
92
+ else:
93
+ console_info = '{}: load_info not ready.'.format(self.__class__.__name__)
94
+ print_log(console_info)
95
+
96
+ def init_load_info(self):
97
+ # implement by sub class
98
+ pass
99
+
100
+ def __len__(self):
101
+ return len(self.load_info)*self.repeat
102
+
103
+ def __cache__(self, pct):
104
+ if pct == 0:
105
+ self.cache_cnt = 0
106
+ return
107
+ self.cache_cnt = int(len(self.load_info)*pct)
108
+ if not self.cache_sm:
109
+ for i in range(self.cache_cnt):
110
+ self.load_info[i] = self.loader(self.load_info[i])
111
+ return
112
+
113
+ for i in range(self.cache_cnt):
114
+ shm_name = str(self.load_info[i]['unique_id']) + '_' + self.cache_unique_id
115
+ if i % self.local_world_size == self.local_rank:
116
+ data = pickle.dumps(self.loader(self.load_info[i]))
117
+ datan = len(data)
118
+ # self.print_smname_to_file(shm_name)
119
+ shm = shared_memory.SharedMemory(
120
+ name=shm_name, create=True, size=datan)
121
+ shm.buf[0:datan] = data[0:datan]
122
+ shm.close()
123
+ self.load_info[i] = shm_name
124
+ else:
125
+ self.load_info[i] = shm_name
126
+ dist.barrier()
127
+
128
+ def __getitem__(self, idx):
129
+ idx = idx%len(self.load_info)
130
+ # element = copy.deepcopy(self.load_info[idx])
131
+
132
+ # 0730 try shared memory
133
+ element = copy.deepcopy(self.load_info[idx])
134
+ if isinstance(element, str):
135
+ shm = shared_memory.SharedMemory(name=element)
136
+ element = pickle.loads(shm.buf)
137
+ shm.close()
138
+ else:
139
+ element = copy.deepcopy(element)
140
+ element['load_info_ptr'] = self.load_info
141
+
142
+ if idx >= self.cache_cnt:
143
+ element = self.loader(element)
144
+ if self.transforms is not None:
145
+ element = self.transforms(element)
146
+ if self.formatter is not None:
147
+ return self.formatter(element)
148
+ else:
149
+ return element
150
+
151
+ # 0730 try shared memory
152
+ def __del__(self):
153
+ # Clean the shared memory
154
+ for infoi in self.load_info:
155
+ if isinstance(infoi, str) and (self.local_rank==0):
156
+ shm = shared_memory.SharedMemory(name=infoi)
157
+ shm.close()
158
+ shm.unlink()
159
+
160
+ def print_smname_to_file(self, smname):
161
+ try:
162
+ log_file = cfguh().cfg.train.log_file
163
+ except:
164
+ try:
165
+ log_file = cfguh().cfg.eval.log_file
166
+ except:
167
+ raise ValueError
168
+ # a trick to use the log_file path
169
+ sm_file = log_file.replace('.log', '.smname')
170
+ with open(sm_file, 'a') as f:
171
+ f.write(smname + '\n')
172
+
173
+ def singleton(class_):
174
+ instances = {}
175
+ def getinstance(*args, **kwargs):
176
+ if class_ not in instances:
177
+ instances[class_] = class_(*args, **kwargs)
178
+ return instances[class_]
179
+ return getinstance
180
+
181
+ from .ds_loader import get_loader
182
+ from .ds_transform import get_transform
183
+ from .ds_estimator import get_estimator
184
+ from .ds_formatter import get_formatter
185
+
186
+ @singleton
187
+ class get_dataset(object):
188
+ def __init__(self):
189
+ self.dataset = {}
190
+
191
+ def register(self, ds):
192
+ self.dataset[ds.__name__] = ds
193
+
194
+ def __call__(self, cfg):
195
+ if cfg is None:
196
+ return None
197
+ t = cfg.type
198
+ if t is None:
199
+ return None
200
+ elif t in ['laion2b', 'laion2b_dummy',
201
+ 'laion2b_webdataset',
202
+ 'laion2b_webdataset_sdofficial', ]:
203
+ from .. import ds_laion2b
204
+ elif t in ['coyo', 'coyo_dummy',
205
+ 'coyo_webdataset', ]:
206
+ from .. import ds_coyo_webdataset
207
+ elif t in ['laionart', 'laionart_dummy',
208
+ 'laionart_webdataset', ]:
209
+ from .. import ds_laionart
210
+ elif t in ['celeba']:
211
+ from .. import ds_celeba
212
+ elif t in ['div2k']:
213
+ from .. import ds_div2k
214
+ elif t in ['pafc']:
215
+ from .. import ds_pafc
216
+ elif t in ['coco_caption']:
217
+ from .. import ds_coco
218
+ else:
219
+ raise ValueError
220
+
221
+ loader = get_loader() (cfg.get('loader' , None))
222
+ transform = get_transform()(cfg.get('transform', None))
223
+ estimator = get_estimator()(cfg.get('estimator', None))
224
+ formatter = get_formatter()(cfg.get('formatter', None))
225
+
226
+ return self.dataset[t](
227
+ cfg, loader, estimator,
228
+ transform, formatter)
229
+
230
+ def register():
231
+ def wrapper(class_):
232
+ get_dataset().register(class_)
233
+ return class_
234
+ return wrapper
235
+
236
+ # some other helpers
237
+
238
+ class collate(object):
239
+ """
240
+ Modified from torch.utils.data._utils.collate
241
+ It handle list different from the default.
242
+ List collate just by append each other.
243
+ """
244
+ def __init__(self):
245
+ self.default_collate = \
246
+ torch.utils.data._utils.collate.default_collate
247
+
248
+ def __call__(self, batch):
249
+ """
250
+ Args:
251
+ batch: [data, data] -or- [(data1, data2, ...), (data1, data2, ...)]
252
+ This function will not be used as induction function
253
+ """
254
+ elem = batch[0]
255
+ if not (elem, (tuple, list)):
256
+ return self.default_collate(batch)
257
+
258
+ rv = []
259
+ # transposed
260
+ for i in zip(*batch):
261
+ if isinstance(i[0], list):
262
+ if len(i[0]) != 1:
263
+ raise ValueError
264
+ try:
265
+ i = [[self.default_collate(ii).squeeze(0)] for ii in i]
266
+ except:
267
+ pass
268
+ rvi = list(itertools.chain.from_iterable(i))
269
+ rv.append(rvi) # list concat
270
+ else:
271
+ rv.append(self.default_collate(i))
272
+ return rv
lib/data_factory/common/ds_estimator.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+ import numpy as np
3
+ import numpy.random as npr
4
+ import PIL
5
+
6
+ import torch
7
+ import torchvision
8
+ import xml.etree.ElementTree as ET
9
+ import json
10
+ import copy
11
+ import math
12
+
13
+ def singleton(class_):
14
+ instances = {}
15
+ def getinstance(*args, **kwargs):
16
+ if class_ not in instances:
17
+ instances[class_] = class_(*args, **kwargs)
18
+ return instances[class_]
19
+ return getinstance
20
+
21
+ @singleton
22
+ class get_estimator(object):
23
+ def __init__(self):
24
+ self.estimator = {}
25
+
26
+ def register(self, estimf):
27
+ self.estimator[estimf.__name__] = estimf
28
+
29
+ def __call__(self, cfg):
30
+ if cfg is None:
31
+ return None
32
+ t = cfg.type
33
+ return self.estimator[t](**cfg.args)
34
+
35
+ def register():
36
+ def wrapper(class_):
37
+ get_estimator().register(class_)
38
+ return class_
39
+ return wrapper
lib/data_factory/common/ds_formatter.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path as osp
3
+ import numpy as np
4
+ import numpy.random as npr
5
+ import torch
6
+ from PIL import Image
7
+ import copy
8
+ import gc
9
+ import itertools
10
+
11
+ def singleton(class_):
12
+ instances = {}
13
+ def getinstance(*args, **kwargs):
14
+ if class_ not in instances:
15
+ instances[class_] = class_(*args, **kwargs)
16
+ return instances[class_]
17
+ return getinstance
18
+
19
+ @singleton
20
+ class get_formatter(object):
21
+ def __init__(self):
22
+ self.formatter = {}
23
+
24
+ def register(self, formatf):
25
+ self.formatter[formatf.__name__] = formatf
26
+
27
+ def __call__(self, cfg):
28
+ if cfg is None:
29
+ return None
30
+ t = cfg.type
31
+ return self.formatter[t](**cfg.args)
32
+
33
+ def register():
34
+ def wrapper(class_):
35
+ get_formatter().register(class_)
36
+ return class_
37
+ return wrapper
lib/data_factory/common/ds_loader.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+ import numpy as np
3
+ import numpy.random as npr
4
+ import PIL
5
+
6
+ import torch
7
+ import torchvision
8
+ import xml.etree.ElementTree as ET
9
+ import json
10
+ import copy
11
+
12
+ from ...cfg_holder import cfg_unique_holder as cfguh
13
+
14
+ def singleton(class_):
15
+ instances = {}
16
+ def getinstance(*args, **kwargs):
17
+ if class_ not in instances:
18
+ instances[class_] = class_(*args, **kwargs)
19
+ return instances[class_]
20
+ return getinstance
21
+
22
+ @singleton
23
+ class get_loader(object):
24
+ def __init__(self):
25
+ self.loader = {}
26
+
27
+ def register(self, loadf):
28
+ self.loader[loadf.__name__] = loadf
29
+
30
+ def __call__(self, cfg):
31
+ if cfg is None:
32
+ return None
33
+ if isinstance(cfg, list):
34
+ loader = []
35
+ for ci in cfg:
36
+ t = ci.type
37
+ loader.append(self.loader[t](**ci.args))
38
+ return compose(loader)
39
+ t = cfg.type
40
+ return self.loader[t](**cfg.args)
41
+
42
+ class compose(object):
43
+ def __init__(self, loaders):
44
+ self.loaders = loaders
45
+
46
+ def __call__(self, element):
47
+ for l in self.loaders:
48
+ element = l(element)
49
+ return element
50
+
51
+ def __getitem__(self, idx):
52
+ return self.loaders[idx]
53
+
54
+ def register():
55
+ def wrapper(class_):
56
+ get_loader().register(class_)
57
+ return class_
58
+ return wrapper
59
+
60
+ def pre_loader_checkings(ltype):
61
+ lpath = ltype+'_path'
62
+ # cache feature added on 20201021
63
+ lcache = ltype+'_cache'
64
+ def wrapper(func):
65
+ def inner(self, element):
66
+ if lcache in element:
67
+ # cache feature added on 20201021
68
+ data = element[lcache]
69
+ else:
70
+ if ltype in element:
71
+ raise ValueError
72
+ if lpath not in element:
73
+ raise ValueError
74
+
75
+ if element[lpath] is None:
76
+ data = None
77
+ else:
78
+ data = func(self, element[lpath], element)
79
+ element[ltype] = data
80
+
81
+ if ltype == 'image':
82
+ if isinstance(data, np.ndarray):
83
+ imsize = data.shape[-2:]
84
+ elif isinstance(data, PIL.Image.Image):
85
+ imsize = data.size[::-1]
86
+ elif isinstance(data, torch.Tensor):
87
+ imsize = [data.size(-2), data.size(-1)]
88
+ elif data is None:
89
+ imsize = None
90
+ else:
91
+ raise ValueError
92
+ element['imsize'] = imsize
93
+ element['imsize_current'] = copy.deepcopy(imsize)
94
+ return element
95
+ return inner
96
+ return wrapper
lib/data_factory/common/ds_sampler.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tokenize import group
2
+ import torch
3
+ import numpy as np
4
+ import numpy.random as npr
5
+ import torch.distributed as dist
6
+ import math
7
+
8
+ from ...log_service import print_log
9
+ from ... import sync
10
+
11
+ def singleton(class_):
12
+ instances = {}
13
+ def getinstance(*args, **kwargs):
14
+ if class_ not in instances:
15
+ instances[class_] = class_(*args, **kwargs)
16
+ return instances[class_]
17
+ return getinstance
18
+
19
+ @singleton
20
+ class get_sampler(object):
21
+ def __init__(self):
22
+ self.sampler = {}
23
+
24
+ def register(self, sampler):
25
+ self.sampler[sampler.__name__] = sampler
26
+
27
+ def __call__(self, dataset, cfg):
28
+ if cfg == 'default_train':
29
+ return GlobalDistributedSampler(dataset, shuffle=True, extend=False)
30
+ elif cfg == 'default_eval':
31
+ return GlobalDistributedSampler(dataset, shuffle=False, extend=True)
32
+ else:
33
+ t = cfg.type
34
+ return self.sampler[t](dataset=dataset, **cfg.args)
35
+
36
+ def register():
37
+ def wrapper(class_):
38
+ get_sampler().register(class_)
39
+ return class_
40
+ return wrapper
41
+
42
+ ######################
43
+ # DistributedSampler #
44
+ ######################
45
+
46
+ @register()
47
+ class GlobalDistributedSampler(torch.utils.data.Sampler):
48
+ """
49
+ This is a distributed sampler that sync accross gpus and nodes.
50
+ """
51
+ def __init__(self,
52
+ dataset,
53
+ shuffle=True,
54
+ extend=False,):
55
+ """
56
+ Arguments:
57
+ dataset: Dataset used for sampling.
58
+ shuffle: If true, sampler will shuffle the indices
59
+ extend: If true, sampler will extend the indices that can be even distributed by ranks
60
+ otherwise sampler will truncate the indices to make it even.
61
+ """
62
+ self.ddp = sync.is_ddp()
63
+ self.rank = sync.get_rank('global')
64
+ self.world_size = sync.get_world_size('global')
65
+ self.dataset = dataset
66
+ self.shuffle = shuffle
67
+ self.extend = extend
68
+
69
+ num_samples = len(dataset) // self.world_size
70
+ if extend and (len(dataset)%self.world_size != 0):
71
+ num_samples+=1
72
+ self.num_samples = num_samples
73
+ self.total_size = num_samples * self.world_size
74
+
75
+ def __iter__(self):
76
+ indices = self.get_sync_order()
77
+ if self.extend:
78
+ # extend using the front indices
79
+ indices = indices+indices[0:self.total_size-len(indices)]
80
+ else:
81
+ # truncate
82
+ indices = indices[0:self.total_size]
83
+ # subsample
84
+ indices = indices[self.rank : len(indices) : self.world_size]
85
+ return iter(indices)
86
+
87
+ def __len__(self):
88
+ return self.num_samples
89
+
90
+ def get_sync_order(self):
91
+ if self.shuffle:
92
+ indices = torch.randperm(len(self.dataset)).to(self.rank)
93
+ if self.ddp:
94
+ dist.broadcast(indices, src=0)
95
+ indices = indices.to('cpu').tolist()
96
+ else:
97
+ indices = list(range(len(self.dataset)))
98
+ print_log('Sampler : {}'.format(str(indices[0:5])) )
99
+ return indices
100
+
101
+ @register()
102
+ class LocalDistributedSampler(GlobalDistributedSampler):
103
+ """
104
+ This is a distributed sampler that sync across gpus within the nodes.
105
+ But not sync across nodes.
106
+ """
107
+ def __init__(self,
108
+ dataset,
109
+ shuffle=True,
110
+ extend=False,):
111
+ super().__init__(dataset, shuffle, extend)
112
+ self.rank = sync.get_rank('local')
113
+ self.world_size = sync.get_world_size('local')
114
+
115
+ def get_sync_order(self):
116
+ if self.shuffle:
117
+ if self.rank == 0:
118
+ indices = list(npr.permutation(len(self.dataset)))
119
+ sync.nodewise_sync().broadcast_r0(indices)
120
+ else:
121
+ indices = sync.nodewise_sync().broadcast_r0(None)
122
+ else:
123
+ indices = list(range(len(self.dataset)))
124
+ print_log('Sampler : {}'.format(str(indices[0:5])) )
125
+ return indices
126
+
127
+ ############################
128
+ # random sample with group #
129
+ ############################
130
+ # Deprecated
131
+
132
+ @register()
133
+ class GroupSampler(torch.utils.data.Sampler):
134
+ """
135
+ This is a new DistributedSampler that sample all index according to group.
136
+ i.e.
137
+ if group_size=3, num_replicas=2, train mode:
138
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
139
+ ==> (group) [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]
140
+ ==> (distribute) process0: [3, 4, 5], (leftover [6, 7, 8, 9, 10])
141
+ process1: [0, 1, 2]
142
+ ==> (group leftover) process0: [3, 4, 5], (leftover [6, 7], [8, 9], 10)
143
+ process1: [0, 1, 2]
144
+ ==> (distribute) process0: [3, 4, 5], [6, 7] (remove 10)
145
+ process1: [0, 1, 2], [8, 9]
146
+
147
+ it will avoid_batchsize=1:
148
+ 0, 1, 2, 3, 4, 5, 6, 7, 8,
149
+ ==> (group) [0, 1, 2], [3, 4, 5], [6, 7, 8]
150
+ ==> (distribute) process0: [3, 4, 5], (leftover [6, 7, 8])
151
+ process1: [0, 1, 2]
152
+ ==> (group leftover) process0: [3, 4, 5], (leftover [6], [7], [8])
153
+ process1: [0, 1, 2]
154
+ ==> (distribute) process0: [3, 4, 5], (remove 6, 7, 8) (because distribute make batchsize 1)
155
+ process1: [0, 1, 2]
156
+
157
+ if group_size=3, num_replicas=2, eval mode:
158
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
159
+ ==> (extend) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10
160
+ ==> (group) [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 10]
161
+ ==> (distribute) process0: [0, 1, 2], [6, 7, 8],
162
+ process1: [3, 4, 5], [9, 10, 10]
163
+ """
164
+
165
+ def __init__(self,
166
+ dataset,
167
+ group_size,
168
+ num_replicas=None,
169
+ rank=None,
170
+ mode='train',):
171
+ if num_replicas is None:
172
+ if not dist.is_available():
173
+ raise ValueError
174
+ num_replicas = dist.get_world_size()
175
+ if rank is None:
176
+ if not dist.is_available():
177
+ raise ValueError
178
+ rank = dist.get_rank()
179
+
180
+ self.dataset = dataset
181
+ self.len_dataset = len(dataset)
182
+ self.group_size = group_size
183
+ self.num_replicas = num_replicas
184
+ self.rank = rank
185
+ self.mode = mode
186
+ len_dataset = self.len_dataset
187
+
188
+ if (len_dataset % num_replicas != 0) and (mode == 'train'):
189
+ # drop the non_aligned
190
+ aligned_indices = np.arange(len_dataset)[:-(len_dataset % num_replicas)]
191
+ aligned_len_dataset = aligned_indices.shape[0]
192
+ elif (len_dataset % num_replicas != 0) and (mode == 'eval'):
193
+ extend = np.array([len_dataset-1 for _ in range(num_replicas - len_dataset % num_replicas)])
194
+ aligned_indices = np.concatenate([range(len_dataset), extend])
195
+ aligned_len_dataset = aligned_indices.shape[0]
196
+ else:
197
+ aligned_indices = np.arange(len_dataset)
198
+ aligned_len_dataset = len_dataset
199
+
200
+ num_even_distributed_groups = aligned_len_dataset // (group_size * num_replicas)
201
+ num_even = num_even_distributed_groups * group_size * num_replicas
202
+
203
+ self.regular_groups = aligned_indices[0:num_even].reshape(-1, group_size)
204
+ self.leftover_groups = aligned_indices[num_even:].reshape(num_replicas, -1)
205
+
206
+ if self.leftover_groups.size == 0:
207
+ self.leftover_groups = None
208
+ elif (self.leftover_groups.shape[-1]==1) and (mode == 'train'):
209
+ # avoid bs=1
210
+ self.leftover_groups = None
211
+
212
+ # a urly way to modify dataset.load_info according to the grouping
213
+ for groupi in self.regular_groups:
214
+ for idx in groupi:
215
+ idx_lowerbd = groupi[0]
216
+ idx_upperbd = groupi[-1]
217
+ idx_reference = (idx_lowerbd+idx_upperbd)//2
218
+ dataset.load_info[idx]['ref_size'] = dataset.load_info[idx_reference]['image_size']
219
+ if self.leftover_groups is not None:
220
+ for groupi in self.leftover_groups:
221
+ for idx in groupi:
222
+ idx_lowerbd = groupi[0]
223
+ idx_upperbd = groupi[-1]
224
+ idx_reference = (idx_lowerbd+idx_upperbd)//2
225
+ dataset.load_info[idx]['ref_size'] = dataset.load_info[idx_reference]['image_size']
226
+
227
+ def concat(self, nparrays, axis=0):
228
+ # a helper for save concaternation
229
+ nparrays = [i for i in nparrays if i.size > 0]
230
+ return np.concatenate(nparrays, axis=axis)
231
+
232
+ def __iter__(self):
233
+ indices = self.get_sync_order()
234
+ return iter(indices)
235
+
236
+ def __len__(self):
237
+ return self.num_samples
238
+
239
+ def get_sync_order(self):
240
+ # g = torch.Generator()
241
+ # g.manual_seed(self.epoch)
242
+
243
+ mode = self.mode
244
+ rank = self.rank
245
+ num_replicas = self.num_replicas
246
+ group_size = self.group_size
247
+ num_groups = len(self.regular_groups)
248
+
249
+ if mode == 'train':
250
+ g_indices = torch.randperm(num_groups).to(rank)
251
+ dist.broadcast(g_indices, src=0)
252
+ g_indices = g_indices.to('cpu').tolist()
253
+ num_groups_per_rank = num_groups // num_replicas
254
+ groups = self.regular_groups[g_indices][num_groups_per_rank*rank : num_groups_per_rank*(rank+1)]
255
+ indices = groups.flatten()
256
+
257
+ if self.leftover_groups is not None:
258
+ leftg_indices = torch.randperm(len(self.leftover_groups)).to(rank)
259
+ dist.broadcast(leftg_indices, src=0)
260
+ leftg_indices = leftg_indices.to('cpu').tolist()
261
+ last = self.leftover_groups[leftg_indices][rank]
262
+ indices = np.concatenate([indices, last], axis=0)
263
+ elif mode == 'eval':
264
+ groups = self.regular_groups.reshape(-1, num_replicas, group_size)[:, rank, :]
265
+ indices = groups.flatten()
266
+ if self.leftover_groups is not None:
267
+ last = self.leftover_groups[rank]
268
+ indices = np.concatenate([indices, last], axis=0)
269
+ else:
270
+ raise ValueError
271
+
272
+ print_log('Sampler RANK {} : {}'.format(rank, str(indices[0:group_size+1])))
273
+ return indices
lib/data_factory/common/ds_transform.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+ import numpy as np
3
+ import numpy.random as npr
4
+ import PIL
5
+
6
+ import torch
7
+ import torchvision
8
+ import xml.etree.ElementTree as ET
9
+ import json
10
+ import copy
11
+ import math
12
+
13
+ def singleton(class_):
14
+ instances = {}
15
+ def getinstance(*args, **kwargs):
16
+ if class_ not in instances:
17
+ instances[class_] = class_(*args, **kwargs)
18
+ return instances[class_]
19
+ return getinstance
20
+
21
+ @singleton
22
+ class get_transform(object):
23
+ def __init__(self):
24
+ self.transform = {}
25
+
26
+ def register(self, transf):
27
+ self.transform[transf.__name__] = transf
28
+
29
+ def __call__(self, cfg):
30
+ if cfg is None:
31
+ return None
32
+ if isinstance(cfg, list):
33
+ loader = []
34
+ for ci in cfg:
35
+ t = ci.type
36
+ loader.append(self.transform[t](**ci.args))
37
+ return compose(loader)
38
+ t = cfg.type
39
+ return self.transform[t](**cfg.args)
40
+
41
+ def register():
42
+ def wrapper(class_):
43
+ get_transform().register(class_)
44
+ return class_
45
+ return wrapper
46
+
47
+ def have(must=[], may=[]):
48
+ """
49
+ The nextgen decorator that have two list of
50
+ input tells what category the transform
51
+ will operate on.
52
+ Args:
53
+ must: [] of str,
54
+ the names of the items that must be included
55
+ inside the element.
56
+ If element[name] exist: do the transform
57
+ If element[name] is None: raise Exception.
58
+ If element[name] not exist: raise Exception.
59
+ may: [] of str,
60
+ the names of the items that may be contained
61
+ inside the element for transform.
62
+ If element[name] exist: do the transform
63
+ If element[name] is None: ignore it.
64
+ If element[name] not exist: ignore it.
65
+ """
66
+ def route(self, item, e, d):
67
+ """
68
+ Route the element to a proper function
69
+ for calculation.
70
+ Args:
71
+ self: object,
72
+ the transform functor.
73
+ item: str,
74
+ the item name of the data.
75
+ e: {},
76
+ the element
77
+ d: nparray, tensor or PIL.Image,
78
+ the data to transform.
79
+ """
80
+ if isinstance(d, np.ndarray):
81
+ dtype = 'nparray'
82
+ elif isinstance(d, torch.Tensor):
83
+ dtype = 'tensor'
84
+ elif isinstance(d, PIL.Image.Image):
85
+ dtype = 'pilimage'
86
+ else:
87
+ raise ValueError
88
+
89
+ # find function by order
90
+ f = None
91
+ for attrname in [
92
+ 'exec_{}_{}'.format(item, dtype),
93
+ 'exec_{}'.format(item),
94
+ 'exec_{}'.format(dtype),
95
+ 'exec']:
96
+ f = getattr(self, attrname, None)
97
+ if f is not None:
98
+ break
99
+ d, e = f(d, e)
100
+ e[item] = d
101
+ return e
102
+
103
+ def wrapper(func):
104
+ def inner(self, e):
105
+ e['imsize_previous'] = e['imsize_current']
106
+ imsize_tag_cnt = 0
107
+ imsize_tag = 'imsize_before_' + self.__class__.__name__
108
+ while True:
109
+ if imsize_tag_cnt != 0:
110
+ tag = imsize_tag + str(imsize_tag_cnt)
111
+ else:
112
+ tag = imsize_tag
113
+ if not tag in e:
114
+ e[tag] = e['imsize_current']
115
+ break
116
+ imsize_tag_cnt += 1
117
+
118
+ e = func(self, e)
119
+ # must transform list
120
+ for item in must:
121
+ try:
122
+ d = e[item]
123
+ except:
124
+ raise ValueError
125
+ if d is None:
126
+ raise ValueError
127
+ e = route(self, item, e, d)
128
+ # may transform list
129
+ for item in may:
130
+ try:
131
+ d = e[item]
132
+ except:
133
+ d = None
134
+ if d is not None:
135
+ e = route(self, item, e, d)
136
+ return e
137
+ return inner
138
+ return wrapper
139
+
140
+ class compose(object):
141
+ def __init__(self, transforms):
142
+ self.transforms = transforms
143
+
144
+ def __call__(self, element):
145
+ for t in self.transforms:
146
+ element = t(element)
147
+ return element
148
+
149
+ class TBase(object):
150
+ def __init__(self):
151
+ pass
152
+
153
+ def exec(self, data, element):
154
+ raise ValueError
155
+
156
+ def rand(self,
157
+ uid,
158
+ tag,
159
+ rand_f,
160
+ *args,
161
+ **kwargs):
162
+ """
163
+ Args:
164
+ uid: string element['unique_id']
165
+ tag: string tells the tag uses when tracking the random number.
166
+ Or the tag to restore the tracked random number.
167
+ rand_f: the random function use to generate random number.
168
+ **kwargs: the argument for the given random function.
169
+ """
170
+ # if rnduh().hdata is not None:
171
+ # return rnduh().get_history(uid, self.__class__.__name__, tag)
172
+ # if rnduh().record_path is None:
173
+ # return rand_f(*args, **kwargs)
174
+ # the special mode to create the random file.
175
+ d = rand_f(*args, **kwargs)
176
+ # rnduh().record(uid, self.__class__.__name__, tag, d)
177
+ return d
lib/evaluator/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .eva_base import get_evaluator
lib/evaluator/eva_base.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.distributed as dist
3
+
4
+ import os
5
+ import os.path as osp
6
+ import numpy as np
7
+ import copy
8
+ import json
9
+
10
+ from ..log_service import print_log
11
+
12
+ def singleton(class_):
13
+ instances = {}
14
+ def getinstance(*args, **kwargs):
15
+ if class_ not in instances:
16
+ instances[class_] = class_(*args, **kwargs)
17
+ return instances[class_]
18
+ return getinstance
19
+
20
+ @singleton
21
+ class get_evaluator(object):
22
+ def __init__(self):
23
+ self.evaluator = {}
24
+
25
+ def register(self, evaf, name):
26
+ self.evaluator[name] = evaf
27
+
28
+ def __call__(self, pipeline_cfg=None):
29
+ if pipeline_cfg is None:
30
+ from . import eva_null
31
+ return self.evaluator['null']()
32
+
33
+ if not isinstance(pipeline_cfg, list):
34
+ t = pipeline_cfg.type
35
+ if t == 'miou':
36
+ from . import eva_miou
37
+ if t == 'psnr':
38
+ from . import eva_psnr
39
+ if t == 'ssim':
40
+ from . import eva_ssim
41
+ if t == 'lpips':
42
+ from . import eva_lpips
43
+ if t == 'fid':
44
+ from . import eva_fid
45
+ return self.evaluator[t](**pipeline_cfg.args)
46
+
47
+ evaluator = []
48
+ for ci in pipeline_cfg:
49
+ t = ci.type
50
+ if t == 'miou':
51
+ from . import eva_miou
52
+ if t == 'psnr':
53
+ from . import eva_psnr
54
+ if t == 'ssim':
55
+ from . import eva_ssim
56
+ if t == 'lpips':
57
+ from . import eva_lpips
58
+ if t == 'fid':
59
+ from . import eva_fid
60
+ evaluator.append(
61
+ self.evaluator[t](**ci.args))
62
+ if len(evaluator) == 0:
63
+ return None
64
+ else:
65
+ return compose(evaluator)
66
+
67
+ def register(name):
68
+ def wrapper(class_):
69
+ get_evaluator().register(class_, name)
70
+ return class_
71
+ return wrapper
72
+
73
+ class base_evaluator(object):
74
+ def __init__(self,
75
+ **args):
76
+ '''
77
+ Args:
78
+ sample_n, int,
79
+ the total number of sample. used in
80
+ distributed sync
81
+ '''
82
+ if not dist.is_available():
83
+ raise ValueError
84
+ self.world_size = dist.get_world_size()
85
+ self.rank = dist.get_rank()
86
+ self.sample_n = None
87
+ self.final = {}
88
+
89
+ def sync(self, data):
90
+ """
91
+ Args:
92
+ data: any,
93
+ the data needs to be broadcasted
94
+ """
95
+ if data is None:
96
+ return None
97
+
98
+ if isinstance(data, tuple):
99
+ data = list(data)
100
+
101
+ if isinstance(data, list):
102
+ data_list = []
103
+ for datai in data:
104
+ data_list.append(self.sync(datai))
105
+ data = [[*i] for i in zip(*data_list)]
106
+ return data
107
+
108
+ data = [
109
+ self.sync_(data, ranki)
110
+ for ranki in range(self.world_size)
111
+ ]
112
+ return data
113
+
114
+ def sync_(self, data, rank):
115
+
116
+ t = type(data)
117
+ is_broadcast = rank == self.rank
118
+
119
+ if t is np.ndarray:
120
+ dtrans = data
121
+ dt = data.dtype
122
+ if dt in [
123
+ int,
124
+ np.bool,
125
+ np.uint8,
126
+ np.int8,
127
+ np.int16,
128
+ np.int32,
129
+ np.int64,]:
130
+ dtt = torch.int64
131
+ elif dt in [
132
+ float,
133
+ np.float16,
134
+ np.float32,
135
+ np.float64,]:
136
+ dtt = torch.float64
137
+
138
+ elif t is str:
139
+ dtrans = np.array(
140
+ [ord(c) for c in data],
141
+ dtype = np.int64
142
+ )
143
+ dt = np.int64
144
+ dtt = torch.int64
145
+ else:
146
+ raise ValueError
147
+
148
+ if is_broadcast:
149
+ n = len(dtrans.shape)
150
+ n = torch.tensor(n).long()
151
+
152
+ n = n.to(self.rank)
153
+ dist.broadcast(n, src=rank)
154
+
155
+ n = list(dtrans.shape)
156
+ n = torch.tensor(n).long()
157
+ n = n.to(self.rank)
158
+ dist.broadcast(n, src=rank)
159
+
160
+ n = torch.tensor(dtrans, dtype=dtt)
161
+ n = n.to(self.rank)
162
+ dist.broadcast(n, src=rank)
163
+ return data
164
+
165
+ n = torch.tensor(0).long()
166
+ n = n.to(self.rank)
167
+ dist.broadcast(n, src=rank)
168
+ n = n.item()
169
+
170
+ n = torch.zeros(n).long()
171
+ n = n.to(self.rank)
172
+ dist.broadcast(n, src=rank)
173
+ n = list(n.to('cpu').numpy())
174
+
175
+ n = torch.zeros(n, dtype=dtt)
176
+ n = n.to(self.rank)
177
+ dist.broadcast(n, src=rank)
178
+ n = n.to('cpu').numpy().astype(dt)
179
+
180
+ if t is np.ndarray:
181
+ return n
182
+ elif t is str:
183
+ n = ''.join([chr(c) for c in n])
184
+ return n
185
+
186
+ def zipzap_arrange(self, data):
187
+ '''
188
+ Order the data so it range like this:
189
+ input [[0, 2, 4, 6], [1, 3, 5, 7]] -> output [0, 1, 2, 3, 4, 5, ...]
190
+ '''
191
+ if isinstance(data[0], list):
192
+ data_new = []
193
+ maxlen = max([len(i) for i in data])
194
+ totlen = sum([len(i) for i in data])
195
+ cnt = 0
196
+ for idx in range(maxlen):
197
+ for datai in data:
198
+ data_new += [datai[idx]]
199
+ cnt += 1
200
+ if cnt >= totlen:
201
+ break
202
+ return data_new
203
+
204
+ elif isinstance(data[0], np.ndarray):
205
+ maxlen = max([i.shape[0] for i in data])
206
+ totlen = sum([i.shape[0] for i in data])
207
+ datai_shape = data[0].shape[1:]
208
+ data = [
209
+ np.concatenate(datai, np.zeros(maxlen-datai.shape[0], *datai_shape), axis=0)
210
+ if datai.shape[0] < maxlen else datai
211
+ for datai in data
212
+ ] # even the array
213
+ data = np.stack(data, axis=1).reshape(-1, *datai_shape)
214
+ data = data[:totlen]
215
+ return data
216
+
217
+ else:
218
+ raise NotImplementedError
219
+
220
+ def add_batch(self, **args):
221
+ raise NotImplementedError
222
+
223
+ def set_sample_n(self, sample_n):
224
+ self.sample_n = sample_n
225
+
226
+ def compute(self):
227
+ raise NotImplementedError
228
+
229
+ # Function needed in training to judge which
230
+ # evaluated number is better
231
+ def isbetter(self, old, new):
232
+ return new>old
233
+
234
+ def one_line_summary(self):
235
+ print_log('Evaluator display')
236
+
237
+ def save(self, path):
238
+ if not osp.exists(path):
239
+ os.makedirs(path)
240
+ ofile = osp.join(path, 'result.json')
241
+ with open(ofile, 'w') as f:
242
+ json.dump(self.final, f, indent=4)
243
+
244
+ def clear_data(self):
245
+ raise NotImplementedError
246
+
247
+ class compose(object):
248
+ def __init__(self, pipeline):
249
+ self.pipeline = pipeline
250
+ self.sample_n = None
251
+ self.final = {}
252
+
253
+ def add_batch(self, *args, **kwargs):
254
+ for pi in self.pipeline:
255
+ pi.add_batch(*args, **kwargs)
256
+
257
+ def set_sample_n(self, sample_n):
258
+ self.sample_n = sample_n
259
+ for pi in self.pipeline:
260
+ pi.set_sample_n(sample_n)
261
+
262
+ def compute(self):
263
+ rv = {}
264
+ for pi in self.pipeline:
265
+ rv[pi.symbol] = pi.compute()
266
+ self.final[pi.symbol] = pi.final
267
+ return rv
268
+
269
+ def isbetter(self, old, new):
270
+ check = 0
271
+ for pi in self.pipeline:
272
+ if pi.isbetter(old, new):
273
+ check+=1
274
+ if check/len(self.pipeline)>0.5:
275
+ return True
276
+ else:
277
+ return False
278
+
279
+ def one_line_summary(self):
280
+ for pi in self.pipeline:
281
+ pi.one_line_summary()
282
+
283
+ def save(self, path):
284
+ if not osp.exists(path):
285
+ os.makedirs(path)
286
+ ofile = osp.join(path, 'result.json')
287
+ with open(ofile, 'w') as f:
288
+ json.dump(self.final, f, indent=4)
289
+
290
+ def clear_data(self):
291
+ for pi in self.pipeline:
292
+ pi.clear_data()
lib/evaluator/eva_null.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+ from .. import nputils
5
+ from ..log_service import print_log
6
+
7
+ from .eva_base import base_evaluator, register
8
+
9
+ @register('null')
10
+ class null_evaluator(base_evaluator):
11
+ def __init__(self, **dummy):
12
+ super().__init__()
13
+
14
+ def add_batch(self,
15
+ **dummy):
16
+ pass
17
+
18
+ def compute(self):
19
+ return None
20
+
21
+ def one_line_summary(self):
22
+ print_log('Evaluator null')
23
+
24
+ def clear_data(self):
25
+ pass
lib/experiments/__init__.py ADDED
File without changes
lib/experiments/sd_default.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.distributed as dist
3
+ from torchvision import transforms as tvtrans
4
+ import os
5
+ import os.path as osp
6
+ import time
7
+ import timeit
8
+ import copy
9
+ import json
10
+ import pickle
11
+ import PIL.Image
12
+ import numpy as np
13
+ from datetime import datetime
14
+ from easydict import EasyDict as edict
15
+ from collections import OrderedDict
16
+
17
+ from lib.cfg_holder import cfg_unique_holder as cfguh
18
+ from lib.data_factory import get_dataset, get_sampler, collate
19
+ from lib.model_zoo import \
20
+ get_model, get_optimizer, get_scheduler
21
+ from lib.log_service import print_log
22
+
23
+ from ..utils import train as train_base
24
+ from ..utils import eval as eval_base
25
+ from ..utils import train_stage as tsbase
26
+ from ..utils import eval_stage as esbase
27
+ from .. import sync
28
+
29
+ ###############
30
+ # some helper #
31
+ ###############
32
+
33
+ def atomic_save(cfg, net, opt, step, path):
34
+ if isinstance(net, (torch.nn.DataParallel,
35
+ torch.nn.parallel.DistributedDataParallel)):
36
+ netm = net.module
37
+ else:
38
+ netm = net
39
+ sd = netm.state_dict()
40
+ slimmed_sd = [(ki, vi) for ki, vi in sd.items()
41
+ if ki.find('first_stage_model')!=0 and ki.find('cond_stage_model')!=0]
42
+
43
+ checkpoint = {
44
+ "config" : cfg,
45
+ "state_dict" : OrderedDict(slimmed_sd),
46
+ "step" : step}
47
+ if opt is not None:
48
+ checkpoint['optimizer_states'] = opt.state_dict()
49
+ import io
50
+ import fsspec
51
+ bytesbuffer = io.BytesIO()
52
+ torch.save(checkpoint, bytesbuffer)
53
+ with fsspec.open(path, "wb") as f:
54
+ f.write(bytesbuffer.getvalue())
55
+
56
+ def load_state_dict(net, cfg):
57
+ pretrained_pth_full = cfg.get('pretrained_pth_full' , None)
58
+ pretrained_ckpt_full = cfg.get('pretrained_ckpt_full', None)
59
+ pretrained_pth = cfg.get('pretrained_pth' , None)
60
+ pretrained_ckpt = cfg.get('pretrained_ckpt' , None)
61
+ pretrained_pth_dm = cfg.get('pretrained_pth_dm' , None)
62
+ pretrained_pth_ema = cfg.get('pretrained_pth_ema' , None)
63
+ strict_sd = cfg.get('strict_sd', False)
64
+ errmsg = "Overlapped model state_dict! This is undesired behavior!"
65
+
66
+ if pretrained_pth_full is not None or pretrained_ckpt_full is not None:
67
+ assert (pretrained_pth is None) and \
68
+ (pretrained_ckpt is None) and \
69
+ (pretrained_pth_dm is None) and \
70
+ (pretrained_pth_ema is None), errmsg
71
+ if pretrained_pth_full is not None:
72
+ target_file = pretrained_pth_full
73
+ sd = torch.load(target_file, map_location='cpu')
74
+ assert pretrained_ckpt is None, errmsg
75
+ else:
76
+ target_file = pretrained_ckpt_full
77
+ sd = torch.load(target_file, map_location='cpu')['state_dict']
78
+ print_log('Load full model from [{}] strict [{}].'.format(
79
+ target_file, strict_sd))
80
+ net.load_state_dict(sd, strict=strict_sd)
81
+
82
+ if pretrained_pth is not None or pretrained_ckpt is not None:
83
+ assert (pretrained_ckpt_full is None) and \
84
+ (pretrained_pth_full is None) and \
85
+ (pretrained_pth_dm is None) and \
86
+ (pretrained_pth_ema is None), errmsg
87
+ if pretrained_pth is not None:
88
+ target_file = pretrained_pth
89
+ sd = torch.load(target_file, map_location='cpu')
90
+ assert pretrained_ckpt is None, errmsg
91
+ else:
92
+ target_file = pretrained_ckpt
93
+ sd = torch.load(target_file, map_location='cpu')['state_dict']
94
+ print_log('Load model from [{}] strict [{}].'.format(
95
+ target_file, strict_sd))
96
+ sd_extra = [(ki, vi) for ki, vi in net.state_dict().items() \
97
+ if ki.find('first_stage_model')==0 or ki.find('cond_stage_model')==0]
98
+ sd.update(OrderedDict(sd_extra))
99
+ net.load_state_dict(sd, strict=strict_sd)
100
+
101
+ if pretrained_pth_dm is not None:
102
+ assert (pretrained_ckpt_full is None) and \
103
+ (pretrained_pth_full is None) and \
104
+ (pretrained_pth is None) and \
105
+ (pretrained_ckpt is None), errmsg
106
+ print_log('Load diffusion model from [{}] strict [{}].'.format(
107
+ pretrained_pth_dm, strict_sd))
108
+ sd = torch.load(pretrained_pth_dm, map_location='cpu')
109
+ net.model.diffusion_model.load_state_dict(sd, strict=strict_sd)
110
+
111
+ if pretrained_pth_ema is not None:
112
+ assert (pretrained_ckpt_full is None) and \
113
+ (pretrained_pth_full is None) and \
114
+ (pretrained_pth is None) and \
115
+ (pretrained_ckpt is None), errmsg
116
+ print_log('Load unet ema model from [{}] strict [{}].'.format(
117
+ pretrained_pth_ema, strict_sd))
118
+ sd = torch.load(pretrained_pth_ema, map_location='cpu')
119
+ net.model_ema.load_state_dict(sd, strict=strict_sd)
120
+
121
+ def auto_merge_imlist(imlist, max=64):
122
+ imlist = imlist[0:max]
123
+ h, w = imlist[0].shape[0:2]
124
+ num_images = len(imlist)
125
+ num_row = int(np.sqrt(num_images))
126
+ num_col = num_images//num_row + 1 if num_images%num_row!=0 else num_images//num_row
127
+ canvas = np.zeros([num_row*h, num_col*w, 3], dtype=np.uint8)
128
+ for idx, im in enumerate(imlist):
129
+ hi = (idx // num_col) * h
130
+ wi = (idx % num_col) * w
131
+ canvas[hi:hi+h, wi:wi+w, :] = im
132
+ return canvas
133
+
134
+ def latent2im(net, latent):
135
+ single_input = len(latent.shape) == 3
136
+ if single_input:
137
+ latent = latent[None]
138
+ im = net.decode_image(latent.to(net.device))
139
+ im = torch.clamp((im+1.0)/2.0, min=0.0, max=1.0)
140
+ im = [tvtrans.ToPILImage()(i) for i in im]
141
+ if single_input:
142
+ im = im[0]
143
+ return im
144
+
145
+ def im2latent(net, im):
146
+ single_input = not isinstance(im, list)
147
+ if single_input:
148
+ im = [im]
149
+ im = torch.stack([tvtrans.ToTensor()(i) for i in im], dim=0)
150
+ im = (im*2-1).to(net.device)
151
+ z = net.encode_image(im)
152
+ if single_input:
153
+ z = z[0]
154
+ return z
155
+
156
+ class color_adjust(object):
157
+ def __init__(self, ref_from, ref_to):
158
+ x0, m0, std0 = self.get_data_and_stat(ref_from)
159
+ x1, m1, std1 = self.get_data_and_stat(ref_to)
160
+ self.ref_from_stat = (m0, std0)
161
+ self.ref_to_stat = (m1, std1)
162
+ self.ref_from = self.preprocess(x0).reshape(-1, 3)
163
+ self.ref_to = x1.reshape(-1, 3)
164
+
165
+ def get_data_and_stat(self, x):
166
+ if isinstance(x, str):
167
+ x = np.array(PIL.Image.open(x))
168
+ elif isinstance(x, PIL.Image.Image):
169
+ x = np.array(x)
170
+ elif isinstance(x, torch.Tensor):
171
+ x = torch.clamp(x, min=0.0, max=1.0)
172
+ x = np.array(tvtrans.ToPILImage()(x))
173
+ elif isinstance(x, np.ndarray):
174
+ pass
175
+ else:
176
+ raise ValueError
177
+ x = x.astype(float)
178
+ m = np.reshape(x, (-1, 3)).mean(0)
179
+ s = np.reshape(x, (-1, 3)).std(0)
180
+ return x, m, s
181
+
182
+ def preprocess(self, x):
183
+ m0, s0 = self.ref_from_stat
184
+ m1, s1 = self.ref_to_stat
185
+ y = ((x-m0)/s0)*s1 + m1
186
+ return y
187
+
188
+ def __call__(self, xin, keep=0, simple=False):
189
+ xin, _, _ = self.get_data_and_stat(xin)
190
+ x = self.preprocess(xin)
191
+ if simple:
192
+ y = (x*(1-keep) + xin*keep)
193
+ y = np.clip(y, 0, 255).astype(np.uint8)
194
+ return y
195
+
196
+ h, w = x.shape[:2]
197
+ x = x.reshape(-1, 3)
198
+ y = []
199
+ for chi in range(3):
200
+ yi = self.pdf_transfer_1d(self.ref_from[:, chi], self.ref_to[:, chi], x[:, chi])
201
+ y.append(yi)
202
+
203
+ y = np.stack(y, axis=1)
204
+ y = y.reshape(h, w, 3)
205
+ y = (y.astype(float)*(1-keep) + xin.astype(float)*keep)
206
+ y = np.clip(y, 0, 255).astype(np.uint8)
207
+ return y
208
+
209
+ def pdf_transfer_1d(self, arr_fo, arr_to, arr_in, n=600):
210
+ arr = np.concatenate((arr_fo, arr_to))
211
+ min_v = arr.min() - 1e-6
212
+ max_v = arr.max() + 1e-6
213
+ min_vto = arr_to.min() - 1e-6
214
+ max_vto = arr_to.max() + 1e-6
215
+ xs = np.array(
216
+ [min_v + (max_v - min_v) * i / n for i in range(n + 1)])
217
+ hist_fo, _ = np.histogram(arr_fo, xs)
218
+ hist_to, _ = np.histogram(arr_to, xs)
219
+ xs = xs[:-1]
220
+ # compute probability distribution
221
+ cum_fo = np.cumsum(hist_fo)
222
+ cum_to = np.cumsum(hist_to)
223
+ d_fo = cum_fo / cum_fo[-1]
224
+ d_to = cum_to / cum_to[-1]
225
+ # transfer
226
+ t_d = np.interp(d_fo, d_to, xs)
227
+ t_d[d_fo <= d_to[ 0]] = min_vto
228
+ t_d[d_fo >= d_to[-1]] = max_vto
229
+ arr_out = np.interp(arr_in, xs, t_d)
230
+ return arr_out
231
+
232
+ ########
233
+ # main #
234
+ ########
235
+
236
+ class eval(eval_base):
237
+ def prepare_model(self):
238
+ cfg = cfguh().cfg
239
+ net = get_model()(cfg.model)
240
+ if cfg.env.cuda:
241
+ net.to(self.local_rank)
242
+ load_state_dict(net, cfg.eval) #<--- added
243
+ net = torch.nn.parallel.DistributedDataParallel(
244
+ net, device_ids=[self.local_rank],
245
+ find_unused_parameters=True)
246
+ net.eval()
247
+ return {'net' : net,}
248
+
249
+ class eval_stage(esbase):
250
+ """
251
+ This is eval stage that can check comprehensive results
252
+ """
253
+ def __init__(self):
254
+ from ..model_zoo.ddim import DDIMSampler
255
+ self.sampler = DDIMSampler
256
+
257
+ def get_net(self, paras):
258
+ return paras['net']
259
+
260
+ def get_image_path(self):
261
+ if 'train' in cfguh().cfg:
262
+ log_dir = cfguh().cfg.train.log_dir
263
+ else:
264
+ log_dir = cfguh().cfg.eval.log_dir
265
+ return os.path.join(log_dir, "udemo")
266
+
267
+ @torch.no_grad()
268
+ def sample(self, net, sampler, prompt, output_dim, scale, n_samples, ddim_steps, ddim_eta):
269
+ h, w = output_dim
270
+ uc = None
271
+ if scale != 1.0:
272
+ uc = net.get_learned_conditioning(n_samples * [""])
273
+ c = net.get_learned_conditioning(n_samples * [prompt])
274
+ shape = [4, h//8, w//8]
275
+ rv = sampler.sample(
276
+ S=ddim_steps,
277
+ conditioning=c,
278
+ batch_size=n_samples,
279
+ shape=shape,
280
+ verbose=False,
281
+ unconditional_guidance_scale=scale,
282
+ unconditional_conditioning=uc,
283
+ eta=ddim_eta)
284
+ return rv
285
+
286
+ def save_images(self, pil_list, name, path, suffix=''):
287
+ canvas = auto_merge_imlist([np.array(i) for i in pil_list])
288
+ image_name = '{}{}.png'.format(name, suffix)
289
+ PIL.Image.fromarray(canvas).save(osp.join(path, image_name))
290
+
291
+ def __call__(self, **paras):
292
+ cfg = cfguh().cfg
293
+ cfgv = cfg.eval
294
+
295
+ net = paras['net']
296
+ eval_cnt = paras.get('eval_cnt', None)
297
+ fix_seed = cfgv.get('fix_seed', False)
298
+
299
+ LRANK = sync.get_rank('local')
300
+ LWSIZE = sync.get_world_size('local')
301
+
302
+ image_path = self.get_image_path()
303
+ self.create_dir(image_path)
304
+ eval_cnt = paras.get('eval_cnt', None)
305
+ suffix='' if eval_cnt is None else '_itern'+str(eval_cnt)
306
+
307
+ if isinstance(net, (torch.nn.DataParallel,
308
+ torch.nn.parallel.DistributedDataParallel)):
309
+ netm = net.module
310
+ else:
311
+ netm = net
312
+
313
+ with_ema = getattr(netm, 'model_ema', None) is not None
314
+ sampler = self.sampler(netm)
315
+ setattr(netm, 'device', LRANK) # Trick
316
+
317
+ replicate = cfgv.get('replicate', 1)
318
+ conditioning = cfgv.conditioning * replicate
319
+ conditioning_local = conditioning[LRANK : len(conditioning) : LWSIZE]
320
+ seed_increment = [i for i in range(len(conditioning))][LRANK : len(conditioning) : LWSIZE]
321
+
322
+ for prompti, seedi in zip(conditioning_local, seed_increment):
323
+ if prompti == 'SKIP':
324
+ continue
325
+ draw_filename = prompti.strip().replace(' ', '-')
326
+ if fix_seed:
327
+ np.random.seed(cfg.env.rnd_seed + seedi)
328
+ torch.manual_seed(cfg.env.rnd_seed + seedi + 100)
329
+ suffixi = suffix + "_seed{}".format(cfg.env.rnd_seed + seedi + 100)
330
+ else:
331
+ suffixi = suffix
332
+
333
+ if with_ema:
334
+ with netm.ema_scope():
335
+ x, _ = self.sample(netm, sampler, prompti, **cfgv.sample)
336
+ else:
337
+ x, _ = self.sample(netm, sampler, prompti, **cfgv.sample)
338
+
339
+ demo_image = latent2im(netm, x)
340
+ self.save_images(demo_image, draw_filename, image_path, suffix=suffixi)
341
+
342
+ if eval_cnt is not None:
343
+ print_log('Demo printed for {}'.format(eval_cnt))
344
+ return {}
345
+
346
+ ##################
347
+ # eval variation #
348
+ ##################
349
+
350
+ class eval_stage_variation(eval_stage):
351
+ @torch.no_grad()
352
+ def sample(self, net, sampler, visual_hint, output_dim, scale, n_samples, ddim_steps, ddim_eta):
353
+ h, w = output_dim
354
+ vh = tvtrans.ToTensor()(PIL.Image.open(visual_hint))[None].to(net.device)
355
+ c = net.get_learned_conditioning(vh)
356
+ c = c.repeat(n_samples, 1, 1)
357
+ uc = None
358
+ if scale != 1.0:
359
+ dummy = torch.zeros_like(vh)
360
+ uc = net.get_learned_conditioning(dummy)
361
+ uc = uc.repeat(n_samples, 1, 1)
362
+
363
+ shape = [4, h//8, w//8]
364
+ rv = sampler.sample(
365
+ S=ddim_steps,
366
+ conditioning=c,
367
+ batch_size=n_samples,
368
+ shape=shape,
369
+ verbose=False,
370
+ unconditional_guidance_scale=scale,
371
+ unconditional_conditioning=uc,
372
+ eta=ddim_eta)
373
+ return rv
374
+
375
+ def __call__(self, **paras):
376
+ cfg = cfguh().cfg
377
+ cfgv = cfg.eval
378
+
379
+ net = paras['net']
380
+ eval_cnt = paras.get('eval_cnt', None)
381
+ fix_seed = cfgv.get('fix_seed', False)
382
+
383
+ LRANK = sync.get_rank('local')
384
+ LWSIZE = sync.get_world_size('local')
385
+
386
+ image_path = self.get_image_path()
387
+ self.create_dir(image_path)
388
+ eval_cnt = paras.get('eval_cnt', None)
389
+ suffix='' if eval_cnt is None else '_'+str(eval_cnt)
390
+
391
+ if isinstance(net, (torch.nn.DataParallel,
392
+ torch.nn.parallel.DistributedDataParallel)):
393
+ netm = net.module
394
+ else:
395
+ netm = net
396
+
397
+ with_ema = getattr(netm, 'model_ema', None) is not None
398
+ sampler = self.sampler(netm)
399
+ setattr(netm, 'device', LRANK) # Trick
400
+
401
+ color_adj = cfguh().cfg.eval.get('color_adj', False)
402
+ color_adj_keep_ratio = cfguh().cfg.eval.get('color_adj_keep_ratio', 0.5)
403
+ color_adj_simple = cfguh().cfg.eval.get('color_adj_simple', True)
404
+
405
+ replicate = cfgv.get('replicate', 1)
406
+ conditioning = cfgv.conditioning * replicate
407
+ conditioning_local = conditioning[LRANK : len(conditioning) : LWSIZE]
408
+ seed_increment = [i for i in range(len(conditioning))][LRANK : len(conditioning) : LWSIZE]
409
+
410
+ for ci, seedi in zip(conditioning_local, seed_increment):
411
+ if ci == 'SKIP':
412
+ continue
413
+
414
+ draw_filename = osp.splitext(osp.basename(ci))[0]
415
+
416
+ if fix_seed:
417
+ np.random.seed(cfg.env.rnd_seed + seedi)
418
+ torch.manual_seed(cfg.env.rnd_seed + seedi + 100)
419
+ suffixi = suffix + "_seed{}".format(cfg.env.rnd_seed + seedi + 100)
420
+ else:
421
+ suffixi = suffix
422
+
423
+ if with_ema:
424
+ with netm.ema_scope():
425
+ x, _ = self.sample(netm, sampler, ci, **cfgv.sample)
426
+ else:
427
+ x, _ = self.sample(netm, sampler, ci, **cfgv.sample)
428
+
429
+ demo_image = latent2im(netm, x)
430
+ if color_adj:
431
+ x_adj = []
432
+ for demoi in demo_image:
433
+ color_adj_f = color_adjust(ref_from=demoi, ref_to=ci)
434
+ xi_adj = color_adj_f(demoi, keep=color_adj_keep_ratio, simple=color_adj_simple)
435
+ x_adj.append(xi_adj)
436
+ demo_image = x_adj
437
+ self.save_images(demo_image, draw_filename, image_path, suffix=suffixi)
438
+
439
+ if eval_cnt is not None:
440
+ print_log('Demo printed for {}'.format(eval_cnt))
441
+ return {}
lib/log_service.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import timeit
2
+ import numpy as np
3
+ import os
4
+ import os.path as osp
5
+ import shutil
6
+ import copy
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.distributed as dist
10
+ from .cfg_holder import cfg_unique_holder as cfguh
11
+ from . import sync
12
+
13
+ print_console_local_rank0_only = True
14
+
15
+ def print_log(*console_info):
16
+ local_rank = sync.get_rank('local')
17
+ if print_console_local_rank0_only and (local_rank!=0):
18
+ return
19
+ console_info = [str(i) for i in console_info]
20
+ console_info = ' '.join(console_info)
21
+ print(console_info)
22
+
23
+ if local_rank!=0:
24
+ return
25
+
26
+ log_file = None
27
+ try:
28
+ log_file = cfguh().cfg.train.log_file
29
+ except:
30
+ try:
31
+ log_file = cfguh().cfg.eval.log_file
32
+ except:
33
+ return
34
+ if log_file is not None:
35
+ with open(log_file, 'a') as f:
36
+ f.write(console_info + '\n')
37
+
38
+ class distributed_log_manager(object):
39
+ def __init__(self):
40
+ self.sum = {}
41
+ self.cnt = {}
42
+ self.time_check = timeit.default_timer()
43
+
44
+ cfgt = cfguh().cfg.train
45
+ use_tensorboard = getattr(cfgt, 'log_tensorboard', False)
46
+
47
+ self.ddp = sync.is_ddp()
48
+ self.rank = sync.get_rank('local')
49
+ self.world_size = sync.get_world_size('local')
50
+
51
+ self.tb = None
52
+ if use_tensorboard and (self.rank==0):
53
+ import tensorboardX
54
+ monitoring_dir = osp.join(cfguh().cfg.train.log_dir, 'tensorboard')
55
+ self.tb = tensorboardX.SummaryWriter(osp.join(monitoring_dir))
56
+
57
+ def accumulate(self, n, **data):
58
+ if n < 0:
59
+ raise ValueError
60
+
61
+ for itemn, di in data.items():
62
+ if itemn in self.sum:
63
+ self.sum[itemn] += di * n
64
+ self.cnt[itemn] += n
65
+ else:
66
+ self.sum[itemn] = di * n
67
+ self.cnt[itemn] = n
68
+
69
+ def get_mean_value_dict(self):
70
+ value_gather = [
71
+ self.sum[itemn]/self.cnt[itemn] \
72
+ for itemn in sorted(self.sum.keys()) ]
73
+
74
+ value_gather_tensor = torch.FloatTensor(value_gather).to(self.rank)
75
+ if self.ddp:
76
+ dist.all_reduce(value_gather_tensor, op=dist.ReduceOp.SUM)
77
+ value_gather_tensor /= self.world_size
78
+
79
+ mean = {}
80
+ for idx, itemn in enumerate(sorted(self.sum.keys())):
81
+ mean[itemn] = value_gather_tensor[idx].item()
82
+ return mean
83
+
84
+ def tensorboard_log(self, step, data, mode='train', **extra):
85
+ if self.tb is None:
86
+ return
87
+ if mode == 'train':
88
+ self.tb.add_scalar('other/epochn', extra['epochn'], step)
89
+ if 'lr' in extra:
90
+ self.tb.add_scalar('other/lr', extra['lr'], step)
91
+ for itemn, di in data.items():
92
+ if itemn.find('loss') == 0:
93
+ self.tb.add_scalar('loss/'+itemn, di, step)
94
+ elif itemn == 'Loss':
95
+ self.tb.add_scalar('Loss', di, step)
96
+ else:
97
+ self.tb.add_scalar('other/'+itemn, di, step)
98
+ elif mode == 'eval':
99
+ if isinstance(data, dict):
100
+ for itemn, di in data.items():
101
+ self.tb.add_scalar('eval/'+itemn, di, step)
102
+ else:
103
+ self.tb.add_scalar('eval', data, step)
104
+ return
105
+
106
+ def train_summary(self, itern, epochn, samplen, lr, tbstep=None):
107
+ console_info = [
108
+ 'Iter:{}'.format(itern),
109
+ 'Epoch:{}'.format(epochn),
110
+ 'Sample:{}'.format(samplen),]
111
+
112
+ if lr is not None:
113
+ console_info += ['LR:{:.4E}'.format(lr)]
114
+
115
+ mean = self.get_mean_value_dict()
116
+
117
+ tbstep = itern if tbstep is None else tbstep
118
+ self.tensorboard_log(
119
+ tbstep, mean, mode='train',
120
+ itern=itern, epochn=epochn, lr=lr)
121
+
122
+ loss = mean.pop('Loss')
123
+ mean_info = ['Loss:{:.4f}'.format(loss)] + [
124
+ '{}:{:.4f}'.format(itemn, mean[itemn]) \
125
+ for itemn in sorted(mean.keys()) \
126
+ if itemn.find('loss') == 0
127
+ ]
128
+ console_info += mean_info
129
+ console_info.append('Time:{:.2f}s'.format(
130
+ timeit.default_timer() - self.time_check))
131
+ return ' , '.join(console_info)
132
+
133
+ def clear(self):
134
+ self.sum = {}
135
+ self.cnt = {}
136
+ self.time_check = timeit.default_timer()
137
+
138
+ def tensorboard_close(self):
139
+ if self.tb is not None:
140
+ self.tb.close()
141
+
142
+ # ----- also include some small utils -----
143
+
144
+ def torch_to_numpy(*argv):
145
+ if len(argv) > 1:
146
+ data = list(argv)
147
+ else:
148
+ data = argv[0]
149
+
150
+ if isinstance(data, torch.Tensor):
151
+ return data.to('cpu').detach().numpy()
152
+
153
+ elif isinstance(data, (list, tuple)):
154
+ out = []
155
+ for di in data:
156
+ out.append(torch_to_numpy(di))
157
+ return out
158
+
159
+ elif isinstance(data, dict):
160
+ out = {}
161
+ for ni, di in data.items():
162
+ out[ni] = torch_to_numpy(di)
163
+ return out
164
+
165
+ else:
166
+ return data
lib/model_zoo/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .common.get_model import get_model
2
+ from .common.get_optimizer import get_optimizer
3
+ from .common.get_scheduler import get_scheduler
4
+ from .common.utils import get_unit
lib/model_zoo/attention.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from inspect import isfunction
2
+ import math
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn, einsum
6
+ from einops import rearrange, repeat
7
+
8
+ from .diffusion_utils import checkpoint
9
+
10
+
11
+ def exists(val):
12
+ return val is not None
13
+
14
+
15
+ def uniq(arr):
16
+ return{el: True for el in arr}.keys()
17
+
18
+
19
+ def default(val, d):
20
+ if exists(val):
21
+ return val
22
+ return d() if isfunction(d) else d
23
+
24
+
25
+ def max_neg_value(t):
26
+ return -torch.finfo(t.dtype).max
27
+
28
+
29
+ def init_(tensor):
30
+ dim = tensor.shape[-1]
31
+ std = 1 / math.sqrt(dim)
32
+ tensor.uniform_(-std, std)
33
+ return tensor
34
+
35
+
36
+ # feedforward
37
+ class GEGLU(nn.Module):
38
+ def __init__(self, dim_in, dim_out):
39
+ super().__init__()
40
+ self.proj = nn.Linear(dim_in, dim_out * 2)
41
+
42
+ def forward(self, x):
43
+ x, gate = self.proj(x).chunk(2, dim=-1)
44
+ return x * F.gelu(gate)
45
+
46
+
47
+ class FeedForward(nn.Module):
48
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
49
+ super().__init__()
50
+ inner_dim = int(dim * mult)
51
+ dim_out = default(dim_out, dim)
52
+ project_in = nn.Sequential(
53
+ nn.Linear(dim, inner_dim),
54
+ nn.GELU()
55
+ ) if not glu else GEGLU(dim, inner_dim)
56
+
57
+ self.net = nn.Sequential(
58
+ project_in,
59
+ nn.Dropout(dropout),
60
+ nn.Linear(inner_dim, dim_out)
61
+ )
62
+
63
+ def forward(self, x):
64
+ return self.net(x)
65
+
66
+
67
+ def zero_module(module):
68
+ """
69
+ Zero out the parameters of a module and return it.
70
+ """
71
+ for p in module.parameters():
72
+ p.detach().zero_()
73
+ return module
74
+
75
+
76
+ def Normalize(in_channels):
77
+ return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
78
+
79
+
80
+ class LinearAttention(nn.Module):
81
+ def __init__(self, dim, heads=4, dim_head=32):
82
+ super().__init__()
83
+ self.heads = heads
84
+ hidden_dim = dim_head * heads
85
+ self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
86
+ self.to_out = nn.Conv2d(hidden_dim, dim, 1)
87
+
88
+ def forward(self, x):
89
+ b, c, h, w = x.shape
90
+ qkv = self.to_qkv(x)
91
+ q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
92
+ k = k.softmax(dim=-1)
93
+ context = torch.einsum('bhdn,bhen->bhde', k, v)
94
+ out = torch.einsum('bhde,bhdn->bhen', context, q)
95
+ out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
96
+ return self.to_out(out)
97
+
98
+
99
+ class SpatialSelfAttention(nn.Module):
100
+ def __init__(self, in_channels):
101
+ super().__init__()
102
+ self.in_channels = in_channels
103
+
104
+ self.norm = Normalize(in_channels)
105
+ self.q = torch.nn.Conv2d(in_channels,
106
+ in_channels,
107
+ kernel_size=1,
108
+ stride=1,
109
+ padding=0)
110
+ self.k = torch.nn.Conv2d(in_channels,
111
+ in_channels,
112
+ kernel_size=1,
113
+ stride=1,
114
+ padding=0)
115
+ self.v = torch.nn.Conv2d(in_channels,
116
+ in_channels,
117
+ kernel_size=1,
118
+ stride=1,
119
+ padding=0)
120
+ self.proj_out = torch.nn.Conv2d(in_channels,
121
+ in_channels,
122
+ kernel_size=1,
123
+ stride=1,
124
+ padding=0)
125
+
126
+ def forward(self, x):
127
+ h_ = x
128
+ h_ = self.norm(h_)
129
+ q = self.q(h_)
130
+ k = self.k(h_)
131
+ v = self.v(h_)
132
+
133
+ # compute attention
134
+ b,c,h,w = q.shape
135
+ q = rearrange(q, 'b c h w -> b (h w) c')
136
+ k = rearrange(k, 'b c h w -> b c (h w)')
137
+ w_ = torch.einsum('bij,bjk->bik', q, k)
138
+
139
+ w_ = w_ * (int(c)**(-0.5))
140
+ w_ = torch.nn.functional.softmax(w_, dim=2)
141
+
142
+ # attend to values
143
+ v = rearrange(v, 'b c h w -> b c (h w)')
144
+ w_ = rearrange(w_, 'b i j -> b j i')
145
+ h_ = torch.einsum('bij,bjk->bik', v, w_)
146
+ h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
147
+ h_ = self.proj_out(h_)
148
+
149
+ return x+h_
150
+
151
+
152
+ class CrossAttention(nn.Module):
153
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
154
+ super().__init__()
155
+ inner_dim = dim_head * heads
156
+ context_dim = default(context_dim, query_dim)
157
+
158
+ self.scale = dim_head ** -0.5
159
+ self.heads = heads
160
+
161
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
162
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
163
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
164
+
165
+ self.to_out = nn.Sequential(
166
+ nn.Linear(inner_dim, query_dim),
167
+ nn.Dropout(dropout)
168
+ )
169
+
170
+ def forward(self, x, context=None, mask=None):
171
+ h = self.heads
172
+
173
+ q = self.to_q(x)
174
+ context = default(context, x)
175
+ k = self.to_k(context)
176
+ v = self.to_v(context)
177
+
178
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
179
+
180
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
181
+
182
+ if exists(mask):
183
+ mask = rearrange(mask, 'b ... -> b (...)')
184
+ max_neg_value = -torch.finfo(sim.dtype).max
185
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
186
+ sim.masked_fill_(~mask, max_neg_value)
187
+
188
+ # attention, what we cannot get enough of
189
+ attn = sim.softmax(dim=-1)
190
+
191
+ out = einsum('b i j, b j d -> b i d', attn, v)
192
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
193
+ return self.to_out(out)
194
+
195
+
196
+ class BasicTransformerBlock(nn.Module):
197
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
198
+ disable_self_attn=False):
199
+ super().__init__()
200
+ self.disable_self_attn = disable_self_attn
201
+ self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
202
+ context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attn
203
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
204
+ self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
205
+ heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
206
+ self.norm1 = nn.LayerNorm(dim)
207
+ self.norm2 = nn.LayerNorm(dim)
208
+ self.norm3 = nn.LayerNorm(dim)
209
+ self.checkpoint = checkpoint
210
+
211
+ def forward(self, x, context=None):
212
+ return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
213
+
214
+ def _forward(self, x, context=None):
215
+ x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
216
+ x = self.attn2(self.norm2(x), context=context) + x
217
+ x = self.ff(self.norm3(x)) + x
218
+ return x
219
+
220
+
221
+ class SpatialTransformer(nn.Module):
222
+ """
223
+ Transformer block for image-like data.
224
+ First, project the input (aka embedding)
225
+ and reshape to b, t, d.
226
+ Then apply standard transformer action.
227
+ Finally, reshape to image
228
+ """
229
+ def __init__(self, in_channels, n_heads, d_head,
230
+ depth=1, dropout=0., context_dim=None,
231
+ disable_self_attn=False):
232
+ super().__init__()
233
+ self.in_channels = in_channels
234
+ inner_dim = n_heads * d_head
235
+ self.norm = Normalize(in_channels)
236
+
237
+ self.proj_in = nn.Conv2d(in_channels,
238
+ inner_dim,
239
+ kernel_size=1,
240
+ stride=1,
241
+ padding=0)
242
+
243
+ self.transformer_blocks = nn.ModuleList(
244
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim,
245
+ disable_self_attn=disable_self_attn)
246
+ for d in range(depth)]
247
+ )
248
+
249
+ self.proj_out = zero_module(nn.Conv2d(inner_dim,
250
+ in_channels,
251
+ kernel_size=1,
252
+ stride=1,
253
+ padding=0))
254
+
255
+ def forward(self, x, context=None):
256
+ # note: if no context is given, cross-attention defaults to self-attention
257
+ b, c, h, w = x.shape
258
+ x_in = x
259
+ x = self.norm(x)
260
+ x = self.proj_in(x)
261
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
262
+ for block in self.transformer_blocks:
263
+ x = block(x, context=context)
264
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
265
+ x = self.proj_out(x)
266
+ return x + x_in
267
+
268
+
269
+ ##########################
270
+ # transformer no context #
271
+ ##########################
272
+
273
+ class BasicTransformerBlockNoContext(nn.Module):
274
+ def __init__(self, dim, n_heads, d_head, dropout=0., gated_ff=True, checkpoint=True):
275
+ super().__init__()
276
+ self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head,
277
+ dropout=dropout, context_dim=None)
278
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
279
+ self.attn2 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head,
280
+ dropout=dropout, context_dim=None)
281
+ self.norm1 = nn.LayerNorm(dim)
282
+ self.norm2 = nn.LayerNorm(dim)
283
+ self.norm3 = nn.LayerNorm(dim)
284
+ self.checkpoint = checkpoint
285
+
286
+ def forward(self, x):
287
+ return checkpoint(self._forward, (x,), self.parameters(), self.checkpoint)
288
+
289
+ def _forward(self, x):
290
+ x = self.attn1(self.norm1(x)) + x
291
+ x = self.attn2(self.norm2(x)) + x
292
+ x = self.ff(self.norm3(x)) + x
293
+ return x
294
+
295
+ class SpatialTransformerNoContext(nn.Module):
296
+ """
297
+ Transformer block for image-like data.
298
+ First, project the input (aka embedding)
299
+ and reshape to b, t, d.
300
+ Then apply standard transformer action.
301
+ Finally, reshape to image
302
+ """
303
+ def __init__(self, in_channels, n_heads, d_head,
304
+ depth=1, dropout=0.,):
305
+ super().__init__()
306
+ self.in_channels = in_channels
307
+ inner_dim = n_heads * d_head
308
+ self.norm = Normalize(in_channels)
309
+
310
+ self.proj_in = nn.Conv2d(in_channels,
311
+ inner_dim,
312
+ kernel_size=1,
313
+ stride=1,
314
+ padding=0)
315
+
316
+ self.transformer_blocks = nn.ModuleList(
317
+ [BasicTransformerBlockNoContext(inner_dim, n_heads, d_head, dropout=dropout)
318
+ for d in range(depth)]
319
+ )
320
+
321
+ self.proj_out = zero_module(nn.Conv2d(inner_dim,
322
+ in_channels,
323
+ kernel_size=1,
324
+ stride=1,
325
+ padding=0))
326
+
327
+ def forward(self, x):
328
+ # note: if no context is given, cross-attention defaults to self-attention
329
+ b, c, h, w = x.shape
330
+ x_in = x
331
+ x = self.norm(x)
332
+ x = self.proj_in(x)
333
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
334
+ for block in self.transformer_blocks:
335
+ x = block(x)
336
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
337
+ x = self.proj_out(x)
338
+ return x + x_in
339
+
340
+
341
+ #######################################
342
+ # Spatial Transformer with Two Branch #
343
+ #######################################
344
+
345
+ class DualSpatialTransformer(nn.Module):
346
+ def __init__(self, in_channels, n_heads, d_head,
347
+ depth=1, dropout=0., context_dim=None,
348
+ disable_self_attn=False):
349
+ super().__init__()
350
+ self.in_channels = in_channels
351
+ inner_dim = n_heads * d_head
352
+
353
+ # First crossattn
354
+ self.norm_0 = Normalize(in_channels)
355
+ self.proj_in_0 = nn.Conv2d(
356
+ in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
357
+ self.transformer_blocks_0 = nn.ModuleList(
358
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim,
359
+ disable_self_attn=disable_self_attn)
360
+ for d in range(depth)]
361
+ )
362
+ self.proj_out_0 = zero_module(nn.Conv2d(
363
+ inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
364
+
365
+ # Second crossattn
366
+ self.norm_1 = Normalize(in_channels)
367
+ self.proj_in_1 = nn.Conv2d(
368
+ in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
369
+ self.transformer_blocks_1 = nn.ModuleList(
370
+ [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim,
371
+ disable_self_attn=disable_self_attn)
372
+ for d in range(depth)]
373
+ )
374
+ self.proj_out_1 = zero_module(nn.Conv2d(
375
+ inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
376
+
377
+ def forward(self, x, context=None, which=None):
378
+ # note: if no context is given, cross-attention defaults to self-attention
379
+ b, c, h, w = x.shape
380
+ x_in = x
381
+ if which==0:
382
+ norm, proj_in, blocks, proj_out = \
383
+ self.norm_0, self.proj_in_0, self.transformer_blocks_0, self.proj_out_0
384
+ elif which==1:
385
+ norm, proj_in, blocks, proj_out = \
386
+ self.norm_1, self.proj_in_1, self.transformer_blocks_1, self.proj_out_1
387
+ else:
388
+ # assert False, 'DualSpatialTransformer forward with a invalid which branch!'
389
+ # import numpy.random as npr
390
+ # rwhich = 0 if npr.rand() < which else 1
391
+ # context = context[rwhich]
392
+ # if rwhich==0:
393
+ # norm, proj_in, blocks, proj_out = \
394
+ # self.norm_0, self.proj_in_0, self.transformer_blocks_0, self.proj_out_0
395
+ # elif rwhich==1:
396
+ # norm, proj_in, blocks, proj_out = \
397
+ # self.norm_1, self.proj_in_1, self.transformer_blocks_1, self.proj_out_1
398
+
399
+ # import numpy.random as npr
400
+ # rwhich = 0 if npr.rand() < 0.33 else 1
401
+ # if rwhich==0:
402
+ # context = context[rwhich]
403
+ # norm, proj_in, blocks, proj_out = \
404
+ # self.norm_0, self.proj_in_0, self.transformer_blocks_0, self.proj_out_0
405
+ # else:
406
+
407
+ norm, proj_in, blocks, proj_out = \
408
+ self.norm_0, self.proj_in_0, self.transformer_blocks_0, self.proj_out_0
409
+ x0 = norm(x)
410
+ x0 = proj_in(x0)
411
+ x0 = rearrange(x0, 'b c h w -> b (h w) c').contiguous()
412
+ for block in blocks:
413
+ x0 = block(x0, context=context[0])
414
+ x0 = rearrange(x0, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
415
+ x0 = proj_out(x0)
416
+
417
+ norm, proj_in, blocks, proj_out = \
418
+ self.norm_1, self.proj_in_1, self.transformer_blocks_1, self.proj_out_1
419
+ x1 = norm(x)
420
+ x1 = proj_in(x1)
421
+ x1 = rearrange(x1, 'b c h w -> b (h w) c').contiguous()
422
+ for block in blocks:
423
+ x1 = block(x1, context=context[1])
424
+ x1 = rearrange(x1, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
425
+ x1 = proj_out(x1)
426
+ return x0*which + x1*(1-which) + x_in
427
+
428
+ x = norm(x)
429
+ x = proj_in(x)
430
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
431
+ for block in blocks:
432
+ x = block(x, context=context)
433
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
434
+ x = proj_out(x)
435
+ return x + x_in
lib/model_zoo/autoencoder.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from contextlib import contextmanager
5
+ from lib.model_zoo.common.get_model import get_model, register
6
+
7
+ from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
8
+
9
+ from .diffusion_modules import Encoder, Decoder
10
+ from .distributions import DiagonalGaussianDistribution
11
+
12
+
13
+ class VQModel(nn.Module):
14
+ def __init__(self,
15
+ ddconfig,
16
+ lossconfig,
17
+ n_embed,
18
+ embed_dim,
19
+ ckpt_path=None,
20
+ ignore_keys=[],
21
+ image_key="image",
22
+ colorize_nlabels=None,
23
+ monitor=None,
24
+ batch_resize_range=None,
25
+ scheduler_config=None,
26
+ lr_g_factor=1.0,
27
+ remap=None,
28
+ sane_index_shape=False, # tell vector quantizer to return indices as bhw
29
+ use_ema=False
30
+ ):
31
+ super().__init__()
32
+ self.embed_dim = embed_dim
33
+ self.n_embed = n_embed
34
+ self.image_key = image_key
35
+ self.encoder = Encoder(**ddconfig)
36
+ self.decoder = Decoder(**ddconfig)
37
+ self.loss = instantiate_from_config(lossconfig)
38
+ self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
39
+ remap=remap,
40
+ sane_index_shape=sane_index_shape)
41
+ self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
42
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
43
+ if colorize_nlabels is not None:
44
+ assert type(colorize_nlabels)==int
45
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
46
+ if monitor is not None:
47
+ self.monitor = monitor
48
+ self.batch_resize_range = batch_resize_range
49
+ if self.batch_resize_range is not None:
50
+ print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
51
+
52
+ self.use_ema = use_ema
53
+ if self.use_ema:
54
+ self.model_ema = LitEma(self)
55
+ print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
56
+
57
+ if ckpt_path is not None:
58
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
59
+ self.scheduler_config = scheduler_config
60
+ self.lr_g_factor = lr_g_factor
61
+
62
+ @contextmanager
63
+ def ema_scope(self, context=None):
64
+ if self.use_ema:
65
+ self.model_ema.store(self.parameters())
66
+ self.model_ema.copy_to(self)
67
+ if context is not None:
68
+ print(f"{context}: Switched to EMA weights")
69
+ try:
70
+ yield None
71
+ finally:
72
+ if self.use_ema:
73
+ self.model_ema.restore(self.parameters())
74
+ if context is not None:
75
+ print(f"{context}: Restored training weights")
76
+
77
+ def init_from_ckpt(self, path, ignore_keys=list()):
78
+ sd = torch.load(path, map_location="cpu")["state_dict"]
79
+ keys = list(sd.keys())
80
+ for k in keys:
81
+ for ik in ignore_keys:
82
+ if k.startswith(ik):
83
+ print("Deleting key {} from state_dict.".format(k))
84
+ del sd[k]
85
+ missing, unexpected = self.load_state_dict(sd, strict=False)
86
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
87
+ if len(missing) > 0:
88
+ print(f"Missing Keys: {missing}")
89
+ print(f"Unexpected Keys: {unexpected}")
90
+
91
+ def on_train_batch_end(self, *args, **kwargs):
92
+ if self.use_ema:
93
+ self.model_ema(self)
94
+
95
+ def encode(self, x):
96
+ h = self.encoder(x)
97
+ h = self.quant_conv(h)
98
+ quant, emb_loss, info = self.quantize(h)
99
+ return quant, emb_loss, info
100
+
101
+ def encode_to_prequant(self, x):
102
+ h = self.encoder(x)
103
+ h = self.quant_conv(h)
104
+ return h
105
+
106
+ def decode(self, quant):
107
+ quant = self.post_quant_conv(quant)
108
+ dec = self.decoder(quant)
109
+ return dec
110
+
111
+ def decode_code(self, code_b):
112
+ quant_b = self.quantize.embed_code(code_b)
113
+ dec = self.decode(quant_b)
114
+ return dec
115
+
116
+ def forward(self, input, return_pred_indices=False):
117
+ quant, diff, (_,_,ind) = self.encode(input)
118
+ dec = self.decode(quant)
119
+ if return_pred_indices:
120
+ return dec, diff, ind
121
+ return dec, diff
122
+
123
+ def get_input(self, batch, k):
124
+ x = batch[k]
125
+ if len(x.shape) == 3:
126
+ x = x[..., None]
127
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
128
+ if self.batch_resize_range is not None:
129
+ lower_size = self.batch_resize_range[0]
130
+ upper_size = self.batch_resize_range[1]
131
+ if self.global_step <= 4:
132
+ # do the first few batches with max size to avoid later oom
133
+ new_resize = upper_size
134
+ else:
135
+ new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
136
+ if new_resize != x.shape[2]:
137
+ x = F.interpolate(x, size=new_resize, mode="bicubic")
138
+ x = x.detach()
139
+ return x
140
+
141
+ def training_step(self, batch, batch_idx, optimizer_idx):
142
+ # https://github.com/pytorch/pytorch/issues/37142
143
+ # try not to fool the heuristics
144
+ x = self.get_input(batch, self.image_key)
145
+ xrec, qloss, ind = self(x, return_pred_indices=True)
146
+
147
+ if optimizer_idx == 0:
148
+ # autoencode
149
+ aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
150
+ last_layer=self.get_last_layer(), split="train",
151
+ predicted_indices=ind)
152
+
153
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
154
+ return aeloss
155
+
156
+ if optimizer_idx == 1:
157
+ # discriminator
158
+ discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
159
+ last_layer=self.get_last_layer(), split="train")
160
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
161
+ return discloss
162
+
163
+ def validation_step(self, batch, batch_idx):
164
+ log_dict = self._validation_step(batch, batch_idx)
165
+ with self.ema_scope():
166
+ log_dict_ema = self._validation_step(batch, batch_idx, suffix="_ema")
167
+ return log_dict
168
+
169
+ def _validation_step(self, batch, batch_idx, suffix=""):
170
+ x = self.get_input(batch, self.image_key)
171
+ xrec, qloss, ind = self(x, return_pred_indices=True)
172
+ aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
173
+ self.global_step,
174
+ last_layer=self.get_last_layer(),
175
+ split="val"+suffix,
176
+ predicted_indices=ind
177
+ )
178
+
179
+ discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
180
+ self.global_step,
181
+ last_layer=self.get_last_layer(),
182
+ split="val"+suffix,
183
+ predicted_indices=ind
184
+ )
185
+ rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
186
+ self.log(f"val{suffix}/rec_loss", rec_loss,
187
+ prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
188
+ self.log(f"val{suffix}/aeloss", aeloss,
189
+ prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
190
+ if version.parse(pl.__version__) >= version.parse('1.4.0'):
191
+ del log_dict_ae[f"val{suffix}/rec_loss"]
192
+ self.log_dict(log_dict_ae)
193
+ self.log_dict(log_dict_disc)
194
+ return self.log_dict
195
+
196
+ def configure_optimizers(self):
197
+ lr_d = self.learning_rate
198
+ lr_g = self.lr_g_factor*self.learning_rate
199
+ print("lr_d", lr_d)
200
+ print("lr_g", lr_g)
201
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
202
+ list(self.decoder.parameters())+
203
+ list(self.quantize.parameters())+
204
+ list(self.quant_conv.parameters())+
205
+ list(self.post_quant_conv.parameters()),
206
+ lr=lr_g, betas=(0.5, 0.9))
207
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
208
+ lr=lr_d, betas=(0.5, 0.9))
209
+
210
+ if self.scheduler_config is not None:
211
+ scheduler = instantiate_from_config(self.scheduler_config)
212
+
213
+ print("Setting up LambdaLR scheduler...")
214
+ scheduler = [
215
+ {
216
+ 'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
217
+ 'interval': 'step',
218
+ 'frequency': 1
219
+ },
220
+ {
221
+ 'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
222
+ 'interval': 'step',
223
+ 'frequency': 1
224
+ },
225
+ ]
226
+ return [opt_ae, opt_disc], scheduler
227
+ return [opt_ae, opt_disc], []
228
+
229
+ def get_last_layer(self):
230
+ return self.decoder.conv_out.weight
231
+
232
+ def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
233
+ log = dict()
234
+ x = self.get_input(batch, self.image_key)
235
+ x = x.to(self.device)
236
+ if only_inputs:
237
+ log["inputs"] = x
238
+ return log
239
+ xrec, _ = self(x)
240
+ if x.shape[1] > 3:
241
+ # colorize with random projection
242
+ assert xrec.shape[1] > 3
243
+ x = self.to_rgb(x)
244
+ xrec = self.to_rgb(xrec)
245
+ log["inputs"] = x
246
+ log["reconstructions"] = xrec
247
+ if plot_ema:
248
+ with self.ema_scope():
249
+ xrec_ema, _ = self(x)
250
+ if x.shape[1] > 3: xrec_ema = self.to_rgb(xrec_ema)
251
+ log["reconstructions_ema"] = xrec_ema
252
+ return log
253
+
254
+ def to_rgb(self, x):
255
+ assert self.image_key == "segmentation"
256
+ if not hasattr(self, "colorize"):
257
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
258
+ x = F.conv2d(x, weight=self.colorize)
259
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
260
+ return x
261
+
262
+
263
+ class VQModelInterface(VQModel):
264
+ def __init__(self, embed_dim, *args, **kwargs):
265
+ super().__init__(embed_dim=embed_dim, *args, **kwargs)
266
+ self.embed_dim = embed_dim
267
+
268
+ def encode(self, x):
269
+ h = self.encoder(x)
270
+ h = self.quant_conv(h)
271
+ return h
272
+
273
+ def decode(self, h, force_not_quantize=False):
274
+ # also go through quantization layer
275
+ if not force_not_quantize:
276
+ quant, emb_loss, info = self.quantize(h)
277
+ else:
278
+ quant = h
279
+ quant = self.post_quant_conv(quant)
280
+ dec = self.decoder(quant)
281
+ return dec
282
+
283
+
284
+ @register('autoencoderkl')
285
+ class AutoencoderKL(nn.Module):
286
+ def __init__(self,
287
+ ddconfig,
288
+ lossconfig,
289
+ embed_dim,
290
+ ckpt_path=None,
291
+ ignore_keys=[],
292
+ image_key="image",
293
+ colorize_nlabels=None,
294
+ monitor=None,):
295
+ super().__init__()
296
+ self.image_key = image_key
297
+ self.encoder = Encoder(**ddconfig)
298
+ self.decoder = Decoder(**ddconfig)
299
+ assert ddconfig["double_z"]
300
+ self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
301
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
302
+ self.embed_dim = embed_dim
303
+ if colorize_nlabels is not None:
304
+ assert type(colorize_nlabels)==int
305
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
306
+ if monitor is not None:
307
+ self.monitor = monitor
308
+
309
+ def encode(self, x):
310
+ h = self.encoder(x)
311
+ moments = self.quant_conv(h)
312
+ posterior = DiagonalGaussianDistribution(moments)
313
+ return posterior
314
+
315
+ def decode(self, z):
316
+ z = self.post_quant_conv(z)
317
+ dec = self.decoder(z)
318
+ return dec
319
+
320
+ def forward(self, input, sample_posterior=True):
321
+ posterior = self.encode(input)
322
+ if sample_posterior:
323
+ z = posterior.sample()
324
+ else:
325
+ z = posterior.mode()
326
+ dec = self.decode(z)
327
+ return dec, posterior
328
+
329
+ def get_input(self, batch, k):
330
+ x = batch[k]
331
+ if len(x.shape) == 3:
332
+ x = x[..., None]
333
+ x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
334
+ return x
335
+
336
+ def training_step(self, batch, batch_idx, optimizer_idx):
337
+ inputs = self.get_input(batch, self.image_key)
338
+ reconstructions, posterior = self(inputs)
339
+
340
+ if optimizer_idx == 0:
341
+ # train encoder+decoder+logvar
342
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
343
+ last_layer=self.get_last_layer(), split="train")
344
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
345
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
346
+ return aeloss
347
+
348
+ if optimizer_idx == 1:
349
+ # train the discriminator
350
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
351
+ last_layer=self.get_last_layer(), split="train")
352
+
353
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
354
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
355
+ return discloss
356
+
357
+ def validation_step(self, batch, batch_idx):
358
+ inputs = self.get_input(batch, self.image_key)
359
+ reconstructions, posterior = self(inputs)
360
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
361
+ last_layer=self.get_last_layer(), split="val")
362
+
363
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
364
+ last_layer=self.get_last_layer(), split="val")
365
+
366
+ self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
367
+ self.log_dict(log_dict_ae)
368
+ self.log_dict(log_dict_disc)
369
+ return self.log_dict
370
+
371
+ def configure_optimizers(self):
372
+ lr = self.learning_rate
373
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
374
+ list(self.decoder.parameters())+
375
+ list(self.quant_conv.parameters())+
376
+ list(self.post_quant_conv.parameters()),
377
+ lr=lr, betas=(0.5, 0.9))
378
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
379
+ lr=lr, betas=(0.5, 0.9))
380
+ return [opt_ae, opt_disc], []
381
+
382
+ def get_last_layer(self):
383
+ return self.decoder.conv_out.weight
384
+
385
+ @torch.no_grad()
386
+ def log_images(self, batch, only_inputs=False, **kwargs):
387
+ log = dict()
388
+ x = self.get_input(batch, self.image_key)
389
+ x = x.to(self.device)
390
+ if not only_inputs:
391
+ xrec, posterior = self(x)
392
+ if x.shape[1] > 3:
393
+ # colorize with random projection
394
+ assert xrec.shape[1] > 3
395
+ x = self.to_rgb(x)
396
+ xrec = self.to_rgb(xrec)
397
+ log["samples"] = self.decode(torch.randn_like(posterior.sample()))
398
+ log["reconstructions"] = xrec
399
+ log["inputs"] = x
400
+ return log
401
+
402
+ def to_rgb(self, x):
403
+ assert self.image_key == "segmentation"
404
+ if not hasattr(self, "colorize"):
405
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
406
+ x = F.conv2d(x, weight=self.colorize)
407
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
408
+ return x
409
+
410
+
411
+ class IdentityFirstStage(nn.Module):
412
+ def __init__(self, *args, vq_interface=False, **kwargs):
413
+ self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
414
+ super().__init__()
415
+
416
+ def encode(self, x, *args, **kwargs):
417
+ return x
418
+
419
+ def decode(self, x, *args, **kwargs):
420
+ return x
421
+
422
+ def quantize(self, x, *args, **kwargs):
423
+ if self.vq_interface:
424
+ return x, None, [None, None, None]
425
+ return x
426
+
427
+ def forward(self, x, *args, **kwargs):
428
+ return x
lib/model_zoo/bert.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from functools import partial
4
+
5
+ # from ldm.modules.x_transformer import Encoder, TransformerWrapper # TODO: can we directly rely on lucidrains code and simply add this as a reuirement? --> test
6
+
7
+
8
+ class AbstractEncoder(nn.Module):
9
+ def __init__(self):
10
+ super().__init__()
11
+
12
+ def encode(self, *args, **kwargs):
13
+ raise NotImplementedError
14
+
15
+
16
+
17
+ class ClassEmbedder(nn.Module):
18
+ def __init__(self, embed_dim, n_classes=1000, key='class'):
19
+ super().__init__()
20
+ self.key = key
21
+ self.embedding = nn.Embedding(n_classes, embed_dim)
22
+
23
+ def forward(self, batch, key=None):
24
+ if key is None:
25
+ key = self.key
26
+ # this is for use in crossattn
27
+ c = batch[key][:, None]
28
+ c = self.embedding(c)
29
+ return c
30
+
31
+
32
+ class TransformerEmbedder(AbstractEncoder):
33
+ """Some transformer encoder layers"""
34
+ def __init__(self, n_embed, n_layer, vocab_size, max_seq_len=77):
35
+ super().__init__()
36
+ self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len,
37
+ attn_layers=Encoder(dim=n_embed, depth=n_layer))
38
+
39
+ def forward(self, tokens):
40
+ z = self.transformer(tokens, return_embeddings=True)
41
+ return z
42
+
43
+ def encode(self, x):
44
+ return self(x)
45
+
46
+
47
+ class BERTTokenizer(AbstractEncoder):
48
+ """ Uses a pretrained BERT tokenizer by huggingface. Vocab size: 30522 (?)"""
49
+ def __init__(self, device="cuda", vq_interface=True, max_length=77):
50
+ super().__init__()
51
+ from transformers import BertTokenizerFast # TODO: add to reuquirements
52
+ self.tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased")
53
+ self.vq_interface = vq_interface
54
+ self.max_length = max_length
55
+
56
+ def forward(self, text):
57
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
58
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
59
+ tokens = batch_encoding["input_ids"]
60
+ return tokens
61
+
62
+ @torch.no_grad()
63
+ def encode(self, text):
64
+ tokens = self(text)
65
+ if not self.vq_interface:
66
+ return tokens
67
+ return None, None, [None, None, tokens]
68
+
69
+ def decode(self, text):
70
+ return text
71
+
72
+
73
+ class BERTEmbedder(AbstractEncoder):
74
+ """Uses the BERT tokenizr model and add some transformer encoder layers"""
75
+ def __init__(self, n_embed, n_layer, vocab_size=30522, max_seq_len=77,
76
+ ckpt_path=None, ignore_keys=[], device="cuda", use_tokenizer=True, embedding_dropout=0.0):
77
+ super().__init__()
78
+ self.use_tknz_fn = use_tokenizer
79
+ if self.use_tknz_fn:
80
+ self.tknz_fn = BERTTokenizer(vq_interface=False, max_length=max_seq_len)
81
+ self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len,
82
+ attn_layers=Encoder(dim=n_embed, depth=n_layer),
83
+ emb_dropout=embedding_dropout)
84
+ if ckpt_path is not None:
85
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
86
+
87
+ def init_from_ckpt(self, path, ignore_keys=list()):
88
+ sd = torch.load(path, map_location="cpu")
89
+ keys = list(sd.keys())
90
+ for k in keys:
91
+ for ik in ignore_keys:
92
+ if k.startswith(ik):
93
+ print("Deleting key {} from state_dict.".format(k))
94
+ del sd[k]
95
+ missing, unexpected = self.load_state_dict(sd, strict=False)
96
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
97
+
98
+ def forward(self, text):
99
+ if self.use_tknz_fn:
100
+ tokens = self.tknz_fn(text)
101
+ else:
102
+ tokens = text
103
+ device = self.transformer.token_emb.weight.device # a trick to get device
104
+ tokens = tokens.to(device)
105
+ z = self.transformer(tokens, return_embeddings=True)
106
+ return z
107
+
108
+ def encode(self, text):
109
+ # output of length 77
110
+ return self(text)
111
+
112
+
113
+ class SpatialRescaler(nn.Module):
114
+ def __init__(self,
115
+ n_stages=1,
116
+ method='bilinear',
117
+ multiplier=0.5,
118
+ in_channels=3,
119
+ out_channels=None,
120
+ bias=False):
121
+ super().__init__()
122
+ self.n_stages = n_stages
123
+ assert self.n_stages >= 0
124
+ assert method in ['nearest','linear','bilinear','trilinear','bicubic','area']
125
+ self.multiplier = multiplier
126
+ self.interpolator = partial(torch.nn.functional.interpolate, mode=method)
127
+ self.remap_output = out_channels is not None
128
+ if self.remap_output:
129
+ print(f'Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing.')
130
+ self.channel_mapper = nn.Conv2d(in_channels,out_channels,1,bias=bias)
131
+
132
+ def forward(self,x):
133
+ for stage in range(self.n_stages):
134
+ x = self.interpolator(x, scale_factor=self.multiplier)
135
+
136
+
137
+ if self.remap_output:
138
+ x = self.channel_mapper(x)
139
+ return x
140
+
141
+ def encode(self, x):
142
+ return self(x)
lib/model_zoo/clip.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from functools import partial
5
+ from lib.model_zoo.common.get_model import register
6
+
7
+ version = '0'
8
+ symbol = 'clip'
9
+
10
+ class AbstractEncoder(nn.Module):
11
+ def __init__(self):
12
+ super().__init__()
13
+
14
+ def encode(self, *args, **kwargs):
15
+ raise NotImplementedError
16
+
17
+ from transformers import CLIPTokenizer, CLIPTextModel
18
+
19
+ def disabled_train(self, mode=True):
20
+ """Overwrite model.train with this function to make sure train/eval mode
21
+ does not change anymore."""
22
+ return self
23
+
24
+ @register('clip_text_frozen', version)
25
+ class FrozenCLIPTextEmbedder(AbstractEncoder):
26
+ """Uses the CLIP transformer encoder for text (from huggingface)"""
27
+ def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77): # clip-vit-base-patch32
28
+ super().__init__()
29
+ self.tokenizer = CLIPTokenizer.from_pretrained(version)
30
+ self.transformer = CLIPTextModel.from_pretrained(version)
31
+ self.device = device
32
+ self.max_length = max_length # TODO: typical value?
33
+ self.freeze()
34
+
35
+ def freeze(self):
36
+ self.transformer = self.transformer.eval()
37
+ #self.train = disabled_train
38
+ for param in self.parameters():
39
+ param.requires_grad = False
40
+
41
+ def forward(self, text):
42
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
43
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
44
+ tokens = batch_encoding["input_ids"].to(self.device)
45
+ outputs = self.transformer(input_ids=tokens)
46
+ z = outputs.last_hidden_state
47
+ return z
48
+
49
+ def encode(self, text):
50
+ return self(text)
51
+
52
+ from transformers import CLIPProcessor, CLIPVisionModel
53
+
54
+ @register('clip_vision_frozen', version)
55
+ class FrozenCLIPVisionEmbedder(AbstractEncoder):
56
+ def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77): # clip-vit-base-patch32
57
+ super().__init__()
58
+ self.processor = CLIPProcessor.from_pretrained(version)
59
+ self.transformer = CLIPVisionModel.from_pretrained(version)
60
+ self.device = device
61
+ self.max_length = max_length # TODO: typical value?
62
+ self.freeze()
63
+
64
+ def freeze(self):
65
+ self.transformer = self.transformer.eval()
66
+ #self.train = disabled_train
67
+ for param in self.parameters():
68
+ param.requires_grad = False
69
+
70
+ def forward(self, images):
71
+ inputs = self.processor(images=images, return_tensors="pt")
72
+ pixels = inputs['pixel_values'].to(self.device)
73
+ outputs = self.transformer(pixel_values=pixels)
74
+ z = outputs.last_hidden_state
75
+ return z
76
+
77
+ def encode(self, image):
78
+ return self(image)
79
+
80
+ from transformers import CLIPModel
81
+
82
+ @register('clip_frozen', version)
83
+ class FrozenCLIP(AbstractEncoder):
84
+ def __init__(self,
85
+ version="openai/clip-vit-large-patch14",
86
+ max_length=77,
87
+ encode_type='encode_text',): # clip-vit-base-patch32
88
+ super().__init__()
89
+ self.tokenizer = CLIPTokenizer.from_pretrained(version)
90
+ self.processor = CLIPProcessor.from_pretrained(version)
91
+ self.model = CLIPModel.from_pretrained(version)
92
+ self.max_length = max_length # TODO: typical value?
93
+ self.encode_type = encode_type
94
+ self.pinv_text_projection = None
95
+ self.freeze()
96
+
97
+ def get_device(self):
98
+ # A trick to get device
99
+ return self.model.text_projection.weight.device
100
+
101
+ def freeze(self):
102
+ self.model = self.model.eval()
103
+ #self.train = disabled_train
104
+ for param in self.parameters():
105
+ param.requires_grad = False
106
+
107
+ def encode_text_pooled(self, text):
108
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
109
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
110
+ tokens = batch_encoding["input_ids"].to(self.get_device())
111
+ return self.model.get_text_features(input_ids=tokens)
112
+
113
+ def encode_vision_pooled(self, images):
114
+ inputs = self.processor(images=images, return_tensors="pt")
115
+ pixels = inputs['pixel_values'].to(self.get_device())
116
+ return self.model.get_image_features(pixel_values=pixels)
117
+
118
+ def encode_text_noproj(self, text):
119
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
120
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
121
+ tokens = batch_encoding["input_ids"].to(self.get_device())
122
+ outputs = self.model.text_model(input_ids=tokens)
123
+ return outputs.last_hidden_state
124
+
125
+ def encode_vision_noproj(self, images):
126
+ inputs = self.processor(images=images, return_tensors="pt")
127
+ pixels = inputs['pixel_values'].to(self.get_device())
128
+ outputs = self.model.vision_model(pixel_values=pixels)
129
+ return outputs.last_hidden_state
130
+
131
+ def encode_text_bug(self, text):
132
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
133
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
134
+ tokens = batch_encoding["input_ids"].to(self.get_device())
135
+ outputs = self.model.text_model(input_ids=tokens)
136
+ z = outputs.last_hidden_state
137
+ z_pooled = outputs.pooler_output
138
+ z = z / torch.norm(z_pooled.unsqueeze(1), dim=-1, keepdim=True)
139
+ return self.model.text_projection(z)
140
+
141
+ def encode_text(self, text):
142
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
143
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
144
+ tokens = batch_encoding["input_ids"].to(self.get_device())
145
+ outputs = self.model.text_model(input_ids=tokens)
146
+ z = self.model.text_projection(outputs.last_hidden_state)
147
+ z_pooled = self.model.text_projection(outputs.pooler_output)
148
+ z = z / torch.norm(z_pooled.unsqueeze(1), dim=-1, keepdim=True)
149
+ return z
150
+
151
+ def encode_vision(self, images):
152
+ z = self.encode_vision_noproj(images)
153
+ z = self.model.vision_model.post_layernorm(z)
154
+ z = self.model.visual_projection(z)
155
+ z_pooled = z[:, 0:1]
156
+ # z_pooled_normed = z_pooled / z_pooled.norm(dim=-1, keepdim=True)
157
+ z = z / torch.norm(z_pooled, dim=-1, keepdim=True)
158
+ return z
159
+
160
+ def encode_vision_pinvtext(self, images):
161
+ blank_text_encode_norm_avg = 28.9096
162
+ z = self.encode_vision(images)
163
+ if self.pinv_text_projection is None:
164
+ self.pinv_text_projection = torch.linalg.pinv(self.model.text_projection.weight).T
165
+ z = torch.matmul(z, self.pinv_text_projection)
166
+ # z = z / torch.norm(z[:, 0:1], dim=-1, keepdim=True)
167
+ z = z / torch.norm(z, dim=-1, keepdim=True)
168
+ z = z*blank_text_encode_norm_avg
169
+ # return z[:, 1:2].repeat(1, 77, 1)
170
+ z2 = self.encode_text_noproj('')
171
+ # z2[:, 1:77] = z[:, 0:76]
172
+ return torch.flip(z, dims=(1,))[:, 0:77]
173
+
174
+ def encode(self, *args, **kwargs):
175
+ return getattr(self, self.encode_type)(*args, **kwargs)
176
+
177
+ #############################
178
+ # copyed from justin's code #
179
+ #############################
180
+
181
+ @register('clip_vision_frozen_justin', version)
182
+ class FrozenCLIPVisionEmbedder_Justin(AbstractEncoder):
183
+ """
184
+ Uses the CLIP image encoder.
185
+ """
186
+ def __init__(
187
+ self,
188
+ model='ViT-L/14',
189
+ jit=False,
190
+ device='cuda' if torch.cuda.is_available() else 'cpu',
191
+ antialias=False,
192
+ ):
193
+ super().__init__()
194
+ from . import clip_justin
195
+ self.model, _ = clip_justin.load(name=model, device=device, jit=jit)
196
+ self.device = device
197
+ self.antialias = antialias
198
+
199
+ self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
200
+ self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
201
+
202
+ # I didn't call this originally, but seems like it was frozen anyway
203
+ self.freeze()
204
+
205
+ def freeze(self):
206
+ self.transformer = self.model.eval()
207
+ for param in self.parameters():
208
+ param.requires_grad = False
209
+
210
+ def preprocess(self, x):
211
+ import kornia
212
+ # Expects inputs in the range -1, 1
213
+ x = kornia.geometry.resize(x, (224, 224),
214
+ interpolation='bicubic',align_corners=True,
215
+ antialias=self.antialias)
216
+ x = (x + 1.) / 2.
217
+ # renormalize according to clip
218
+ x = kornia.enhance.normalize(x, self.mean, self.std)
219
+ return x
220
+
221
+ def forward(self, x):
222
+ # x is assumed to be in range [-1,1]
223
+ return self.model.encode_image(self.preprocess(x)).float()
224
+
225
+ def encode(self, im):
226
+ return self(im).unsqueeze(1)
lib/model_zoo/clip_justin/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .clip import load
lib/model_zoo/clip_justin/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
lib/model_zoo/clip_justin/model.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ return self.resblocks(x)
204
+
205
+
206
+ class VisionTransformer(nn.Module):
207
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
208
+ super().__init__()
209
+ self.input_resolution = input_resolution
210
+ self.output_dim = output_dim
211
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
212
+
213
+ scale = width ** -0.5
214
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
215
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
216
+ self.ln_pre = LayerNorm(width)
217
+
218
+ self.transformer = Transformer(width, layers, heads)
219
+
220
+ self.ln_post = LayerNorm(width)
221
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
222
+
223
+ def forward(self, x: torch.Tensor):
224
+ x = self.conv1(x) # shape = [*, width, grid, grid]
225
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
226
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
227
+ 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]
228
+ x = x + self.positional_embedding.to(x.dtype)
229
+ x = self.ln_pre(x)
230
+
231
+ x = x.permute(1, 0, 2) # NLD -> LND
232
+ x = self.transformer(x)
233
+ x = x.permute(1, 0, 2) # LND -> NLD
234
+
235
+ x = self.ln_post(x[:, 0, :])
236
+
237
+ if self.proj is not None:
238
+ x = x @ self.proj
239
+
240
+ return x
241
+
242
+
243
+ class CLIP(nn.Module):
244
+ def __init__(self,
245
+ embed_dim: int,
246
+ # vision
247
+ image_resolution: int,
248
+ vision_layers: Union[Tuple[int, int, int, int], int],
249
+ vision_width: int,
250
+ vision_patch_size: int,
251
+ # text
252
+ context_length: int,
253
+ vocab_size: int,
254
+ transformer_width: int,
255
+ transformer_heads: int,
256
+ transformer_layers: int
257
+ ):
258
+ super().__init__()
259
+
260
+ self.context_length = context_length
261
+
262
+ if isinstance(vision_layers, (tuple, list)):
263
+ vision_heads = vision_width * 32 // 64
264
+ self.visual = ModifiedResNet(
265
+ layers=vision_layers,
266
+ output_dim=embed_dim,
267
+ heads=vision_heads,
268
+ input_resolution=image_resolution,
269
+ width=vision_width
270
+ )
271
+ else:
272
+ vision_heads = vision_width // 64
273
+ self.visual = VisionTransformer(
274
+ input_resolution=image_resolution,
275
+ patch_size=vision_patch_size,
276
+ width=vision_width,
277
+ layers=vision_layers,
278
+ heads=vision_heads,
279
+ output_dim=embed_dim
280
+ )
281
+
282
+ self.transformer = Transformer(
283
+ width=transformer_width,
284
+ layers=transformer_layers,
285
+ heads=transformer_heads,
286
+ attn_mask=self.build_attention_mask()
287
+ )
288
+
289
+ self.vocab_size = vocab_size
290
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
291
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
292
+ self.ln_final = LayerNorm(transformer_width)
293
+
294
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
295
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
296
+
297
+ self.initialize_parameters()
298
+
299
+ def initialize_parameters(self):
300
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
301
+ nn.init.normal_(self.positional_embedding, std=0.01)
302
+
303
+ if isinstance(self.visual, ModifiedResNet):
304
+ if self.visual.attnpool is not None:
305
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
306
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
307
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
308
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
309
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
310
+
311
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
312
+ for name, param in resnet_block.named_parameters():
313
+ if name.endswith("bn3.weight"):
314
+ nn.init.zeros_(param)
315
+
316
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
317
+ attn_std = self.transformer.width ** -0.5
318
+ fc_std = (2 * self.transformer.width) ** -0.5
319
+ for block in self.transformer.resblocks:
320
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
321
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
322
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
323
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
324
+
325
+ if self.text_projection is not None:
326
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
327
+
328
+ def build_attention_mask(self):
329
+ # lazily create causal attention mask, with full attention between the vision tokens
330
+ # pytorch uses additive attention mask; fill with -inf
331
+ mask = torch.empty(self.context_length, self.context_length)
332
+ mask.fill_(float("-inf"))
333
+ mask.triu_(1) # zero out the lower diagonal
334
+ return mask
335
+
336
+ @property
337
+ def dtype(self):
338
+ return self.visual.conv1.weight.dtype
339
+
340
+ def encode_image(self, image):
341
+ return self.visual(image.type(self.dtype))
342
+
343
+ def encode_text(self, text):
344
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
345
+
346
+ x = x + self.positional_embedding.type(self.dtype)
347
+ x = x.permute(1, 0, 2) # NLD -> LND
348
+ x = self.transformer(x)
349
+ x = x.permute(1, 0, 2) # LND -> NLD
350
+ x = self.ln_final(x).type(self.dtype)
351
+
352
+ # x.shape = [batch_size, n_ctx, transformer.width]
353
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
354
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
355
+
356
+ return x
357
+
358
+ def forward(self, image, text):
359
+ image_features = self.encode_image(image)
360
+ text_features = self.encode_text(text)
361
+
362
+ # normalized features
363
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
364
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
365
+
366
+ # cosine similarity as logits
367
+ logit_scale = self.logit_scale.exp()
368
+ logits_per_image = logit_scale * image_features @ text_features.t()
369
+ logits_per_text = logits_per_image.t()
370
+
371
+ # shape = [global_batch_size, global_batch_size]
372
+ return logits_per_image, logits_per_text
373
+
374
+
375
+ def convert_weights(model: nn.Module):
376
+ """Convert applicable model parameters to fp16"""
377
+
378
+ def _convert_weights_to_fp16(l):
379
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
380
+ l.weight.data = l.weight.data.half()
381
+ if l.bias is not None:
382
+ l.bias.data = l.bias.data.half()
383
+
384
+ if isinstance(l, nn.MultiheadAttention):
385
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
386
+ tensor = getattr(l, attr)
387
+ if tensor is not None:
388
+ tensor.data = tensor.data.half()
389
+
390
+ for name in ["text_projection", "proj"]:
391
+ if hasattr(l, name):
392
+ attr = getattr(l, name)
393
+ if attr is not None:
394
+ attr.data = attr.data.half()
395
+
396
+ model.apply(_convert_weights_to_fp16)
397
+
398
+
399
+ def build_model(state_dict: dict):
400
+ vit = "visual.proj" in state_dict
401
+
402
+ if vit:
403
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
404
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
405
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
406
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
407
+ image_resolution = vision_patch_size * grid_size
408
+ else:
409
+ 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]]
410
+ vision_layers = tuple(counts)
411
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
412
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
413
+ vision_patch_size = None
414
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
415
+ image_resolution = output_width * 32
416
+
417
+ embed_dim = state_dict["text_projection"].shape[1]
418
+ context_length = state_dict["positional_embedding"].shape[0]
419
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
420
+ transformer_width = state_dict["ln_final.weight"].shape[0]
421
+ transformer_heads = transformer_width // 64
422
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
423
+
424
+ model = CLIP(
425
+ embed_dim,
426
+ image_resolution, vision_layers, vision_width, vision_patch_size,
427
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
428
+ )
429
+
430
+ for key in ["input_resolution", "context_length", "vocab_size"]:
431
+ if key in state_dict:
432
+ del state_dict[key]
433
+
434
+ convert_weights(model)
435
+ model.load_state_dict(state_dict)
436
+ return model.eval()